blob: 6f841e220caaece60cd8b235e7eef28a38624f3c [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**
35** 2015-04-20: The input text can be divided into separate SQL chunks using
36** lines of the form:
37**
38** |****<...>****|
39**
40** where the "..." is arbitrary text, except the "|" should really be "/".
41** ("|" is used here to avoid compiler warnings about nested comments.)
42** Each such SQL comment is printed as it is encountered. A separate
43** in-memory SQLite database is created to run each chunk of SQL. This
44** feature allows the "queue" of AFL to be captured into a single big
45** file using a command like this:
46**
47** (for i in id:*; do echo '|****<'$i'>****|'; cat $i; done) >~/all-queue.txt
48**
49** (Once again, change the "|" to "/") Then all elements of the AFL queue
50** can be run in a single go (for regression testing, for example, by typing:
51**
52** fuzzershell -f ~/all-queue.txt >out.txt
53**
54** After running each chunk of SQL, the database connection is closed. The
55** program aborts if the close fails or if there is any unfreed memory after
56** the close.
drh268e72f2015-04-17 14:30:49 +000057*/
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <stdarg.h>
62#include "sqlite3.h"
63
64/*
65** All global variables are gathered into the "g" singleton.
66*/
67struct GlobalVars {
68 const char *zArgv0; /* Name of program */
69} g;
70
71
72
73/*
74** Print an error message and abort in such a way to indicate to the
75** fuzzer that this counts as a crash.
76*/
77static void abendError(const char *zFormat, ...){
78 va_list ap;
79 fprintf(stderr, "%s: ", g.zArgv0);
80 va_start(ap, zFormat);
81 vfprintf(stderr, zFormat, ap);
82 va_end(ap);
83 fprintf(stderr, "\n");
84 abort();
85}
86/*
87** Print an error message and quit, but not in a way that would look
88** like a crash.
89*/
90static void fatalError(const char *zFormat, ...){
91 va_list ap;
92 fprintf(stderr, "%s: ", g.zArgv0);
93 va_start(ap, zFormat);
94 vfprintf(stderr, zFormat, ap);
95 va_end(ap);
96 fprintf(stderr, "\n");
97 exit(1);
98}
99
100/*
101** This callback is invoked by sqlite3_log().
102*/
103static void shellLog(void *pNotUsed, int iErrCode, const char *zMsg){
104 printf("LOG: (%d) %s\n", iErrCode, zMsg);
105}
106
107/*
108** This callback is invoked by sqlite3_exec() to return query results.
109*/
110static int execCallback(void *NotUsed, int argc, char **argv, char **colv){
111 int i;
112 static unsigned cnt = 0;
113 printf("ROW #%u:\n", ++cnt);
114 for(i=0; i<argc; i++){
115 printf(" %s=", colv[i]);
116 if( argv[i] ){
117 printf("[%s]\n", argv[i]);
118 }else{
119 printf("NULL\n");
120 }
121 }
122 return 0;
123}
124
125/*
126** This callback is invoked by sqlite3_trace() as each SQL statement
127** starts.
128*/
129static void traceCallback(void *NotUsed, const char *zMsg){
130 printf("TRACE: %s\n", zMsg);
131}
132
133/***************************************************************************
134** eval() implementation copied from ../ext/misc/eval.c
135*/
136/*
137** Structure used to accumulate the output
138*/
139struct EvalResult {
140 char *z; /* Accumulated output */
141 const char *zSep; /* Separator */
142 int szSep; /* Size of the separator string */
143 sqlite3_int64 nAlloc; /* Number of bytes allocated for z[] */
144 sqlite3_int64 nUsed; /* Number of bytes of z[] actually used */
145};
146
147/*
148** Callback from sqlite_exec() for the eval() function.
149*/
150static int callback(void *pCtx, int argc, char **argv, char **colnames){
151 struct EvalResult *p = (struct EvalResult*)pCtx;
152 int i;
153 for(i=0; i<argc; i++){
154 const char *z = argv[i] ? argv[i] : "";
155 size_t sz = strlen(z);
156 if( (sqlite3_int64)sz+p->nUsed+p->szSep+1 > p->nAlloc ){
157 char *zNew;
158 p->nAlloc = p->nAlloc*2 + sz + p->szSep + 1;
159 /* Using sqlite3_realloc64() would be better, but it is a recent
160 ** addition and will cause a segfault if loaded by an older version
161 ** of SQLite. */
162 zNew = p->nAlloc<=0x7fffffff ? sqlite3_realloc(p->z, (int)p->nAlloc) : 0;
163 if( zNew==0 ){
164 sqlite3_free(p->z);
165 memset(p, 0, sizeof(*p));
166 return 1;
167 }
168 p->z = zNew;
169 }
170 if( p->nUsed>0 ){
171 memcpy(&p->z[p->nUsed], p->zSep, p->szSep);
172 p->nUsed += p->szSep;
173 }
174 memcpy(&p->z[p->nUsed], z, sz);
175 p->nUsed += sz;
176 }
177 return 0;
178}
179
180/*
181** Implementation of the eval(X) and eval(X,Y) SQL functions.
182**
183** Evaluate the SQL text in X. Return the results, using string
184** Y as the separator. If Y is omitted, use a single space character.
185*/
186static void sqlEvalFunc(
187 sqlite3_context *context,
188 int argc,
189 sqlite3_value **argv
190){
191 const char *zSql;
192 sqlite3 *db;
193 char *zErr = 0;
194 int rc;
195 struct EvalResult x;
196
197 memset(&x, 0, sizeof(x));
198 x.zSep = " ";
199 zSql = (const char*)sqlite3_value_text(argv[0]);
200 if( zSql==0 ) return;
201 if( argc>1 ){
202 x.zSep = (const char*)sqlite3_value_text(argv[1]);
203 if( x.zSep==0 ) return;
204 }
205 x.szSep = (int)strlen(x.zSep);
206 db = sqlite3_context_db_handle(context);
207 rc = sqlite3_exec(db, zSql, callback, &x, &zErr);
208 if( rc!=SQLITE_OK ){
209 sqlite3_result_error(context, zErr, -1);
210 sqlite3_free(zErr);
211 }else if( x.zSep==0 ){
212 sqlite3_result_error_nomem(context);
213 sqlite3_free(x.z);
214 }else{
215 sqlite3_result_text(context, x.z, (int)x.nUsed, sqlite3_free);
216 }
217}
218/* End of the eval() implementation
219******************************************************************************/
220
221/*
222** Print sketchy documentation for this utility program
223*/
224static void showHelp(void){
225 printf("Usage: %s [options]\n", g.zArgv0);
226 printf(
227"Read SQL text from standard input and evaluate it.\n"
228"Options:\n"
229" -f FILE Read SQL text from FILE instead of standard input\n"
230" --help Show this help text\n"
231" --initdb DBFILE Initialize the in-memory database using template DBFILE\n"
232 );
233}
234
235
236int main(int argc, char **argv){
237 char *zIn = 0; /* Input text */
238 int nAlloc = 0; /* Number of bytes allocated for zIn[] */
239 int nIn = 0; /* Number of bytes of zIn[] used */
240 size_t got; /* Bytes read from input */
241 FILE *in = stdin; /* Where to read SQL text from */
242 int rc = SQLITE_OK; /* Result codes from API functions */
243 int i; /* Loop counter */
drhf34e9aa2015-04-20 12:50:13 +0000244 int iNext; /* Next block of SQL */
drh268e72f2015-04-17 14:30:49 +0000245 sqlite3 *db; /* Open database */
drhf34e9aa2015-04-20 12:50:13 +0000246 sqlite3 *dbInit = 0; /* On-disk database used to initialize the in-memory db */
drh268e72f2015-04-17 14:30:49 +0000247 const char *zInitDb = 0;/* Name of the initialization database file */
248 char *zErrMsg = 0; /* Error message returned from sqlite3_exec() */
249
250 g.zArgv0 = argv[0];
251 for(i=1; i<argc; i++){
252 const char *z = argv[i];
253 if( z[0]=='-' ){
254 z++;
255 if( z[0]=='-' ) z++;
256 if( strcmp(z,"help")==0 ){
257 showHelp();
258 return 0;
259 }else
260 if( strcmp(z, "f")==0 && i+1<argc ){
261 if( in!=stdin ) abendError("only one -f allowed");
262 in = fopen(argv[++i],"rb");
263 if( in==0 ) abendError("cannot open input file \"%s\"", argv[i]);
264 }else
265 if( strcmp(z, "initdb")==0 && i+1<argc ){
266 if( zInitDb!=0 ) abendError("only one --initdb allowed");
267 zInitDb = argv[++i];
268 }else
269 {
270 abendError("unknown option: %s", argv[i]);
271 }
272 }else{
273 abendError("unknown argument: %s", argv[i]);
274 }
275 }
276 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, 0);
drh268e72f2015-04-17 14:30:49 +0000277 while( !feof(in) ){
drhf34e9aa2015-04-20 12:50:13 +0000278 nAlloc += nAlloc+1000;
279 zIn = realloc(zIn, nAlloc);
drh268e72f2015-04-17 14:30:49 +0000280 if( zIn==0 ) fatalError("out of memory");
281 got = fread(zIn+nIn, 1, nAlloc-nIn-1, in);
282 nIn += (int)got;
283 zIn[nIn] = 0;
284 if( got==0 ) break;
285 }
drhf34e9aa2015-04-20 12:50:13 +0000286 if( zInitDb ){
287 rc = sqlite3_open_v2(zInitDb, &dbInit, SQLITE_OPEN_READONLY, 0);
288 if( rc!=SQLITE_OK ){
289 abendError("unable to open initialization database \"%s\"", zInitDb);
290 }
drh268e72f2015-04-17 14:30:49 +0000291 }
drhf34e9aa2015-04-20 12:50:13 +0000292 for(i=0; i<nIn; i=iNext){
293 char cSaved;
294 if( strncmp(&zIn[i], "/****<",6)==0 ){
295 char *z = strstr(&zIn[i], ">****/");
296 if( z ){
297 z += 6;
298 printf("%.*s\n", (int)(z-&zIn[i]), &zIn[i]);
299 i += (int)(z-&zIn[i]);
300 }
301 }
302 for(iNext=i; iNext<nIn && strncmp(&zIn[iNext],"/****<",6)!=0; iNext++){}
303
304 rc = sqlite3_open_v2(
305 "main.db", &db,
306 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY,
307 0);
308 if( rc!=SQLITE_OK ){
309 abendError("Unable to open the in-memory database");
310 }
311 if( zInitDb ){
312 sqlite3_backup *pBackup;
313 pBackup = sqlite3_backup_init(db, "main", dbInit, "main");
314 rc = sqlite3_backup_step(pBackup, -1);
315 if( rc!=SQLITE_DONE ){
316 abendError("attempt to initialize the in-memory database failed (rc=%d)",
317 rc);
318 }
319 sqlite3_backup_finish(pBackup);
320 }
321 sqlite3_trace(db, traceCallback, 0);
322 sqlite3_create_function(db, "eval", 1, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
323 sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
324 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
325
326 cSaved = zIn[iNext];
327 zIn[iNext] = 0;
328 printf("INPUT (offset: %d, size: %d): [%s]\n",
329 i, (int)strlen(&zIn[i]), &zIn[i]);
330 rc = sqlite3_exec(db, &zIn[i], execCallback, 0, &zErrMsg);
331 zIn[iNext] = cSaved;
332
333 printf("RESULT-CODE: %d\n", rc);
334 if( zErrMsg ){
335 printf("ERROR-MSG: [%s]\n", zErrMsg);
336 sqlite3_free(zErrMsg);
337 }
338 rc = sqlite3_close(db);
339 if( rc ){
340 abendError("sqlite3_close() failed with rc=%d", rc);
341 }
342 if( sqlite3_memory_used()>0 ){
343 abendError("memory in use after close: %lld bytes", sqlite3_memory_used());
344 }
345 }
346 free(zIn);
347 return 0;
drh268e72f2015-04-17 14:30:49 +0000348}