blob: d19139d984d0c681b64565b410954efb8d0a0f82 [file] [log] [blame]
drh268e72f2015-04-17 14:30:49 +00001/*
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.
drhf34e9aa2015-04-20 12:50:13 +000034**
drhbe5248f2015-04-25 11:35:48 +000035** (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:
drhf34e9aa2015-04-20 12:50:13 +000039**
40** |****<...>****|
41**
drhf3320712015-04-25 13:39:29 +000042** where the "..." is arbitrary text. (Except the "|" should really be "/".
43** "|" is used here to avoid compiler errors about nested comments.)
drhbe5248f2015-04-25 11:35:48 +000044** A separate in-memory SQLite database is created to run each test case.
drh875bafa2015-04-24 14:47:59 +000045** This feature allows the "queue" of AFL to be captured into a single big
drhf34e9aa2015-04-20 12:50:13 +000046** 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
drh4a74d072015-04-20 18:58:38 +000051** can be run in a single go (for regression testing, for example) by typing:
drhf34e9aa2015-04-20 12:50:13 +000052**
drh875bafa2015-04-24 14:47:59 +000053** fuzzershell -f ~/all-queue.txt
drhf34e9aa2015-04-20 12:50:13 +000054**
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.
drh875bafa2015-04-24 14:47:59 +000058**
drhbe5248f2015-04-25 11:35:48 +000059** 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:
drh875bafa2015-04-24 14:47:59 +000061**
62** fuzzershell -f ~/all-queue.txt --unique-cases ~/unique-cases.txt
drh268e72f2015-04-17 14:30:49 +000063*/
64#include <stdio.h>
65#include <stdlib.h>
66#include <string.h>
67#include <stdarg.h>
drh4a74d072015-04-20 18:58:38 +000068#include <ctype.h>
drh268e72f2015-04-17 14:30:49 +000069#include "sqlite3.h"
drhc56fac72015-10-29 13:48:15 +000070#define ISDIGIT(X) isdigit((unsigned char)(X))
drh268e72f2015-04-17 14:30:49 +000071
72/*
73** All global variables are gathered into the "g" singleton.
74*/
75struct GlobalVars {
drh048810b2015-04-24 23:45:23 +000076 const char *zArgv0; /* Name of program */
77 sqlite3_mem_methods sOrigMem; /* Original memory methods */
78 sqlite3_mem_methods sOomMem; /* Memory methods with OOM simulator */
79 int iOomCntdown; /* Memory fails on 1 to 0 transition */
80 int nOomFault; /* Increments for each OOM fault */
81 int bOomOnce; /* Fail just once if true */
82 int bOomEnable; /* True to enable OOM simulation */
83 int nOomBrkpt; /* Number of calls to oomFault() */
drh0ee751f2015-04-25 11:19:51 +000084 char zTestName[100]; /* Name of current test */
drh268e72f2015-04-17 14:30:49 +000085} g;
86
drh048810b2015-04-24 23:45:23 +000087/*
drhf3320712015-04-25 13:39:29 +000088** Maximum number of iterations for an OOM test
89*/
90#ifndef OOM_MAX
drh7c84c022015-04-25 16:39:49 +000091# define OOM_MAX 625
drhf3320712015-04-25 13:39:29 +000092#endif
93
94/*
drh048810b2015-04-24 23:45:23 +000095** This routine is called when a simulated OOM occurs. It exists as a
96** convenient place to set a debugger breakpoint.
97*/
98static void oomFault(void){
drhbe5248f2015-04-25 11:35:48 +000099 g.nOomBrkpt++; /* Prevent oomFault() from being optimized out */
drh048810b2015-04-24 23:45:23 +0000100}
drh268e72f2015-04-17 14:30:49 +0000101
102
drh048810b2015-04-24 23:45:23 +0000103/* Versions of malloc() and realloc() that simulate OOM conditions */
104static void *oomMalloc(int nByte){
105 if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
106 g.iOomCntdown--;
107 if( g.iOomCntdown==0 ){
108 if( g.nOomFault==0 ) oomFault();
109 g.nOomFault++;
110 if( !g.bOomOnce ) g.iOomCntdown = 1;
111 return 0;
112 }
113 }
114 return g.sOrigMem.xMalloc(nByte);
115}
116static void *oomRealloc(void *pOld, int nByte){
117 if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
118 g.iOomCntdown--;
119 if( g.iOomCntdown==0 ){
120 if( g.nOomFault==0 ) oomFault();
121 g.nOomFault++;
122 if( !g.bOomOnce ) g.iOomCntdown = 1;
123 return 0;
124 }
125 }
126 return g.sOrigMem.xRealloc(pOld, nByte);
127}
128
drh268e72f2015-04-17 14:30:49 +0000129/*
130** Print an error message and abort in such a way to indicate to the
131** fuzzer that this counts as a crash.
132*/
133static void abendError(const char *zFormat, ...){
134 va_list ap;
drhbe5248f2015-04-25 11:35:48 +0000135 if( g.zTestName[0] ){
136 fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
137 }else{
138 fprintf(stderr, "%s: ", g.zArgv0);
139 }
drh268e72f2015-04-17 14:30:49 +0000140 va_start(ap, zFormat);
141 vfprintf(stderr, zFormat, ap);
142 va_end(ap);
143 fprintf(stderr, "\n");
144 abort();
145}
146/*
147** Print an error message and quit, but not in a way that would look
148** like a crash.
149*/
150static void fatalError(const char *zFormat, ...){
151 va_list ap;
drhbe5248f2015-04-25 11:35:48 +0000152 if( g.zTestName[0] ){
153 fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
154 }else{
155 fprintf(stderr, "%s: ", g.zArgv0);
156 }
drh268e72f2015-04-17 14:30:49 +0000157 va_start(ap, zFormat);
158 vfprintf(stderr, zFormat, ap);
159 va_end(ap);
160 fprintf(stderr, "\n");
161 exit(1);
162}
163
164/*
drh4a74d072015-04-20 18:58:38 +0000165** Evaluate some SQL. Abort if unable.
166*/
167static void sqlexec(sqlite3 *db, const char *zFormat, ...){
168 va_list ap;
169 char *zSql;
170 char *zErrMsg = 0;
171 int rc;
172 va_start(ap, zFormat);
173 zSql = sqlite3_vmprintf(zFormat, ap);
174 va_end(ap);
175 rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg);
176 if( rc ) abendError("failed sql [%s]: %s", zSql, zErrMsg);
177 sqlite3_free(zSql);
178}
179
180/*
drh268e72f2015-04-17 14:30:49 +0000181** This callback is invoked by sqlite3_log().
182*/
183static void shellLog(void *pNotUsed, int iErrCode, const char *zMsg){
184 printf("LOG: (%d) %s\n", iErrCode, zMsg);
drh9f18f742015-04-25 00:20:15 +0000185 fflush(stdout);
drh268e72f2015-04-17 14:30:49 +0000186}
drh0ee751f2015-04-25 11:19:51 +0000187static void shellLogNoop(void *pNotUsed, int iErrCode, const char *zMsg){
188 return;
189}
drh268e72f2015-04-17 14:30:49 +0000190
191/*
192** This callback is invoked by sqlite3_exec() to return query results.
193*/
194static int execCallback(void *NotUsed, int argc, char **argv, char **colv){
195 int i;
196 static unsigned cnt = 0;
197 printf("ROW #%u:\n", ++cnt);
198 for(i=0; i<argc; i++){
199 printf(" %s=", colv[i]);
200 if( argv[i] ){
201 printf("[%s]\n", argv[i]);
202 }else{
203 printf("NULL\n");
204 }
205 }
drh9f18f742015-04-25 00:20:15 +0000206 fflush(stdout);
drh268e72f2015-04-17 14:30:49 +0000207 return 0;
208}
drh1cbb7fa2015-04-24 13:00:59 +0000209static int execNoop(void *NotUsed, int argc, char **argv, char **colv){
210 return 0;
211}
drh268e72f2015-04-17 14:30:49 +0000212
drh61a0d6b2015-04-24 18:31:12 +0000213#ifndef SQLITE_OMIT_TRACE
drh268e72f2015-04-17 14:30:49 +0000214/*
215** This callback is invoked by sqlite3_trace() as each SQL statement
216** starts.
217*/
218static void traceCallback(void *NotUsed, const char *zMsg){
219 printf("TRACE: %s\n", zMsg);
drh9f18f742015-04-25 00:20:15 +0000220 fflush(stdout);
drh268e72f2015-04-17 14:30:49 +0000221}
drh0ee751f2015-04-25 11:19:51 +0000222static void traceNoop(void *NotUsed, const char *zMsg){
223 return;
224}
drh61a0d6b2015-04-24 18:31:12 +0000225#endif
drh268e72f2015-04-17 14:30:49 +0000226
227/***************************************************************************
228** eval() implementation copied from ../ext/misc/eval.c
229*/
230/*
231** Structure used to accumulate the output
232*/
233struct EvalResult {
234 char *z; /* Accumulated output */
235 const char *zSep; /* Separator */
236 int szSep; /* Size of the separator string */
237 sqlite3_int64 nAlloc; /* Number of bytes allocated for z[] */
238 sqlite3_int64 nUsed; /* Number of bytes of z[] actually used */
239};
240
241/*
242** Callback from sqlite_exec() for the eval() function.
243*/
244static int callback(void *pCtx, int argc, char **argv, char **colnames){
245 struct EvalResult *p = (struct EvalResult*)pCtx;
246 int i;
247 for(i=0; i<argc; i++){
248 const char *z = argv[i] ? argv[i] : "";
249 size_t sz = strlen(z);
250 if( (sqlite3_int64)sz+p->nUsed+p->szSep+1 > p->nAlloc ){
251 char *zNew;
252 p->nAlloc = p->nAlloc*2 + sz + p->szSep + 1;
253 /* Using sqlite3_realloc64() would be better, but it is a recent
254 ** addition and will cause a segfault if loaded by an older version
255 ** of SQLite. */
256 zNew = p->nAlloc<=0x7fffffff ? sqlite3_realloc(p->z, (int)p->nAlloc) : 0;
257 if( zNew==0 ){
258 sqlite3_free(p->z);
259 memset(p, 0, sizeof(*p));
260 return 1;
261 }
262 p->z = zNew;
263 }
264 if( p->nUsed>0 ){
265 memcpy(&p->z[p->nUsed], p->zSep, p->szSep);
266 p->nUsed += p->szSep;
267 }
268 memcpy(&p->z[p->nUsed], z, sz);
269 p->nUsed += sz;
270 }
271 return 0;
272}
273
274/*
275** Implementation of the eval(X) and eval(X,Y) SQL functions.
276**
277** Evaluate the SQL text in X. Return the results, using string
278** Y as the separator. If Y is omitted, use a single space character.
279*/
280static void sqlEvalFunc(
281 sqlite3_context *context,
282 int argc,
283 sqlite3_value **argv
284){
285 const char *zSql;
286 sqlite3 *db;
287 char *zErr = 0;
288 int rc;
289 struct EvalResult x;
290
291 memset(&x, 0, sizeof(x));
292 x.zSep = " ";
293 zSql = (const char*)sqlite3_value_text(argv[0]);
294 if( zSql==0 ) return;
295 if( argc>1 ){
296 x.zSep = (const char*)sqlite3_value_text(argv[1]);
297 if( x.zSep==0 ) return;
298 }
299 x.szSep = (int)strlen(x.zSep);
300 db = sqlite3_context_db_handle(context);
301 rc = sqlite3_exec(db, zSql, callback, &x, &zErr);
302 if( rc!=SQLITE_OK ){
303 sqlite3_result_error(context, zErr, -1);
304 sqlite3_free(zErr);
305 }else if( x.zSep==0 ){
306 sqlite3_result_error_nomem(context);
307 sqlite3_free(x.z);
308 }else{
309 sqlite3_result_text(context, x.z, (int)x.nUsed, sqlite3_free);
310 }
311}
312/* End of the eval() implementation
313******************************************************************************/
314
drh9f6dd022016-09-03 16:23:42 +0000315/******************************************************************************
316** The generate_series(START,END,STEP) eponymous table-valued function.
317**
318** This code is copy/pasted from ext/misc/series.c in the SQLite source tree.
319*/
320/* series_cursor is a subclass of sqlite3_vtab_cursor which will
321** serve as the underlying representation of a cursor that scans
322** over rows of the result
323*/
324typedef struct series_cursor series_cursor;
325struct series_cursor {
326 sqlite3_vtab_cursor base; /* Base class - must be first */
327 int isDesc; /* True to count down rather than up */
328 sqlite3_int64 iRowid; /* The rowid */
329 sqlite3_int64 iValue; /* Current value ("value") */
330 sqlite3_int64 mnValue; /* Mimimum value ("start") */
331 sqlite3_int64 mxValue; /* Maximum value ("stop") */
332 sqlite3_int64 iStep; /* Increment ("step") */
333};
334
335/*
336** The seriesConnect() method is invoked to create a new
337** series_vtab that describes the generate_series virtual table.
338**
339** Think of this routine as the constructor for series_vtab objects.
340**
341** All this routine needs to do is:
342**
343** (1) Allocate the series_vtab object and initialize all fields.
344**
345** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
346** result set of queries against generate_series will look like.
347*/
348static int seriesConnect(
349 sqlite3 *db,
350 void *pAux,
351 int argc, const char *const*argv,
352 sqlite3_vtab **ppVtab,
353 char **pzErr
354){
355 sqlite3_vtab *pNew;
356 int rc;
357
358/* Column numbers */
359#define SERIES_COLUMN_VALUE 0
360#define SERIES_COLUMN_START 1
361#define SERIES_COLUMN_STOP 2
362#define SERIES_COLUMN_STEP 3
363
364 rc = sqlite3_declare_vtab(db,
365 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
366 if( rc==SQLITE_OK ){
367 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
368 if( pNew==0 ) return SQLITE_NOMEM;
369 memset(pNew, 0, sizeof(*pNew));
370 }
371 return rc;
372}
373
374/*
375** This method is the destructor for series_cursor objects.
376*/
377static int seriesDisconnect(sqlite3_vtab *pVtab){
378 sqlite3_free(pVtab);
379 return SQLITE_OK;
380}
381
382/*
383** Constructor for a new series_cursor object.
384*/
385static int seriesOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
386 series_cursor *pCur;
387 pCur = sqlite3_malloc( sizeof(*pCur) );
388 if( pCur==0 ) return SQLITE_NOMEM;
389 memset(pCur, 0, sizeof(*pCur));
390 *ppCursor = &pCur->base;
391 return SQLITE_OK;
392}
393
394/*
395** Destructor for a series_cursor.
396*/
397static int seriesClose(sqlite3_vtab_cursor *cur){
398 sqlite3_free(cur);
399 return SQLITE_OK;
400}
401
402
403/*
404** Advance a series_cursor to its next row of output.
405*/
406static int seriesNext(sqlite3_vtab_cursor *cur){
407 series_cursor *pCur = (series_cursor*)cur;
408 if( pCur->isDesc ){
409 pCur->iValue -= pCur->iStep;
410 }else{
411 pCur->iValue += pCur->iStep;
412 }
413 pCur->iRowid++;
414 return SQLITE_OK;
415}
416
417/*
418** Return values of columns for the row at which the series_cursor
419** is currently pointing.
420*/
421static int seriesColumn(
422 sqlite3_vtab_cursor *cur, /* The cursor */
423 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
424 int i /* Which column to return */
425){
426 series_cursor *pCur = (series_cursor*)cur;
427 sqlite3_int64 x = 0;
428 switch( i ){
429 case SERIES_COLUMN_START: x = pCur->mnValue; break;
430 case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
431 case SERIES_COLUMN_STEP: x = pCur->iStep; break;
432 default: x = pCur->iValue; break;
433 }
434 sqlite3_result_int64(ctx, x);
435 return SQLITE_OK;
436}
437
438/*
439** Return the rowid for the current row. In this implementation, the
440** rowid is the same as the output value.
441*/
442static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
443 series_cursor *pCur = (series_cursor*)cur;
444 *pRowid = pCur->iRowid;
445 return SQLITE_OK;
446}
447
448/*
449** Return TRUE if the cursor has been moved off of the last
450** row of output.
451*/
452static int seriesEof(sqlite3_vtab_cursor *cur){
453 series_cursor *pCur = (series_cursor*)cur;
454 if( pCur->isDesc ){
455 return pCur->iValue < pCur->mnValue;
456 }else{
457 return pCur->iValue > pCur->mxValue;
458 }
459}
460
461/* True to cause run-time checking of the start=, stop=, and/or step=
462** parameters. The only reason to do this is for testing the
463** constraint checking logic for virtual tables in the SQLite core.
464*/
465#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
466# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
467#endif
468
469/*
470** This method is called to "rewind" the series_cursor object back
471** to the first row of output. This method is always called at least
472** once prior to any call to seriesColumn() or seriesRowid() or
473** seriesEof().
474**
475** The query plan selected by seriesBestIndex is passed in the idxNum
476** parameter. (idxStr is not used in this implementation.) idxNum
477** is a bitmask showing which constraints are available:
478**
479** 1: start=VALUE
480** 2: stop=VALUE
481** 4: step=VALUE
482**
483** Also, if bit 8 is set, that means that the series should be output
484** in descending order rather than in ascending order.
485**
486** This routine should initialize the cursor and position it so that it
487** is pointing at the first row, or pointing off the end of the table
488** (so that seriesEof() will return true) if the table is empty.
489*/
490static int seriesFilter(
491 sqlite3_vtab_cursor *pVtabCursor,
492 int idxNum, const char *idxStr,
493 int argc, sqlite3_value **argv
494){
495 series_cursor *pCur = (series_cursor *)pVtabCursor;
496 int i = 0;
497 if( idxNum & 1 ){
498 pCur->mnValue = sqlite3_value_int64(argv[i++]);
499 }else{
500 pCur->mnValue = 0;
501 }
502 if( idxNum & 2 ){
503 pCur->mxValue = sqlite3_value_int64(argv[i++]);
504 }else{
505 pCur->mxValue = 0xffffffff;
506 }
507 if( idxNum & 4 ){
508 pCur->iStep = sqlite3_value_int64(argv[i++]);
509 if( pCur->iStep<1 ) pCur->iStep = 1;
510 }else{
511 pCur->iStep = 1;
512 }
513 if( idxNum & 8 ){
514 pCur->isDesc = 1;
515 pCur->iValue = pCur->mxValue;
516 if( pCur->iStep>0 ){
517 pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
518 }
519 }else{
520 pCur->isDesc = 0;
521 pCur->iValue = pCur->mnValue;
522 }
523 pCur->iRowid = 1;
524 return SQLITE_OK;
525}
526
527/*
528** SQLite will invoke this method one or more times while planning a query
529** that uses the generate_series virtual table. This routine needs to create
530** a query plan for each invocation and compute an estimated cost for that
531** plan.
532**
533** In this implementation idxNum is used to represent the
534** query plan. idxStr is unused.
535**
536** The query plan is represented by bits in idxNum:
537**
538** (1) start = $value -- constraint exists
539** (2) stop = $value -- constraint exists
540** (4) step = $value -- constraint exists
541** (8) output in descending order
542*/
543static int seriesBestIndex(
544 sqlite3_vtab *tab,
545 sqlite3_index_info *pIdxInfo
546){
547 int i; /* Loop over constraints */
548 int idxNum = 0; /* The query plan bitmask */
549 int startIdx = -1; /* Index of the start= constraint, or -1 if none */
550 int stopIdx = -1; /* Index of the stop= constraint, or -1 if none */
551 int stepIdx = -1; /* Index of the step= constraint, or -1 if none */
552 int nArg = 0; /* Number of arguments that seriesFilter() expects */
553
554 const struct sqlite3_index_constraint *pConstraint;
555 pConstraint = pIdxInfo->aConstraint;
556 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
557 if( pConstraint->usable==0 ) continue;
558 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
559 switch( pConstraint->iColumn ){
560 case SERIES_COLUMN_START:
561 startIdx = i;
562 idxNum |= 1;
563 break;
564 case SERIES_COLUMN_STOP:
565 stopIdx = i;
566 idxNum |= 2;
567 break;
568 case SERIES_COLUMN_STEP:
569 stepIdx = i;
570 idxNum |= 4;
571 break;
572 }
573 }
574 if( startIdx>=0 ){
575 pIdxInfo->aConstraintUsage[startIdx].argvIndex = ++nArg;
576 pIdxInfo->aConstraintUsage[startIdx].omit= !SQLITE_SERIES_CONSTRAINT_VERIFY;
577 }
578 if( stopIdx>=0 ){
579 pIdxInfo->aConstraintUsage[stopIdx].argvIndex = ++nArg;
580 pIdxInfo->aConstraintUsage[stopIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
581 }
582 if( stepIdx>=0 ){
583 pIdxInfo->aConstraintUsage[stepIdx].argvIndex = ++nArg;
584 pIdxInfo->aConstraintUsage[stepIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
585 }
586 if( (idxNum & 3)==3 ){
587 /* Both start= and stop= boundaries are available. This is the
588 ** the preferred case */
589 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
590 pIdxInfo->estimatedRows = 1000;
591 if( pIdxInfo->nOrderBy==1 ){
592 if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
593 pIdxInfo->orderByConsumed = 1;
594 }
595 }else{
596 /* If either boundary is missing, we have to generate a huge span
597 ** of numbers. Make this case very expensive so that the query
598 ** planner will work hard to avoid it. */
599 pIdxInfo->estimatedCost = (double)2147483647;
600 pIdxInfo->estimatedRows = 2147483647;
601 }
602 pIdxInfo->idxNum = idxNum;
603 return SQLITE_OK;
604}
605
606/*
607** This following structure defines all the methods for the
608** generate_series virtual table.
609*/
610static sqlite3_module seriesModule = {
611 0, /* iVersion */
612 0, /* xCreate */
613 seriesConnect, /* xConnect */
614 seriesBestIndex, /* xBestIndex */
615 seriesDisconnect, /* xDisconnect */
616 0, /* xDestroy */
617 seriesOpen, /* xOpen - open a cursor */
618 seriesClose, /* xClose - close a cursor */
619 seriesFilter, /* xFilter - configure scan constraints */
620 seriesNext, /* xNext - advance a cursor */
621 seriesEof, /* xEof - check for end of scan */
622 seriesColumn, /* xColumn - read data */
623 seriesRowid, /* xRowid - read data */
624 0, /* xUpdate */
625 0, /* xBegin */
626 0, /* xSync */
627 0, /* xCommit */
628 0, /* xRollback */
629 0, /* xFindMethod */
630 0, /* xRename */
631};
632/* END the generate_series(START,END,STEP) implementation
633*********************************************************************************/
634
drh268e72f2015-04-17 14:30:49 +0000635/*
636** Print sketchy documentation for this utility program
637*/
638static void showHelp(void){
drhb3df0c62015-05-01 19:21:12 +0000639 printf("Usage: %s [options] ?FILE...?\n", g.zArgv0);
drh268e72f2015-04-17 14:30:49 +0000640 printf(
drhb3df0c62015-05-01 19:21:12 +0000641"Read SQL text from FILE... (or from standard input if FILE... is omitted)\n"
642"and then evaluate each block of SQL contained therein.\n"
drh268e72f2015-04-17 14:30:49 +0000643"Options:\n"
drh875bafa2015-04-24 14:47:59 +0000644" --autovacuum Enable AUTOVACUUM mode\n"
drhacd33742015-05-22 11:38:22 +0000645" --database FILE Use database FILE instead of an in-memory database\n"
drhb97ad022015-09-19 19:36:13 +0000646" --disable-lookaside Turn off lookaside memory\n"
drh875bafa2015-04-24 14:47:59 +0000647" --heap SZ MIN Memory allocator uses SZ bytes & min allocation MIN\n"
648" --help Show this help text\n"
drh875bafa2015-04-24 14:47:59 +0000649" --lookaside N SZ Configure lookaside for N slots of SZ bytes each\n"
drh048810b2015-04-24 23:45:23 +0000650" --oom Run each test multiple times in a simulated OOM loop\n"
drh875bafa2015-04-24 14:47:59 +0000651" --pagesize N Set the page size to N\n"
652" --pcache N SZ Configure N pages of pagecache each of size SZ bytes\n"
653" -q Reduced output\n"
654" --quiet Reduced output\n"
655" --scratch N SZ Configure scratch memory for N slots of SZ bytes each\n"
656" --unique-cases FILE Write all unique test cases to FILE\n"
657" --utf16be Set text encoding to UTF-16BE\n"
658" --utf16le Set text encoding to UTF-16LE\n"
659" -v Increased output\n"
660" --verbose Increased output\n"
drh268e72f2015-04-17 14:30:49 +0000661 );
662}
663
drh4a74d072015-04-20 18:58:38 +0000664/*
665** Return the value of a hexadecimal digit. Return -1 if the input
666** is not a hex digit.
667*/
668static int hexDigitValue(char c){
669 if( c>='0' && c<='9' ) return c - '0';
670 if( c>='a' && c<='f' ) return c - 'a' + 10;
671 if( c>='A' && c<='F' ) return c - 'A' + 10;
672 return -1;
673}
674
675/*
676** Interpret zArg as an integer value, possibly with suffixes.
677*/
678static int integerValue(const char *zArg){
679 sqlite3_int64 v = 0;
680 static const struct { char *zSuffix; int iMult; } aMult[] = {
681 { "KiB", 1024 },
682 { "MiB", 1024*1024 },
683 { "GiB", 1024*1024*1024 },
684 { "KB", 1000 },
685 { "MB", 1000000 },
686 { "GB", 1000000000 },
687 { "K", 1000 },
688 { "M", 1000000 },
689 { "G", 1000000000 },
690 };
691 int i;
692 int isNeg = 0;
693 if( zArg[0]=='-' ){
694 isNeg = 1;
695 zArg++;
696 }else if( zArg[0]=='+' ){
697 zArg++;
698 }
699 if( zArg[0]=='0' && zArg[1]=='x' ){
700 int x;
701 zArg += 2;
702 while( (x = hexDigitValue(zArg[0]))>=0 ){
703 v = (v<<4) + x;
704 zArg++;
705 }
706 }else{
drhc56fac72015-10-29 13:48:15 +0000707 while( ISDIGIT(zArg[0]) ){
drh4a74d072015-04-20 18:58:38 +0000708 v = v*10 + zArg[0] - '0';
709 zArg++;
710 }
711 }
712 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
713 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
714 v *= aMult[i].iMult;
715 break;
716 }
717 }
718 if( v>0x7fffffff ) abendError("parameter too large - max 2147483648");
719 return (int)(isNeg? -v : v);
720}
721
drhc8430162015-05-01 20:34:47 +0000722/* Return the current wall-clock time */
723static sqlite3_int64 timeOfDay(void){
724 static sqlite3_vfs *clockVfs = 0;
725 sqlite3_int64 t;
726 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
727 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
728 clockVfs->xCurrentTimeInt64(clockVfs, &t);
729 }else{
730 double r;
731 clockVfs->xCurrentTime(clockVfs, &r);
732 t = (sqlite3_int64)(r*86400000.0);
733 }
734 return t;
735}
drh268e72f2015-04-17 14:30:49 +0000736
737int main(int argc, char **argv){
drhb3df0c62015-05-01 19:21:12 +0000738 char *zIn = 0; /* Input text */
739 int nAlloc = 0; /* Number of bytes allocated for zIn[] */
740 int nIn = 0; /* Number of bytes of zIn[] used */
741 size_t got; /* Bytes read from input */
742 int rc = SQLITE_OK; /* Result codes from API functions */
743 int i; /* Loop counter */
744 int iNext; /* Next block of SQL */
745 sqlite3 *db; /* Open database */
746 char *zErrMsg = 0; /* Error message returned from sqlite3_exec() */
drh4a74d072015-04-20 18:58:38 +0000747 const char *zEncoding = 0; /* --utf16be or --utf16le */
748 int nHeap = 0, mnHeap = 0; /* Heap size from --heap */
749 int nLook = 0, szLook = 0; /* --lookaside configuration */
750 int nPCache = 0, szPCache = 0;/* --pcache configuration */
751 int nScratch = 0, szScratch=0;/* --scratch configuration */
752 int pageSize = 0; /* Desired page size. 0 means default */
753 void *pHeap = 0; /* Allocated heap space */
754 void *pLook = 0; /* Allocated lookaside space */
755 void *pPCache = 0; /* Allocated storage for pcache */
756 void *pScratch = 0; /* Allocated storage for scratch */
757 int doAutovac = 0; /* True for --autovacuum */
drh9985dab2015-04-20 22:36:49 +0000758 char *zSql; /* SQL to run */
759 char *zToFree = 0; /* Call sqlite3_free() on this afte running zSql */
drh1cbb7fa2015-04-24 13:00:59 +0000760 int verboseFlag = 0; /* --verbose or -v flag */
761 int quietFlag = 0; /* --quiet or -q flag */
762 int nTest = 0; /* Number of test cases run */
763 int multiTest = 0; /* True if there will be multiple test cases */
764 int lastPct = -1; /* Previous percentage done output */
drh875bafa2015-04-24 14:47:59 +0000765 sqlite3 *dataDb = 0; /* Database holding compacted input data */
766 sqlite3_stmt *pStmt = 0; /* Statement to insert testcase into dataDb */
767 const char *zDataOut = 0; /* Write compacted data to this output file */
drhe1a71a52015-04-24 16:09:12 +0000768 int nHeader = 0; /* Bytes of header comment text on input file */
drh048810b2015-04-24 23:45:23 +0000769 int oomFlag = 0; /* --oom */
770 int oomCnt = 0; /* Counter for the OOM loop */
771 char zErrBuf[200]; /* Space for the error message */
772 const char *zFailCode; /* Value of the TEST_FAILURE environment var */
drhb3df0c62015-05-01 19:21:12 +0000773 const char *zPrompt; /* Initial prompt when large-file fuzzing */
774 int nInFile = 0; /* Number of input files to read */
775 char **azInFile = 0; /* Array of input file names */
776 int jj; /* Loop counter for azInFile[] */
drh1a57c172015-05-02 19:54:35 +0000777 sqlite3_int64 iBegin; /* Start time for the whole program */
drhc8430162015-05-01 20:34:47 +0000778 sqlite3_int64 iStart, iEnd; /* Start and end-times for a test case */
drhf9def062015-05-22 23:45:56 +0000779 const char *zDbName = 0; /* Name of an on-disk database file to open */
drh4a74d072015-04-20 18:58:38 +0000780
drh1a57c172015-05-02 19:54:35 +0000781 iBegin = timeOfDay();
drhb97ad022015-09-19 19:36:13 +0000782 sqlite3_shutdown();
drh048810b2015-04-24 23:45:23 +0000783 zFailCode = getenv("TEST_FAILURE");
drh268e72f2015-04-17 14:30:49 +0000784 g.zArgv0 = argv[0];
drhb3df0c62015-05-01 19:21:12 +0000785 zPrompt = "<stdin>";
drh268e72f2015-04-17 14:30:49 +0000786 for(i=1; i<argc; i++){
787 const char *z = argv[i];
788 if( z[0]=='-' ){
789 z++;
790 if( z[0]=='-' ) z++;
drh4a74d072015-04-20 18:58:38 +0000791 if( strcmp(z,"autovacuum")==0 ){
792 doAutovac = 1;
drh268e72f2015-04-17 14:30:49 +0000793 }else
drhacd33742015-05-22 11:38:22 +0000794 if( strcmp(z,"database")==0 ){
795 if( i>=argc-1 ) abendError("missing argument on %s\n", argv[i]);
796 zDbName = argv[i+1];
797 i += 1;
798 }else
drhb97ad022015-09-19 19:36:13 +0000799 if( strcmp(z,"disable-lookaside")==0 ){
800 nLook = 1;
801 szLook = 0;
802 }else
drh268e72f2015-04-17 14:30:49 +0000803 if( strcmp(z, "f")==0 && i+1<argc ){
drhb3df0c62015-05-01 19:21:12 +0000804 i++;
805 goto addNewInFile;
drh268e72f2015-04-17 14:30:49 +0000806 }else
drh4a74d072015-04-20 18:58:38 +0000807 if( strcmp(z,"heap")==0 ){
808 if( i>=argc-2 ) abendError("missing arguments on %s\n", argv[i]);
809 nHeap = integerValue(argv[i+1]);
810 mnHeap = integerValue(argv[i+2]);
811 i += 2;
812 }else
813 if( strcmp(z,"help")==0 ){
814 showHelp();
815 return 0;
816 }else
drh4a74d072015-04-20 18:58:38 +0000817 if( strcmp(z,"lookaside")==0 ){
818 if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
819 nLook = integerValue(argv[i+1]);
820 szLook = integerValue(argv[i+2]);
821 i += 2;
822 }else
drh048810b2015-04-24 23:45:23 +0000823 if( strcmp(z,"oom")==0 ){
824 oomFlag = 1;
825 }else
drh4a74d072015-04-20 18:58:38 +0000826 if( strcmp(z,"pagesize")==0 ){
827 if( i>=argc-1 ) abendError("missing argument on %s", argv[i]);
828 pageSize = integerValue(argv[++i]);
829 }else
830 if( strcmp(z,"pcache")==0 ){
831 if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
832 nPCache = integerValue(argv[i+1]);
833 szPCache = integerValue(argv[i+2]);
834 i += 2;
835 }else
drh1cbb7fa2015-04-24 13:00:59 +0000836 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
837 quietFlag = 1;
838 verboseFlag = 0;
839 }else
drh4a74d072015-04-20 18:58:38 +0000840 if( strcmp(z,"scratch")==0 ){
841 if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
842 nScratch = integerValue(argv[i+1]);
843 szScratch = integerValue(argv[i+2]);
844 i += 2;
845 }else
drh875bafa2015-04-24 14:47:59 +0000846 if( strcmp(z, "unique-cases")==0 ){
847 if( i>=argc-1 ) abendError("missing arguments on %s", argv[i]);
848 if( zDataOut ) abendError("only one --minimize allowed");
849 zDataOut = argv[++i];
850 }else
drh4a74d072015-04-20 18:58:38 +0000851 if( strcmp(z,"utf16le")==0 ){
852 zEncoding = "utf16le";
853 }else
854 if( strcmp(z,"utf16be")==0 ){
855 zEncoding = "utf16be";
856 }else
drh1cbb7fa2015-04-24 13:00:59 +0000857 if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
858 quietFlag = 0;
859 verboseFlag = 1;
860 }else
drh268e72f2015-04-17 14:30:49 +0000861 {
862 abendError("unknown option: %s", argv[i]);
863 }
864 }else{
drhb3df0c62015-05-01 19:21:12 +0000865 addNewInFile:
866 nInFile++;
867 azInFile = realloc(azInFile, sizeof(azInFile[0])*nInFile);
868 if( azInFile==0 ) abendError("out of memory");
869 azInFile[nInFile-1] = argv[i];
drh268e72f2015-04-17 14:30:49 +0000870 }
871 }
drhb3df0c62015-05-01 19:21:12 +0000872
873 /* Do global SQLite initialization */
drh0ee751f2015-04-25 11:19:51 +0000874 sqlite3_config(SQLITE_CONFIG_LOG, verboseFlag ? shellLog : shellLogNoop, 0);
drh4a74d072015-04-20 18:58:38 +0000875 if( nHeap>0 ){
876 pHeap = malloc( nHeap );
877 if( pHeap==0 ) fatalError("cannot allocate %d-byte heap\n", nHeap);
878 rc = sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nHeap, mnHeap);
879 if( rc ) abendError("heap configuration failed: %d\n", rc);
880 }
drh048810b2015-04-24 23:45:23 +0000881 if( oomFlag ){
882 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &g.sOrigMem);
883 g.sOomMem = g.sOrigMem;
884 g.sOomMem.xMalloc = oomMalloc;
885 g.sOomMem.xRealloc = oomRealloc;
886 sqlite3_config(SQLITE_CONFIG_MALLOC, &g.sOomMem);
887 }
drh4a74d072015-04-20 18:58:38 +0000888 if( nLook>0 ){
889 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
890 if( szLook>0 ){
891 pLook = malloc( nLook*szLook );
892 if( pLook==0 ) fatalError("out of memory");
893 }
894 }
895 if( nScratch>0 && szScratch>0 ){
896 pScratch = malloc( nScratch*(sqlite3_int64)szScratch );
897 if( pScratch==0 ) fatalError("cannot allocate %lld-byte scratch",
898 nScratch*(sqlite3_int64)szScratch);
899 rc = sqlite3_config(SQLITE_CONFIG_SCRATCH, pScratch, szScratch, nScratch);
900 if( rc ) abendError("scratch configuration failed: %d\n", rc);
901 }
902 if( nPCache>0 && szPCache>0 ){
903 pPCache = malloc( nPCache*(sqlite3_int64)szPCache );
904 if( pPCache==0 ) fatalError("cannot allocate %lld-byte pcache",
905 nPCache*(sqlite3_int64)szPCache);
906 rc = sqlite3_config(SQLITE_CONFIG_PAGECACHE, pPCache, szPCache, nPCache);
907 if( rc ) abendError("pcache configuration failed: %d", rc);
908 }
drhb3df0c62015-05-01 19:21:12 +0000909
910 /* If the --unique-cases option was supplied, open the database that will
911 ** be used to gather unique test cases.
912 */
drh875bafa2015-04-24 14:47:59 +0000913 if( zDataOut ){
914 rc = sqlite3_open(":memory:", &dataDb);
915 if( rc ) abendError("cannot open :memory: database");
916 rc = sqlite3_exec(dataDb,
drhc8430162015-05-01 20:34:47 +0000917 "CREATE TABLE testcase(sql BLOB PRIMARY KEY, tm) WITHOUT ROWID;",0,0,0);
drh875bafa2015-04-24 14:47:59 +0000918 if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
drhb3df0c62015-05-01 19:21:12 +0000919 rc = sqlite3_prepare_v2(dataDb,
drhc8430162015-05-01 20:34:47 +0000920 "INSERT OR IGNORE INTO testcase(sql,tm)VALUES(?1,?2)",
drhb3df0c62015-05-01 19:21:12 +0000921 -1, &pStmt, 0);
drh875bafa2015-04-24 14:47:59 +0000922 if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
923 }
drhb3df0c62015-05-01 19:21:12 +0000924
925 /* Initialize the input buffer used to hold SQL text */
926 if( nInFile==0 ) nInFile = 1;
927 nAlloc = 1000;
928 zIn = malloc(nAlloc);
929 if( zIn==0 ) fatalError("out of memory");
930
931 /* Loop over all input files */
932 for(jj=0; jj<nInFile; jj++){
933
934 /* Read the complete content of the next input file into zIn[] */
935 FILE *in;
936 if( azInFile ){
937 int j, k;
938 in = fopen(azInFile[jj],"rb");
939 if( in==0 ){
940 abendError("cannot open %s for reading", azInFile[jj]);
drhf34e9aa2015-04-20 12:50:13 +0000941 }
drhb3df0c62015-05-01 19:21:12 +0000942 zPrompt = azInFile[jj];
943 for(j=k=0; zPrompt[j]; j++) if( zPrompt[j]=='/' ) k = j+1;
944 zPrompt += k;
drh048810b2015-04-24 23:45:23 +0000945 }else{
drhb3df0c62015-05-01 19:21:12 +0000946 in = stdin;
947 zPrompt = "<stdin>";
drh048810b2015-04-24 23:45:23 +0000948 }
drhb3df0c62015-05-01 19:21:12 +0000949 while( !feof(in) ){
drhb3df0c62015-05-01 19:21:12 +0000950 got = fread(zIn+nIn, 1, nAlloc-nIn-1, in);
951 nIn += (int)got;
952 zIn[nIn] = 0;
953 if( got==0 ) break;
drh1a57c172015-05-02 19:54:35 +0000954 if( nAlloc - nIn - 1 < 100 ){
955 nAlloc += nAlloc+1000;
956 zIn = realloc(zIn, nAlloc);
957 if( zIn==0 ) fatalError("out of memory");
958 }
drhb3df0c62015-05-01 19:21:12 +0000959 }
960 if( in!=stdin ) fclose(in);
961 lastPct = -1;
962
963 /* Skip initial lines of the input file that begin with "#" */
964 for(i=0; i<nIn; i=iNext+1){
965 if( zIn[i]!='#' ) break;
966 for(iNext=i+1; iNext<nIn && zIn[iNext]!='\n'; iNext++){}
967 }
968 nHeader = i;
969
970 /* Process all test cases contained within the input file.
971 */
972 for(; i<nIn; i=iNext, nTest++, g.zTestName[0]=0){
973 char cSaved;
974 if( strncmp(&zIn[i], "/****<",6)==0 ){
975 char *z = strstr(&zIn[i], ">****/");
976 if( z ){
977 z += 6;
978 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "%.*s",
979 (int)(z-&zIn[i]) - 12, &zIn[i+6]);
drh048810b2015-04-24 23:45:23 +0000980 if( verboseFlag ){
drhb3df0c62015-05-01 19:21:12 +0000981 printf("%.*s\n", (int)(z-&zIn[i]), &zIn[i]);
drh9f18f742015-04-25 00:20:15 +0000982 fflush(stdout);
drh048810b2015-04-24 23:45:23 +0000983 }
drhb3df0c62015-05-01 19:21:12 +0000984 i += (int)(z-&zIn[i]);
985 multiTest = 1;
drh048810b2015-04-24 23:45:23 +0000986 }
987 }
drhb3df0c62015-05-01 19:21:12 +0000988 for(iNext=i; iNext<nIn && strncmp(&zIn[iNext],"/****<",6)!=0; iNext++){}
drhb3df0c62015-05-01 19:21:12 +0000989 cSaved = zIn[iNext];
990 zIn[iNext] = 0;
drhc8430162015-05-01 20:34:47 +0000991
drhb3df0c62015-05-01 19:21:12 +0000992
993 /* Print out the SQL of the next test case is --verbose is enabled
994 */
995 zSql = &zIn[i];
996 if( verboseFlag ){
997 printf("INPUT (offset: %d, size: %d): [%s]\n",
998 i, (int)strlen(&zIn[i]), &zIn[i]);
999 }else if( multiTest && !quietFlag ){
1000 if( oomFlag ){
1001 printf("%s\n", g.zTestName);
1002 }else{
1003 int pct = (10*iNext)/nIn;
1004 if( pct!=lastPct ){
1005 if( lastPct<0 ) printf("%s:", zPrompt);
1006 printf(" %d%%", pct*10);
1007 lastPct = pct;
1008 }
1009 }
drh1a57c172015-05-02 19:54:35 +00001010 }else if( nInFile>1 ){
1011 printf("%s\n", zPrompt);
drh1cbb7fa2015-04-24 13:00:59 +00001012 }
drh9f18f742015-04-25 00:20:15 +00001013 fflush(stdout);
drhb3df0c62015-05-01 19:21:12 +00001014
1015 /* Run the next test case. Run it multiple times in --oom mode
1016 */
1017 if( oomFlag ){
1018 oomCnt = g.iOomCntdown = 1;
1019 g.nOomFault = 0;
1020 g.bOomOnce = 1;
1021 if( verboseFlag ){
1022 printf("Once.%d\n", oomCnt);
1023 fflush(stdout);
1024 }
1025 }else{
1026 oomCnt = 0;
1027 }
1028 do{
drhacd33742015-05-22 11:38:22 +00001029 if( zDbName ){
1030 rc = sqlite3_open_v2(zDbName, &db, SQLITE_OPEN_READWRITE, 0);
drhc19bc9b2015-05-22 23:50:19 +00001031 if( rc!=SQLITE_OK ){
1032 abendError("Cannot open database file %s", zDbName);
1033 }
drhacd33742015-05-22 11:38:22 +00001034 }else{
1035 rc = sqlite3_open_v2(
1036 "main.db", &db,
1037 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY,
1038 0);
drhc19bc9b2015-05-22 23:50:19 +00001039 if( rc!=SQLITE_OK ){
1040 abendError("Unable to open the in-memory database");
1041 }
drhb3df0c62015-05-01 19:21:12 +00001042 }
1043 if( pLook ){
1044 rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE,pLook,szLook,nLook);
1045 if( rc!=SQLITE_OK ) abendError("lookaside configuration filed: %d", rc);
1046 }
1047 #ifndef SQLITE_OMIT_TRACE
1048 sqlite3_trace(db, verboseFlag ? traceCallback : traceNoop, 0);
1049 #endif
1050 sqlite3_create_function(db, "eval", 1, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
1051 sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
drh9f6dd022016-09-03 16:23:42 +00001052 sqlite3_create_module(db, "generate_series", &seriesModule, 0);
drhb3df0c62015-05-01 19:21:12 +00001053 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
1054 if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
1055 if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
1056 if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
drhc8430162015-05-01 20:34:47 +00001057 iStart = timeOfDay();
drhb3df0c62015-05-01 19:21:12 +00001058 g.bOomEnable = 1;
1059 if( verboseFlag ){
1060 zErrMsg = 0;
1061 rc = sqlite3_exec(db, zSql, execCallback, 0, &zErrMsg);
1062 if( zErrMsg ){
1063 sqlite3_snprintf(sizeof(zErrBuf),zErrBuf,"%z", zErrMsg);
1064 zErrMsg = 0;
1065 }
1066 }else {
1067 rc = sqlite3_exec(db, zSql, execNoop, 0, 0);
1068 }
1069 g.bOomEnable = 0;
drhc8430162015-05-01 20:34:47 +00001070 iEnd = timeOfDay();
drhb3df0c62015-05-01 19:21:12 +00001071 rc = sqlite3_close(db);
1072 if( rc ){
1073 abendError("sqlite3_close() failed with rc=%d", rc);
1074 }
drhc8430162015-05-01 20:34:47 +00001075 if( !zDataOut && sqlite3_memory_used()>0 ){
drhb3df0c62015-05-01 19:21:12 +00001076 abendError("memory in use after close: %lld bytes",sqlite3_memory_used());
1077 }
1078 if( oomFlag ){
1079 /* Limit the number of iterations of the OOM loop to OOM_MAX. If the
1080 ** first pass (single failure) exceeds 2/3rds of OOM_MAX this skip the
1081 ** second pass (continuous failure after first) completely. */
1082 if( g.nOomFault==0 || oomCnt>OOM_MAX ){
1083 if( g.bOomOnce && oomCnt<=(OOM_MAX*2/3) ){
1084 oomCnt = g.iOomCntdown = 1;
1085 g.bOomOnce = 0;
1086 }else{
1087 oomCnt = 0;
1088 }
1089 }else{
1090 g.iOomCntdown = ++oomCnt;
1091 g.nOomFault = 0;
1092 }
1093 if( oomCnt ){
1094 if( verboseFlag ){
1095 printf("%s.%d\n", g.bOomOnce ? "Once" : "Multi", oomCnt);
1096 fflush(stdout);
1097 }
1098 nTest++;
1099 }
1100 }
1101 }while( oomCnt>0 );
1102
drhc8430162015-05-01 20:34:47 +00001103 /* Store unique test cases in the in the dataDb database if the
1104 ** --unique-cases flag is present
1105 */
1106 if( zDataOut ){
1107 sqlite3_bind_blob(pStmt, 1, &zIn[i], iNext-i, SQLITE_STATIC);
1108 sqlite3_bind_int64(pStmt, 2, iEnd - iStart);
1109 rc = sqlite3_step(pStmt);
1110 if( rc!=SQLITE_DONE ) abendError("%s", sqlite3_errmsg(dataDb));
1111 sqlite3_reset(pStmt);
1112 }
1113
drhb3df0c62015-05-01 19:21:12 +00001114 /* Free the SQL from the current test case
1115 */
1116 if( zToFree ){
1117 sqlite3_free(zToFree);
1118 zToFree = 0;
1119 }
1120 zIn[iNext] = cSaved;
1121
1122 /* Show test-case results in --verbose mode
1123 */
1124 if( verboseFlag ){
1125 printf("RESULT-CODE: %d\n", rc);
1126 if( zErrMsg ){
1127 printf("ERROR-MSG: [%s]\n", zErrBuf);
1128 }
1129 fflush(stdout);
1130 }
1131
1132 /* Simulate an error if the TEST_FAILURE environment variable is "5".
1133 ** This is used to verify that automated test script really do spot
1134 ** errors that occur in this test program.
1135 */
1136 if( zFailCode ){
1137 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1138 abendError("simulated failure");
1139 }else if( zFailCode[0]!=0 ){
1140 /* If TEST_FAILURE is something other than 5, just exit the test
1141 ** early */
1142 printf("\nExit early due to TEST_FAILURE being set");
1143 break;
1144 }
drhe1a71a52015-04-24 16:09:12 +00001145 }
1146 }
drhb3df0c62015-05-01 19:21:12 +00001147 if( !verboseFlag && multiTest && !quietFlag && !oomFlag ) printf("\n");
drhf34e9aa2015-04-20 12:50:13 +00001148 }
drhb3df0c62015-05-01 19:21:12 +00001149
1150 /* Report total number of tests run
1151 */
drh1cbb7fa2015-04-24 13:00:59 +00001152 if( nTest>1 && !quietFlag ){
drh1a57c172015-05-02 19:54:35 +00001153 sqlite3_int64 iElapse = timeOfDay() - iBegin;
1154 printf("%s: 0 errors out of %d tests in %d.%03d seconds\nSQLite %s %s\n",
1155 g.zArgv0, nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1156 sqlite3_libversion(), sqlite3_sourceid());
drh875bafa2015-04-24 14:47:59 +00001157 }
drhb3df0c62015-05-01 19:21:12 +00001158
1159 /* Write the unique test cases if the --unique-cases flag was used
1160 */
drh875bafa2015-04-24 14:47:59 +00001161 if( zDataOut ){
drh875bafa2015-04-24 14:47:59 +00001162 int n = 0;
drhe1a71a52015-04-24 16:09:12 +00001163 FILE *out = fopen(zDataOut, "wb");
drh875bafa2015-04-24 14:47:59 +00001164 if( out==0 ) abendError("cannot open %s for writing", zDataOut);
drhe1a71a52015-04-24 16:09:12 +00001165 if( nHeader>0 ) fwrite(zIn, nHeader, 1, out);
drh875bafa2015-04-24 14:47:59 +00001166 sqlite3_finalize(pStmt);
drhc8430162015-05-01 20:34:47 +00001167 rc = sqlite3_prepare_v2(dataDb, "SELECT sql, tm FROM testcase ORDER BY tm, sql",
1168 -1, &pStmt, 0);
drh875bafa2015-04-24 14:47:59 +00001169 if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
1170 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drhc8430162015-05-01 20:34:47 +00001171 fprintf(out,"/****<%d:%dms>****/", ++n, sqlite3_column_int(pStmt,1));
drh875bafa2015-04-24 14:47:59 +00001172 fwrite(sqlite3_column_blob(pStmt,0),sqlite3_column_bytes(pStmt,0),1,out);
1173 }
1174 fclose(out);
1175 sqlite3_finalize(pStmt);
1176 sqlite3_close(dataDb);
drh1cbb7fa2015-04-24 13:00:59 +00001177 }
drhb3df0c62015-05-01 19:21:12 +00001178
1179 /* Clean up and exit.
1180 */
1181 free(azInFile);
drhf34e9aa2015-04-20 12:50:13 +00001182 free(zIn);
drh4a74d072015-04-20 18:58:38 +00001183 free(pHeap);
1184 free(pLook);
1185 free(pScratch);
1186 free(pPCache);
drhf34e9aa2015-04-20 12:50:13 +00001187 return 0;
drh268e72f2015-04-17 14:30:49 +00001188}