fuzzershell.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. /*
  2. ** 2015-04-17
  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 the SQLite library
  14. ** against an external fuzzer, such as American Fuzzy Lop (AFL)
  15. ** (http://lcamtuf.coredump.cx/afl/). Basically, this program reads
  16. ** SQL text from standard input and passes it through to SQLite for evaluation,
  17. ** just like the "sqlite3" command-line shell. Differences from the
  18. ** command-line shell:
  19. **
  20. ** (1) The complex "dot-command" extensions are omitted. This
  21. ** prevents the fuzzer from discovering that it can run things
  22. ** like ".shell rm -rf ~"
  23. **
  24. ** (2) The database is opened with the SQLITE_OPEN_MEMORY flag so that
  25. ** no disk I/O from the database is permitted. The ATTACH command
  26. ** with a filename still uses an in-memory database.
  27. **
  28. ** (3) The main in-memory database can be initialized from a template
  29. ** disk database so that the fuzzer starts with a database containing
  30. ** content.
  31. **
  32. ** (4) The eval() SQL function is added, allowing the fuzzer to do
  33. ** interesting recursive operations.
  34. **
  35. ** (5) An error is raised if there is a memory leak.
  36. **
  37. ** The input text can be divided into separate test cases using comments
  38. ** of the form:
  39. **
  40. ** |****<...>****|
  41. **
  42. ** where the "..." is arbitrary text. (Except the "|" should really be "/".
  43. ** "|" is used here to avoid compiler errors about nested comments.)
  44. ** A separate in-memory SQLite database is created to run each test case.
  45. ** This feature allows the "queue" of AFL to be captured into a single big
  46. ** file using a command like this:
  47. **
  48. ** (for i in id:*; do echo '|****<'$i'>****|'; cat $i; done) >~/all-queue.txt
  49. **
  50. ** (Once again, change the "|" to "/") Then all elements of the AFL queue
  51. ** can be run in a single go (for regression testing, for example) by typing:
  52. **
  53. ** fuzzershell -f ~/all-queue.txt
  54. **
  55. ** After running each chunk of SQL, the database connection is closed. The
  56. ** program aborts if the close fails or if there is any unfreed memory after
  57. ** the close.
  58. **
  59. ** New test cases can be appended to all-queue.txt at any time. If redundant
  60. ** test cases are added, they can be eliminated by running:
  61. **
  62. ** fuzzershell -f ~/all-queue.txt --unique-cases ~/unique-cases.txt
  63. */
  64. #include <stdio.h>
  65. #include <stdlib.h>
  66. #include <string.h>
  67. #include <stdarg.h>
  68. #include <ctype.h>
  69. #include "sqlite3.h"
  70. #define ISDIGIT(X) isdigit((unsigned char)(X))
  71. /*
  72. ** All global variables are gathered into the "g" singleton.
  73. */
  74. struct GlobalVars {
  75. const char *zArgv0; /* Name of program */
  76. sqlite3_mem_methods sOrigMem; /* Original memory methods */
  77. sqlite3_mem_methods sOomMem; /* Memory methods with OOM simulator */
  78. int iOomCntdown; /* Memory fails on 1 to 0 transition */
  79. int nOomFault; /* Increments for each OOM fault */
  80. int bOomOnce; /* Fail just once if true */
  81. int bOomEnable; /* True to enable OOM simulation */
  82. int nOomBrkpt; /* Number of calls to oomFault() */
  83. char zTestName[100]; /* Name of current test */
  84. } g;
  85. /*
  86. ** Maximum number of iterations for an OOM test
  87. */
  88. #ifndef OOM_MAX
  89. # define OOM_MAX 625
  90. #endif
  91. /*
  92. ** This routine is called when a simulated OOM occurs. It exists as a
  93. ** convenient place to set a debugger breakpoint.
  94. */
  95. static void oomFault(void){
  96. g.nOomBrkpt++; /* Prevent oomFault() from being optimized out */
  97. }
  98. /* Versions of malloc() and realloc() that simulate OOM conditions */
  99. static void *oomMalloc(int nByte){
  100. if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
  101. g.iOomCntdown--;
  102. if( g.iOomCntdown==0 ){
  103. if( g.nOomFault==0 ) oomFault();
  104. g.nOomFault++;
  105. if( !g.bOomOnce ) g.iOomCntdown = 1;
  106. return 0;
  107. }
  108. }
  109. return g.sOrigMem.xMalloc(nByte);
  110. }
  111. static void *oomRealloc(void *pOld, int nByte){
  112. if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
  113. g.iOomCntdown--;
  114. if( g.iOomCntdown==0 ){
  115. if( g.nOomFault==0 ) oomFault();
  116. g.nOomFault++;
  117. if( !g.bOomOnce ) g.iOomCntdown = 1;
  118. return 0;
  119. }
  120. }
  121. return g.sOrigMem.xRealloc(pOld, nByte);
  122. }
  123. /*
  124. ** Print an error message and abort in such a way to indicate to the
  125. ** fuzzer that this counts as a crash.
  126. */
  127. static void abendError(const char *zFormat, ...){
  128. va_list ap;
  129. if( g.zTestName[0] ){
  130. fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
  131. }else{
  132. fprintf(stderr, "%s: ", g.zArgv0);
  133. }
  134. va_start(ap, zFormat);
  135. vfprintf(stderr, zFormat, ap);
  136. va_end(ap);
  137. fprintf(stderr, "\n");
  138. abort();
  139. }
  140. /*
  141. ** Print an error message and quit, but not in a way that would look
  142. ** like a crash.
  143. */
  144. static void fatalError(const char *zFormat, ...){
  145. va_list ap;
  146. if( g.zTestName[0] ){
  147. fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
  148. }else{
  149. fprintf(stderr, "%s: ", g.zArgv0);
  150. }
  151. va_start(ap, zFormat);
  152. vfprintf(stderr, zFormat, ap);
  153. va_end(ap);
  154. fprintf(stderr, "\n");
  155. exit(1);
  156. }
  157. /*
  158. ** Evaluate some SQL. Abort if unable.
  159. */
  160. static void sqlexec(sqlite3 *db, const char *zFormat, ...){
  161. va_list ap;
  162. char *zSql;
  163. char *zErrMsg = 0;
  164. int rc;
  165. va_start(ap, zFormat);
  166. zSql = sqlite3_vmprintf(zFormat, ap);
  167. va_end(ap);
  168. rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg);
  169. if( rc ) abendError("failed sql [%s]: %s", zSql, zErrMsg);
  170. sqlite3_free(zSql);
  171. }
  172. /*
  173. ** This callback is invoked by sqlite3_log().
  174. */
  175. static void shellLog(void *pNotUsed, int iErrCode, const char *zMsg){
  176. printf("LOG: (%d) %s\n", iErrCode, zMsg);
  177. fflush(stdout);
  178. }
  179. static void shellLogNoop(void *pNotUsed, int iErrCode, const char *zMsg){
  180. return;
  181. }
  182. /*
  183. ** This callback is invoked by sqlite3_exec() to return query results.
  184. */
  185. static int execCallback(void *NotUsed, int argc, char **argv, char **colv){
  186. int i;
  187. static unsigned cnt = 0;
  188. printf("ROW #%u:\n", ++cnt);
  189. if( argv ){
  190. for(i=0; i<argc; i++){
  191. printf(" %s=", colv[i]);
  192. if( argv[i] ){
  193. printf("[%s]\n", argv[i]);
  194. }else{
  195. printf("NULL\n");
  196. }
  197. }
  198. }
  199. fflush(stdout);
  200. return 0;
  201. }
  202. static int execNoop(void *NotUsed, int argc, char **argv, char **colv){
  203. return 0;
  204. }
  205. #ifndef SQLITE_OMIT_TRACE
  206. /*
  207. ** This callback is invoked by sqlite3_trace() as each SQL statement
  208. ** starts.
  209. */
  210. static void traceCallback(void *NotUsed, const char *zMsg){
  211. printf("TRACE: %s\n", zMsg);
  212. fflush(stdout);
  213. }
  214. static void traceNoop(void *NotUsed, const char *zMsg){
  215. return;
  216. }
  217. #endif
  218. /***************************************************************************
  219. ** String accumulator object
  220. */
  221. typedef struct Str Str;
  222. struct Str {
  223. char *z; /* The string. Memory from malloc() */
  224. sqlite3_uint64 n; /* Bytes of input used */
  225. sqlite3_uint64 nAlloc; /* Bytes allocated to z[] */
  226. int oomErr; /* OOM error has been seen */
  227. };
  228. /* Initialize a Str object */
  229. static void StrInit(Str *p){
  230. memset(p, 0, sizeof(*p));
  231. }
  232. /* Append text to the end of a Str object */
  233. static void StrAppend(Str *p, const char *z){
  234. sqlite3_uint64 n = strlen(z);
  235. if( p->n + n >= p->nAlloc ){
  236. char *zNew;
  237. sqlite3_uint64 nNew;
  238. if( p->oomErr ) return;
  239. nNew = p->nAlloc*2 + 100 + n;
  240. zNew = sqlite3_realloc(p->z, (int)nNew);
  241. if( zNew==0 ){
  242. sqlite3_free(p->z);
  243. memset(p, 0, sizeof(*p));
  244. p->oomErr = 1;
  245. return;
  246. }
  247. p->z = zNew;
  248. p->nAlloc = nNew;
  249. }
  250. memcpy(p->z + p->n, z, (size_t)n);
  251. p->n += n;
  252. p->z[p->n] = 0;
  253. }
  254. /* Return the current string content */
  255. static char *StrStr(Str *p){
  256. return p->z;
  257. }
  258. /* Free the string */
  259. static void StrFree(Str *p){
  260. sqlite3_free(p->z);
  261. StrInit(p);
  262. }
  263. /***************************************************************************
  264. ** eval() implementation copied from ../ext/misc/eval.c
  265. */
  266. /*
  267. ** Structure used to accumulate the output
  268. */
  269. struct EvalResult {
  270. char *z; /* Accumulated output */
  271. const char *zSep; /* Separator */
  272. int szSep; /* Size of the separator string */
  273. sqlite3_int64 nAlloc; /* Number of bytes allocated for z[] */
  274. sqlite3_int64 nUsed; /* Number of bytes of z[] actually used */
  275. };
  276. /*
  277. ** Callback from sqlite_exec() for the eval() function.
  278. */
  279. static int callback(void *pCtx, int argc, char **argv, char **colnames){
  280. struct EvalResult *p = (struct EvalResult*)pCtx;
  281. int i;
  282. for(i=0; i<argc; i++){
  283. const char *z = argv[i] ? argv[i] : "";
  284. size_t sz = strlen(z);
  285. if( (sqlite3_int64)sz+p->nUsed+p->szSep+1 > p->nAlloc ){
  286. char *zNew;
  287. p->nAlloc = p->nAlloc*2 + sz + p->szSep + 1;
  288. /* Using sqlite3_realloc64() would be better, but it is a recent
  289. ** addition and will cause a segfault if loaded by an older version
  290. ** of SQLite. */
  291. zNew = p->nAlloc<=0x7fffffff ? sqlite3_realloc(p->z, (int)p->nAlloc) : 0;
  292. if( zNew==0 ){
  293. sqlite3_free(p->z);
  294. memset(p, 0, sizeof(*p));
  295. return 1;
  296. }
  297. p->z = zNew;
  298. }
  299. if( p->nUsed>0 ){
  300. memcpy(&p->z[p->nUsed], p->zSep, p->szSep);
  301. p->nUsed += p->szSep;
  302. }
  303. memcpy(&p->z[p->nUsed], z, sz);
  304. p->nUsed += sz;
  305. }
  306. return 0;
  307. }
  308. /*
  309. ** Implementation of the eval(X) and eval(X,Y) SQL functions.
  310. **
  311. ** Evaluate the SQL text in X. Return the results, using string
  312. ** Y as the separator. If Y is omitted, use a single space character.
  313. */
  314. static void sqlEvalFunc(
  315. sqlite3_context *context,
  316. int argc,
  317. sqlite3_value **argv
  318. ){
  319. const char *zSql;
  320. sqlite3 *db;
  321. char *zErr = 0;
  322. int rc;
  323. struct EvalResult x;
  324. memset(&x, 0, sizeof(x));
  325. x.zSep = " ";
  326. zSql = (const char*)sqlite3_value_text(argv[0]);
  327. if( zSql==0 ) return;
  328. if( argc>1 ){
  329. x.zSep = (const char*)sqlite3_value_text(argv[1]);
  330. if( x.zSep==0 ) return;
  331. }
  332. x.szSep = (int)strlen(x.zSep);
  333. db = sqlite3_context_db_handle(context);
  334. rc = sqlite3_exec(db, zSql, callback, &x, &zErr);
  335. if( rc!=SQLITE_OK ){
  336. sqlite3_result_error(context, zErr, -1);
  337. sqlite3_free(zErr);
  338. }else if( x.zSep==0 ){
  339. sqlite3_result_error_nomem(context);
  340. sqlite3_free(x.z);
  341. }else{
  342. sqlite3_result_text(context, x.z, (int)x.nUsed, sqlite3_free);
  343. }
  344. }
  345. /* End of the eval() implementation
  346. ******************************************************************************/
  347. /******************************************************************************
  348. ** The generate_series(START,END,STEP) eponymous table-valued function.
  349. **
  350. ** This code is copy/pasted from ext/misc/series.c in the SQLite source tree.
  351. */
  352. /* series_cursor is a subclass of sqlite3_vtab_cursor which will
  353. ** serve as the underlying representation of a cursor that scans
  354. ** over rows of the result
  355. */
  356. typedef struct series_cursor series_cursor;
  357. struct series_cursor {
  358. sqlite3_vtab_cursor base; /* Base class - must be first */
  359. int isDesc; /* True to count down rather than up */
  360. sqlite3_int64 iRowid; /* The rowid */
  361. sqlite3_int64 iValue; /* Current value ("value") */
  362. sqlite3_int64 mnValue; /* Mimimum value ("start") */
  363. sqlite3_int64 mxValue; /* Maximum value ("stop") */
  364. sqlite3_int64 iStep; /* Increment ("step") */
  365. };
  366. /*
  367. ** The seriesConnect() method is invoked to create a new
  368. ** series_vtab that describes the generate_series virtual table.
  369. **
  370. ** Think of this routine as the constructor for series_vtab objects.
  371. **
  372. ** All this routine needs to do is:
  373. **
  374. ** (1) Allocate the series_vtab object and initialize all fields.
  375. **
  376. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  377. ** result set of queries against generate_series will look like.
  378. */
  379. static int seriesConnect(
  380. sqlite3 *db,
  381. void *pAux,
  382. int argc, const char *const*argv,
  383. sqlite3_vtab **ppVtab,
  384. char **pzErr
  385. ){
  386. sqlite3_vtab *pNew;
  387. int rc;
  388. /* Column numbers */
  389. #define SERIES_COLUMN_VALUE 0
  390. #define SERIES_COLUMN_START 1
  391. #define SERIES_COLUMN_STOP 2
  392. #define SERIES_COLUMN_STEP 3
  393. rc = sqlite3_declare_vtab(db,
  394. "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
  395. if( rc==SQLITE_OK ){
  396. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  397. if( pNew==0 ) return SQLITE_NOMEM;
  398. memset(pNew, 0, sizeof(*pNew));
  399. }
  400. return rc;
  401. }
  402. /*
  403. ** This method is the destructor for series_cursor objects.
  404. */
  405. static int seriesDisconnect(sqlite3_vtab *pVtab){
  406. sqlite3_free(pVtab);
  407. return SQLITE_OK;
  408. }
  409. /*
  410. ** Constructor for a new series_cursor object.
  411. */
  412. static int seriesOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  413. series_cursor *pCur;
  414. pCur = sqlite3_malloc( sizeof(*pCur) );
  415. if( pCur==0 ) return SQLITE_NOMEM;
  416. memset(pCur, 0, sizeof(*pCur));
  417. *ppCursor = &pCur->base;
  418. return SQLITE_OK;
  419. }
  420. /*
  421. ** Destructor for a series_cursor.
  422. */
  423. static int seriesClose(sqlite3_vtab_cursor *cur){
  424. sqlite3_free(cur);
  425. return SQLITE_OK;
  426. }
  427. /*
  428. ** Advance a series_cursor to its next row of output.
  429. */
  430. static int seriesNext(sqlite3_vtab_cursor *cur){
  431. series_cursor *pCur = (series_cursor*)cur;
  432. if( pCur->isDesc ){
  433. pCur->iValue -= pCur->iStep;
  434. }else{
  435. pCur->iValue += pCur->iStep;
  436. }
  437. pCur->iRowid++;
  438. return SQLITE_OK;
  439. }
  440. /*
  441. ** Return values of columns for the row at which the series_cursor
  442. ** is currently pointing.
  443. */
  444. static int seriesColumn(
  445. sqlite3_vtab_cursor *cur, /* The cursor */
  446. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  447. int i /* Which column to return */
  448. ){
  449. series_cursor *pCur = (series_cursor*)cur;
  450. sqlite3_int64 x = 0;
  451. switch( i ){
  452. case SERIES_COLUMN_START: x = pCur->mnValue; break;
  453. case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
  454. case SERIES_COLUMN_STEP: x = pCur->iStep; break;
  455. default: x = pCur->iValue; break;
  456. }
  457. sqlite3_result_int64(ctx, x);
  458. return SQLITE_OK;
  459. }
  460. /*
  461. ** Return the rowid for the current row. In this implementation, the
  462. ** rowid is the same as the output value.
  463. */
  464. static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  465. series_cursor *pCur = (series_cursor*)cur;
  466. *pRowid = pCur->iRowid;
  467. return SQLITE_OK;
  468. }
  469. /*
  470. ** Return TRUE if the cursor has been moved off of the last
  471. ** row of output.
  472. */
  473. static int seriesEof(sqlite3_vtab_cursor *cur){
  474. series_cursor *pCur = (series_cursor*)cur;
  475. if( pCur->isDesc ){
  476. return pCur->iValue < pCur->mnValue;
  477. }else{
  478. return pCur->iValue > pCur->mxValue;
  479. }
  480. }
  481. /* True to cause run-time checking of the start=, stop=, and/or step=
  482. ** parameters. The only reason to do this is for testing the
  483. ** constraint checking logic for virtual tables in the SQLite core.
  484. */
  485. #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
  486. # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
  487. #endif
  488. /*
  489. ** This method is called to "rewind" the series_cursor object back
  490. ** to the first row of output. This method is always called at least
  491. ** once prior to any call to seriesColumn() or seriesRowid() or
  492. ** seriesEof().
  493. **
  494. ** The query plan selected by seriesBestIndex is passed in the idxNum
  495. ** parameter. (idxStr is not used in this implementation.) idxNum
  496. ** is a bitmask showing which constraints are available:
  497. **
  498. ** 1: start=VALUE
  499. ** 2: stop=VALUE
  500. ** 4: step=VALUE
  501. **
  502. ** Also, if bit 8 is set, that means that the series should be output
  503. ** in descending order rather than in ascending order.
  504. **
  505. ** This routine should initialize the cursor and position it so that it
  506. ** is pointing at the first row, or pointing off the end of the table
  507. ** (so that seriesEof() will return true) if the table is empty.
  508. */
  509. static int seriesFilter(
  510. sqlite3_vtab_cursor *pVtabCursor,
  511. int idxNum, const char *idxStr,
  512. int argc, sqlite3_value **argv
  513. ){
  514. series_cursor *pCur = (series_cursor *)pVtabCursor;
  515. int i = 0;
  516. if( idxNum & 1 ){
  517. pCur->mnValue = sqlite3_value_int64(argv[i++]);
  518. }else{
  519. pCur->mnValue = 0;
  520. }
  521. if( idxNum & 2 ){
  522. pCur->mxValue = sqlite3_value_int64(argv[i++]);
  523. }else{
  524. pCur->mxValue = 0xffffffff;
  525. }
  526. if( idxNum & 4 ){
  527. pCur->iStep = sqlite3_value_int64(argv[i++]);
  528. if( pCur->iStep<1 ) pCur->iStep = 1;
  529. }else{
  530. pCur->iStep = 1;
  531. }
  532. if( idxNum & 8 ){
  533. pCur->isDesc = 1;
  534. pCur->iValue = pCur->mxValue;
  535. if( pCur->iStep>0 ){
  536. pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
  537. }
  538. }else{
  539. pCur->isDesc = 0;
  540. pCur->iValue = pCur->mnValue;
  541. }
  542. pCur->iRowid = 1;
  543. return SQLITE_OK;
  544. }
  545. /*
  546. ** SQLite will invoke this method one or more times while planning a query
  547. ** that uses the generate_series virtual table. This routine needs to create
  548. ** a query plan for each invocation and compute an estimated cost for that
  549. ** plan.
  550. **
  551. ** In this implementation idxNum is used to represent the
  552. ** query plan. idxStr is unused.
  553. **
  554. ** The query plan is represented by bits in idxNum:
  555. **
  556. ** (1) start = $value -- constraint exists
  557. ** (2) stop = $value -- constraint exists
  558. ** (4) step = $value -- constraint exists
  559. ** (8) output in descending order
  560. */
  561. static int seriesBestIndex(
  562. sqlite3_vtab *tab,
  563. sqlite3_index_info *pIdxInfo
  564. ){
  565. int i; /* Loop over constraints */
  566. int idxNum = 0; /* The query plan bitmask */
  567. int startIdx = -1; /* Index of the start= constraint, or -1 if none */
  568. int stopIdx = -1; /* Index of the stop= constraint, or -1 if none */
  569. int stepIdx = -1; /* Index of the step= constraint, or -1 if none */
  570. int nArg = 0; /* Number of arguments that seriesFilter() expects */
  571. const struct sqlite3_index_constraint *pConstraint;
  572. pConstraint = pIdxInfo->aConstraint;
  573. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  574. if( pConstraint->usable==0 ) continue;
  575. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  576. switch( pConstraint->iColumn ){
  577. case SERIES_COLUMN_START:
  578. startIdx = i;
  579. idxNum |= 1;
  580. break;
  581. case SERIES_COLUMN_STOP:
  582. stopIdx = i;
  583. idxNum |= 2;
  584. break;
  585. case SERIES_COLUMN_STEP:
  586. stepIdx = i;
  587. idxNum |= 4;
  588. break;
  589. }
  590. }
  591. if( startIdx>=0 ){
  592. pIdxInfo->aConstraintUsage[startIdx].argvIndex = ++nArg;
  593. pIdxInfo->aConstraintUsage[startIdx].omit= !SQLITE_SERIES_CONSTRAINT_VERIFY;
  594. }
  595. if( stopIdx>=0 ){
  596. pIdxInfo->aConstraintUsage[stopIdx].argvIndex = ++nArg;
  597. pIdxInfo->aConstraintUsage[stopIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
  598. }
  599. if( stepIdx>=0 ){
  600. pIdxInfo->aConstraintUsage[stepIdx].argvIndex = ++nArg;
  601. pIdxInfo->aConstraintUsage[stepIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
  602. }
  603. if( (idxNum & 3)==3 ){
  604. /* Both start= and stop= boundaries are available. This is the
  605. ** the preferred case */
  606. pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
  607. pIdxInfo->estimatedRows = 1000;
  608. if( pIdxInfo->nOrderBy==1 ){
  609. if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
  610. pIdxInfo->orderByConsumed = 1;
  611. }
  612. }else{
  613. /* If either boundary is missing, we have to generate a huge span
  614. ** of numbers. Make this case very expensive so that the query
  615. ** planner will work hard to avoid it. */
  616. pIdxInfo->estimatedCost = (double)2147483647;
  617. pIdxInfo->estimatedRows = 2147483647;
  618. }
  619. pIdxInfo->idxNum = idxNum;
  620. return SQLITE_OK;
  621. }
  622. /*
  623. ** This following structure defines all the methods for the
  624. ** generate_series virtual table.
  625. */
  626. static sqlite3_module seriesModule = {
  627. 0, /* iVersion */
  628. 0, /* xCreate */
  629. seriesConnect, /* xConnect */
  630. seriesBestIndex, /* xBestIndex */
  631. seriesDisconnect, /* xDisconnect */
  632. 0, /* xDestroy */
  633. seriesOpen, /* xOpen - open a cursor */
  634. seriesClose, /* xClose - close a cursor */
  635. seriesFilter, /* xFilter - configure scan constraints */
  636. seriesNext, /* xNext - advance a cursor */
  637. seriesEof, /* xEof - check for end of scan */
  638. seriesColumn, /* xColumn - read data */
  639. seriesRowid, /* xRowid - read data */
  640. 0, /* xUpdate */
  641. 0, /* xBegin */
  642. 0, /* xSync */
  643. 0, /* xCommit */
  644. 0, /* xRollback */
  645. 0, /* xFindMethod */
  646. 0, /* xRename */
  647. 0, /* xSavepoint */
  648. 0, /* xRelease */
  649. 0, /* xRollbackTo */
  650. 0, /* xShadowName */
  651. 0 /* xIntegrity */
  652. };
  653. /* END the generate_series(START,END,STEP) implementation
  654. *********************************************************************************/
  655. /*
  656. ** Print sketchy documentation for this utility program
  657. */
  658. static void showHelp(void){
  659. printf("Usage: %s [options] ?FILE...?\n", g.zArgv0);
  660. printf(
  661. "Read SQL text from FILE... (or from standard input if FILE... is omitted)\n"
  662. "and then evaluate each block of SQL contained therein.\n"
  663. "Options:\n"
  664. " --autovacuum Enable AUTOVACUUM mode\n"
  665. " --database FILE Use database FILE instead of an in-memory database\n"
  666. " --disable-lookaside Turn off lookaside memory\n"
  667. " --heap SZ MIN Memory allocator uses SZ bytes & min allocation MIN\n"
  668. " --help Show this help text\n"
  669. " --lookaside N SZ Configure lookaside for N slots of SZ bytes each\n"
  670. " --oom Run each test multiple times in a simulated OOM loop\n"
  671. " --pagesize N Set the page size to N\n"
  672. " --pcache N SZ Configure N pages of pagecache each of size SZ bytes\n"
  673. " -q Reduced output\n"
  674. " --quiet Reduced output\n"
  675. " --scratch N SZ Configure scratch memory for N slots of SZ bytes each\n"
  676. " --unique-cases FILE Write all unique test cases to FILE\n"
  677. " --utf16be Set text encoding to UTF-16BE\n"
  678. " --utf16le Set text encoding to UTF-16LE\n"
  679. " -v Increased output\n"
  680. " --verbose Increased output\n"
  681. );
  682. }
  683. /*
  684. ** Return the value of a hexadecimal digit. Return -1 if the input
  685. ** is not a hex digit.
  686. */
  687. static int hexDigitValue(char c){
  688. if( c>='0' && c<='9' ) return c - '0';
  689. if( c>='a' && c<='f' ) return c - 'a' + 10;
  690. if( c>='A' && c<='F' ) return c - 'A' + 10;
  691. return -1;
  692. }
  693. /*
  694. ** Interpret zArg as an integer value, possibly with suffixes.
  695. */
  696. static int integerValue(const char *zArg){
  697. sqlite3_int64 v = 0;
  698. static const struct { char *zSuffix; int iMult; } aMult[] = {
  699. { "KiB", 1024 },
  700. { "MiB", 1024*1024 },
  701. { "GiB", 1024*1024*1024 },
  702. { "KB", 1000 },
  703. { "MB", 1000000 },
  704. { "GB", 1000000000 },
  705. { "K", 1000 },
  706. { "M", 1000000 },
  707. { "G", 1000000000 },
  708. };
  709. int i;
  710. int isNeg = 0;
  711. if( zArg[0]=='-' ){
  712. isNeg = 1;
  713. zArg++;
  714. }else if( zArg[0]=='+' ){
  715. zArg++;
  716. }
  717. if( zArg[0]=='0' && zArg[1]=='x' ){
  718. int x;
  719. zArg += 2;
  720. while( (x = hexDigitValue(zArg[0]))>=0 ){
  721. v = (v<<4) + x;
  722. zArg++;
  723. }
  724. }else{
  725. while( ISDIGIT(zArg[0]) ){
  726. v = v*10 + zArg[0] - '0';
  727. zArg++;
  728. }
  729. }
  730. for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
  731. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  732. v *= aMult[i].iMult;
  733. break;
  734. }
  735. }
  736. if( v>0x7fffffff ) abendError("parameter too large - max 2147483648");
  737. return (int)(isNeg? -v : v);
  738. }
  739. /* Return the current wall-clock time */
  740. static sqlite3_int64 timeOfDay(void){
  741. static sqlite3_vfs *clockVfs = 0;
  742. sqlite3_int64 t;
  743. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  744. if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
  745. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  746. }else{
  747. double r;
  748. clockVfs->xCurrentTime(clockVfs, &r);
  749. t = (sqlite3_int64)(r*86400000.0);
  750. }
  751. return t;
  752. }
  753. int main(int argc, char **argv){
  754. char *zIn = 0; /* Input text */
  755. int nAlloc = 0; /* Number of bytes allocated for zIn[] */
  756. int nIn = 0; /* Number of bytes of zIn[] used */
  757. size_t got; /* Bytes read from input */
  758. int rc = SQLITE_OK; /* Result codes from API functions */
  759. int i; /* Loop counter */
  760. int iNext; /* Next block of SQL */
  761. sqlite3 *db; /* Open database */
  762. char *zErrMsg = 0; /* Error message returned from sqlite3_exec() */
  763. const char *zEncoding = 0; /* --utf16be or --utf16le */
  764. int nHeap = 0, mnHeap = 0; /* Heap size from --heap */
  765. int nLook = 0, szLook = 0; /* --lookaside configuration */
  766. int nPCache = 0, szPCache = 0;/* --pcache configuration */
  767. int nScratch = 0, szScratch=0;/* --scratch configuration */
  768. int pageSize = 0; /* Desired page size. 0 means default */
  769. void *pHeap = 0; /* Allocated heap space */
  770. void *pLook = 0; /* Allocated lookaside space */
  771. void *pPCache = 0; /* Allocated storage for pcache */
  772. void *pScratch = 0; /* Allocated storage for scratch */
  773. int doAutovac = 0; /* True for --autovacuum */
  774. char *zSql; /* SQL to run */
  775. char *zToFree = 0; /* Call sqlite3_free() on this afte running zSql */
  776. int verboseFlag = 0; /* --verbose or -v flag */
  777. int quietFlag = 0; /* --quiet or -q flag */
  778. int nTest = 0; /* Number of test cases run */
  779. int multiTest = 0; /* True if there will be multiple test cases */
  780. int lastPct = -1; /* Previous percentage done output */
  781. sqlite3 *dataDb = 0; /* Database holding compacted input data */
  782. sqlite3_stmt *pStmt = 0; /* Statement to insert testcase into dataDb */
  783. const char *zDataOut = 0; /* Write compacted data to this output file */
  784. int nHeader = 0; /* Bytes of header comment text on input file */
  785. int oomFlag = 0; /* --oom */
  786. int oomCnt = 0; /* Counter for the OOM loop */
  787. char zErrBuf[200]; /* Space for the error message */
  788. const char *zFailCode; /* Value of the TEST_FAILURE environment var */
  789. const char *zPrompt; /* Initial prompt when large-file fuzzing */
  790. int nInFile = 0; /* Number of input files to read */
  791. char **azInFile = 0; /* Array of input file names */
  792. int jj; /* Loop counter for azInFile[] */
  793. sqlite3_int64 iBegin; /* Start time for the whole program */
  794. sqlite3_int64 iStart, iEnd; /* Start and end-times for a test case */
  795. const char *zDbName = 0; /* Name of an on-disk database file to open */
  796. iBegin = timeOfDay();
  797. sqlite3_shutdown();
  798. zFailCode = getenv("TEST_FAILURE");
  799. g.zArgv0 = argv[0];
  800. zPrompt = "<stdin>";
  801. for(i=1; i<argc; i++){
  802. const char *z = argv[i];
  803. if( z[0]=='-' ){
  804. z++;
  805. if( z[0]=='-' ) z++;
  806. if( strcmp(z,"autovacuum")==0 ){
  807. doAutovac = 1;
  808. }else
  809. if( strcmp(z,"database")==0 ){
  810. if( i>=argc-1 ) abendError("missing argument on %s\n", argv[i]);
  811. zDbName = argv[i+1];
  812. i += 1;
  813. }else
  814. if( strcmp(z,"disable-lookaside")==0 ){
  815. nLook = 1;
  816. szLook = 0;
  817. }else
  818. if( strcmp(z, "f")==0 && i+1<argc ){
  819. i++;
  820. goto addNewInFile;
  821. }else
  822. if( strcmp(z,"heap")==0 ){
  823. if( i>=argc-2 ) abendError("missing arguments on %s\n", argv[i]);
  824. nHeap = integerValue(argv[i+1]);
  825. mnHeap = integerValue(argv[i+2]);
  826. i += 2;
  827. }else
  828. if( strcmp(z,"help")==0 ){
  829. showHelp();
  830. return 0;
  831. }else
  832. if( strcmp(z,"lookaside")==0 ){
  833. if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
  834. nLook = integerValue(argv[i+1]);
  835. szLook = integerValue(argv[i+2]);
  836. i += 2;
  837. }else
  838. if( strcmp(z,"oom")==0 ){
  839. oomFlag = 1;
  840. }else
  841. if( strcmp(z,"pagesize")==0 ){
  842. if( i>=argc-1 ) abendError("missing argument on %s", argv[i]);
  843. pageSize = integerValue(argv[++i]);
  844. }else
  845. if( strcmp(z,"pcache")==0 ){
  846. if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
  847. nPCache = integerValue(argv[i+1]);
  848. szPCache = integerValue(argv[i+2]);
  849. i += 2;
  850. }else
  851. if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
  852. quietFlag = 1;
  853. verboseFlag = 0;
  854. }else
  855. if( strcmp(z,"scratch")==0 ){
  856. if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
  857. nScratch = integerValue(argv[i+1]);
  858. szScratch = integerValue(argv[i+2]);
  859. i += 2;
  860. }else
  861. if( strcmp(z, "unique-cases")==0 ){
  862. if( i>=argc-1 ) abendError("missing arguments on %s", argv[i]);
  863. if( zDataOut ) abendError("only one --minimize allowed");
  864. zDataOut = argv[++i];
  865. }else
  866. if( strcmp(z,"utf16le")==0 ){
  867. zEncoding = "utf16le";
  868. }else
  869. if( strcmp(z,"utf16be")==0 ){
  870. zEncoding = "utf16be";
  871. }else
  872. if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
  873. quietFlag = 0;
  874. verboseFlag = 1;
  875. }else
  876. {
  877. abendError("unknown option: %s", argv[i]);
  878. }
  879. }else{
  880. addNewInFile:
  881. nInFile++;
  882. azInFile = realloc(azInFile, sizeof(azInFile[0])*nInFile);
  883. if( azInFile==0 ) abendError("out of memory");
  884. azInFile[nInFile-1] = argv[i];
  885. }
  886. }
  887. /* Do global SQLite initialization */
  888. sqlite3_config(SQLITE_CONFIG_LOG, verboseFlag ? shellLog : shellLogNoop, 0);
  889. if( nHeap>0 ){
  890. pHeap = malloc( nHeap );
  891. if( pHeap==0 ) fatalError("cannot allocate %d-byte heap\n", nHeap);
  892. rc = sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nHeap, mnHeap);
  893. if( rc ) abendError("heap configuration failed: %d\n", rc);
  894. }
  895. if( oomFlag ){
  896. sqlite3_config(SQLITE_CONFIG_GETMALLOC, &g.sOrigMem);
  897. g.sOomMem = g.sOrigMem;
  898. g.sOomMem.xMalloc = oomMalloc;
  899. g.sOomMem.xRealloc = oomRealloc;
  900. sqlite3_config(SQLITE_CONFIG_MALLOC, &g.sOomMem);
  901. }
  902. if( nLook>0 ){
  903. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
  904. if( szLook>0 ){
  905. pLook = malloc( nLook*szLook );
  906. if( pLook==0 ) fatalError("out of memory");
  907. }
  908. }
  909. if( nScratch>0 && szScratch>0 ){
  910. pScratch = malloc( nScratch*(sqlite3_int64)szScratch );
  911. if( pScratch==0 ) fatalError("cannot allocate %lld-byte scratch",
  912. nScratch*(sqlite3_int64)szScratch);
  913. rc = sqlite3_config(SQLITE_CONFIG_SCRATCH, pScratch, szScratch, nScratch);
  914. if( rc ) abendError("scratch configuration failed: %d\n", rc);
  915. }
  916. if( nPCache>0 && szPCache>0 ){
  917. pPCache = malloc( nPCache*(sqlite3_int64)szPCache );
  918. if( pPCache==0 ) fatalError("cannot allocate %lld-byte pcache",
  919. nPCache*(sqlite3_int64)szPCache);
  920. rc = sqlite3_config(SQLITE_CONFIG_PAGECACHE, pPCache, szPCache, nPCache);
  921. if( rc ) abendError("pcache configuration failed: %d", rc);
  922. }
  923. /* If the --unique-cases option was supplied, open the database that will
  924. ** be used to gather unique test cases.
  925. */
  926. if( zDataOut ){
  927. rc = sqlite3_open(":memory:", &dataDb);
  928. if( rc ) abendError("cannot open :memory: database");
  929. rc = sqlite3_exec(dataDb,
  930. "CREATE TABLE testcase(sql BLOB PRIMARY KEY, tm) WITHOUT ROWID;",0,0,0);
  931. if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
  932. rc = sqlite3_prepare_v2(dataDb,
  933. "INSERT OR IGNORE INTO testcase(sql,tm)VALUES(?1,?2)",
  934. -1, &pStmt, 0);
  935. if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
  936. }
  937. /* Initialize the input buffer used to hold SQL text */
  938. if( nInFile==0 ) nInFile = 1;
  939. nAlloc = 1000;
  940. zIn = malloc(nAlloc);
  941. if( zIn==0 ) fatalError("out of memory");
  942. /* Loop over all input files */
  943. for(jj=0; jj<nInFile; jj++){
  944. /* Read the complete content of the next input file into zIn[] */
  945. FILE *in;
  946. if( azInFile ){
  947. int j, k;
  948. in = fopen(azInFile[jj],"rb");
  949. if( in==0 ){
  950. abendError("cannot open %s for reading", azInFile[jj]);
  951. }
  952. zPrompt = azInFile[jj];
  953. for(j=k=0; zPrompt[j]; j++) if( zPrompt[j]=='/' ) k = j+1;
  954. zPrompt += k;
  955. }else{
  956. in = stdin;
  957. zPrompt = "<stdin>";
  958. }
  959. while( !feof(in) ){
  960. got = fread(zIn+nIn, 1, nAlloc-nIn-1, in);
  961. nIn += (int)got;
  962. zIn[nIn] = 0;
  963. if( got==0 ) break;
  964. if( nAlloc - nIn - 1 < 100 ){
  965. nAlloc += nAlloc+1000;
  966. zIn = realloc(zIn, nAlloc);
  967. if( zIn==0 ) fatalError("out of memory");
  968. }
  969. }
  970. if( in!=stdin ) fclose(in);
  971. lastPct = -1;
  972. /* Skip initial lines of the input file that begin with "#" */
  973. for(i=0; i<nIn; i=iNext+1){
  974. if( zIn[i]!='#' ) break;
  975. for(iNext=i+1; iNext<nIn && zIn[iNext]!='\n'; iNext++){}
  976. }
  977. nHeader = i;
  978. /* Process all test cases contained within the input file.
  979. */
  980. for(; i<nIn; i=iNext, nTest++, g.zTestName[0]=0){
  981. char cSaved;
  982. if( strncmp(&zIn[i], "/****<",6)==0 ){
  983. char *z = strstr(&zIn[i], ">****/");
  984. if( z ){
  985. z += 6;
  986. sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "%.*s",
  987. (int)(z-&zIn[i]) - 12, &zIn[i+6]);
  988. if( verboseFlag ){
  989. printf("%.*s\n", (int)(z-&zIn[i]), &zIn[i]);
  990. fflush(stdout);
  991. }
  992. i += (int)(z-&zIn[i]);
  993. multiTest = 1;
  994. }
  995. }
  996. for(iNext=i; iNext<nIn && strncmp(&zIn[iNext],"/****<",6)!=0; iNext++){}
  997. cSaved = zIn[iNext];
  998. zIn[iNext] = 0;
  999. /* Print out the SQL of the next test case is --verbose is enabled
  1000. */
  1001. zSql = &zIn[i];
  1002. if( verboseFlag ){
  1003. printf("INPUT (offset: %d, size: %d): [%s]\n",
  1004. i, (int)strlen(&zIn[i]), &zIn[i]);
  1005. }else if( multiTest && !quietFlag ){
  1006. if( oomFlag ){
  1007. printf("%s\n", g.zTestName);
  1008. }else{
  1009. int pct = (10*iNext)/nIn;
  1010. if( pct!=lastPct ){
  1011. if( lastPct<0 ) printf("%s:", zPrompt);
  1012. printf(" %d%%", pct*10);
  1013. lastPct = pct;
  1014. }
  1015. }
  1016. }else if( nInFile>1 ){
  1017. printf("%s\n", zPrompt);
  1018. }
  1019. fflush(stdout);
  1020. /* Run the next test case. Run it multiple times in --oom mode
  1021. */
  1022. if( oomFlag ){
  1023. oomCnt = g.iOomCntdown = 1;
  1024. g.nOomFault = 0;
  1025. g.bOomOnce = 1;
  1026. if( verboseFlag ){
  1027. printf("Once.%d\n", oomCnt);
  1028. fflush(stdout);
  1029. }
  1030. }else{
  1031. oomCnt = 0;
  1032. }
  1033. do{
  1034. Str sql;
  1035. StrInit(&sql);
  1036. if( zDbName ){
  1037. rc = sqlite3_open_v2(zDbName, &db, SQLITE_OPEN_READWRITE, 0);
  1038. if( rc!=SQLITE_OK ){
  1039. abendError("Cannot open database file %s", zDbName);
  1040. }
  1041. }else{
  1042. rc = sqlite3_open_v2(
  1043. "main.db", &db,
  1044. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY,
  1045. 0);
  1046. if( rc!=SQLITE_OK ){
  1047. abendError("Unable to open the in-memory database");
  1048. }
  1049. }
  1050. if( pLook ){
  1051. rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE,pLook,szLook,nLook);
  1052. if( rc!=SQLITE_OK ) abendError("lookaside configuration filed: %d", rc);
  1053. }
  1054. #ifndef SQLITE_OMIT_TRACE
  1055. sqlite3_trace(db, verboseFlag ? traceCallback : traceNoop, 0);
  1056. #endif
  1057. sqlite3_create_function(db, "eval", 1, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
  1058. sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
  1059. sqlite3_create_module(db, "generate_series", &seriesModule, 0);
  1060. sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
  1061. if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
  1062. if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
  1063. if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
  1064. iStart = timeOfDay();
  1065. /* If using an input database file and that database contains a table
  1066. ** named "autoexec" with a column "sql", then replace the input SQL
  1067. ** with the concatenated text of the autoexec table. In this way,
  1068. ** if the database file is the input being fuzzed, the SQL text is
  1069. ** fuzzed at the same time. */
  1070. if( sqlite3_table_column_metadata(db,0,"autoexec","sql",0,0,0,0,0)==0 ){
  1071. sqlite3_stmt *pStmt2;
  1072. rc = sqlite3_prepare_v2(db,"SELECT sql FROM autoexec",-1,&pStmt2,0);
  1073. if( rc==SQLITE_OK ){
  1074. while( sqlite3_step(pStmt2)==SQLITE_ROW ){
  1075. StrAppend(&sql, (const char*)sqlite3_column_text(pStmt2, 0));
  1076. StrAppend(&sql, "\n");
  1077. }
  1078. }
  1079. sqlite3_finalize(pStmt2);
  1080. zSql = StrStr(&sql);
  1081. }
  1082. g.bOomEnable = 1;
  1083. if( verboseFlag ){
  1084. zErrMsg = 0;
  1085. rc = sqlite3_exec(db, zSql, execCallback, 0, &zErrMsg);
  1086. if( zErrMsg ){
  1087. sqlite3_snprintf(sizeof(zErrBuf),zErrBuf,"%z", zErrMsg);
  1088. zErrMsg = 0;
  1089. }
  1090. }else {
  1091. rc = sqlite3_exec(db, zSql, execNoop, 0, 0);
  1092. }
  1093. g.bOomEnable = 0;
  1094. iEnd = timeOfDay();
  1095. StrFree(&sql);
  1096. rc = sqlite3_close(db);
  1097. if( rc ){
  1098. abendError("sqlite3_close() failed with rc=%d", rc);
  1099. }
  1100. if( !zDataOut && sqlite3_memory_used()>0 ){
  1101. abendError("memory in use after close: %lld bytes",sqlite3_memory_used());
  1102. }
  1103. if( oomFlag ){
  1104. /* Limit the number of iterations of the OOM loop to OOM_MAX. If the
  1105. ** first pass (single failure) exceeds 2/3rds of OOM_MAX this skip the
  1106. ** second pass (continuous failure after first) completely. */
  1107. if( g.nOomFault==0 || oomCnt>OOM_MAX ){
  1108. if( g.bOomOnce && oomCnt<=(OOM_MAX*2/3) ){
  1109. oomCnt = g.iOomCntdown = 1;
  1110. g.bOomOnce = 0;
  1111. }else{
  1112. oomCnt = 0;
  1113. }
  1114. }else{
  1115. g.iOomCntdown = ++oomCnt;
  1116. g.nOomFault = 0;
  1117. }
  1118. if( oomCnt ){
  1119. if( verboseFlag ){
  1120. printf("%s.%d\n", g.bOomOnce ? "Once" : "Multi", oomCnt);
  1121. fflush(stdout);
  1122. }
  1123. nTest++;
  1124. }
  1125. }
  1126. }while( oomCnt>0 );
  1127. /* Store unique test cases in the in the dataDb database if the
  1128. ** --unique-cases flag is present
  1129. */
  1130. if( zDataOut ){
  1131. sqlite3_bind_blob(pStmt, 1, &zIn[i], iNext-i, SQLITE_STATIC);
  1132. sqlite3_bind_int64(pStmt, 2, iEnd - iStart);
  1133. rc = sqlite3_step(pStmt);
  1134. if( rc!=SQLITE_DONE ) abendError("%s", sqlite3_errmsg(dataDb));
  1135. sqlite3_reset(pStmt);
  1136. }
  1137. /* Free the SQL from the current test case
  1138. */
  1139. if( zToFree ){
  1140. sqlite3_free(zToFree);
  1141. zToFree = 0;
  1142. }
  1143. zIn[iNext] = cSaved;
  1144. /* Show test-case results in --verbose mode
  1145. */
  1146. if( verboseFlag ){
  1147. printf("RESULT-CODE: %d\n", rc);
  1148. if( zErrMsg ){
  1149. printf("ERROR-MSG: [%s]\n", zErrBuf);
  1150. }
  1151. fflush(stdout);
  1152. }
  1153. /* Simulate an error if the TEST_FAILURE environment variable is "5".
  1154. ** This is used to verify that automated test script really do spot
  1155. ** errors that occur in this test program.
  1156. */
  1157. if( zFailCode ){
  1158. if( zFailCode[0]=='5' && zFailCode[1]==0 ){
  1159. abendError("simulated failure");
  1160. }else if( zFailCode[0]!=0 ){
  1161. /* If TEST_FAILURE is something other than 5, just exit the test
  1162. ** early */
  1163. printf("\nExit early due to TEST_FAILURE being set");
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. if( !verboseFlag && multiTest && !quietFlag && !oomFlag ) printf("\n");
  1169. }
  1170. /* Report total number of tests run
  1171. */
  1172. if( nTest>1 && !quietFlag ){
  1173. sqlite3_int64 iElapse = timeOfDay() - iBegin;
  1174. printf("%s: 0 errors out of %d tests in %d.%03d seconds\nSQLite %s %s\n",
  1175. g.zArgv0, nTest, (int)(iElapse/1000), (int)(iElapse%1000),
  1176. sqlite3_libversion(), sqlite3_sourceid());
  1177. }
  1178. /* Write the unique test cases if the --unique-cases flag was used
  1179. */
  1180. if( zDataOut ){
  1181. int n = 0;
  1182. FILE *out = fopen(zDataOut, "wb");
  1183. if( out==0 ) abendError("cannot open %s for writing", zDataOut);
  1184. if( nHeader>0 ) fwrite(zIn, nHeader, 1, out);
  1185. sqlite3_finalize(pStmt);
  1186. rc = sqlite3_prepare_v2(dataDb, "SELECT sql, tm FROM testcase ORDER BY tm, sql",
  1187. -1, &pStmt, 0);
  1188. if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
  1189. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  1190. fprintf(out,"/****<%d:%dms>****/", ++n, sqlite3_column_int(pStmt,1));
  1191. fwrite(sqlite3_column_blob(pStmt,0),sqlite3_column_bytes(pStmt,0),1,out);
  1192. }
  1193. fclose(out);
  1194. sqlite3_finalize(pStmt);
  1195. sqlite3_close(dataDb);
  1196. }
  1197. /* Clean up and exit.
  1198. */
  1199. free(azInFile);
  1200. free(zIn);
  1201. free(pHeap);
  1202. free(pLook);
  1203. free(pScratch);
  1204. free(pPCache);
  1205. return 0;
  1206. }