blob: 4bf0eb5e41ef4e32f4ed252ea7bbc237d9acbf9e [file] [log] [blame]
drhea432ba2016-11-11 16:33:47 +00001/*
2** This module interfaces SQLite to the Google OSS-Fuzz, fuzzer as a service.
3** (https://github.com/google/oss-fuzz)
4*/
5#include <stddef.h>
6#include <stdint.h>
7#include "sqlite3.h"
8
9/*
10** Progress handler callback
11*/
12static int progress_handler(void *pReturn) {
13 return *(int*)pReturn;
14}
15
16/*
17** Callback for sqlite3_exec().
18*/
19static int exec_handler(void *pCnt, int argc, char **argv, char **namev){
20 int i;
drh55377b42016-11-14 17:25:57 +000021 if( argv ){
22 for(i=0; i<argc; i++) sqlite3_free(sqlite3_mprintf("%s", argv[i]));
23 }
drhea432ba2016-11-11 16:33:47 +000024 return ((*(int*)pCnt)--)<=0;
25}
26
27/*
28** Main entry point. The fuzzer invokes this function with each
29** fuzzed input.
30*/
31int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
32 int progressArg = 0; /* 1 causes progress handler abort */
33 int execCnt = 0; /* Abort row callback when count reaches zero */
34 char *zErrMsg = 0; /* Error message returned by sqlite_exec() */
35 sqlite3 *db; /* The database connection */
36 uint8_t uSelector; /* First byte of input data[] */
37 int rc; /* Return code from various interfaces */
38 char *zSql; /* Zero-terminated copy of data[] */
39
40 if( size<3 ) return 0; /* Early out if unsufficient data */
41
42 /* Extract the selector byte from the beginning of the input. But only
43 ** do this if the second byte is a \n. If the second byte is not \n,
44 ** then use a default selector */
45 if( data[1]=='\n' ){
46 uSelector = data[0]; data += 2; size -= 2;
47 }else{
48 uSelector = 0xfd;
49 }
50
51 /* Open the database connection. Only use an in-memory database. */
52 rc = sqlite3_open_v2("fuzz.db", &db,
53 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY, 0);
54 if( rc ) return 0;
55
56 /* Bit 0 of the selector enables progress callbacks. Bit 1 is the
57 ** return code from progress callbacks */
58 if( uSelector & 1 ){
59 sqlite3_progress_handler(db, 4, progress_handler, (void*)&progressArg);
60 }
61 uSelector >>= 1;
62 progressArg = uSelector & 1; uSelector >>= 1;
63
64 /* Bit 2 of the selector enables foreign key constraints */
65 sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_FKEY, uSelector&1, &rc);
66 uSelector >>= 1;
67
68 /* Remaining bits of the selector determine a limit on the number of
69 ** output rows */
70 execCnt = uSelector + 1;
71
72 /* Run the SQL. The sqlite_exec() interface expects a zero-terminated
73 ** string, so make a copy. */
74 zSql = sqlite3_mprintf("%.*s", (int)size, data);
75 sqlite3_exec(db, zSql, exec_handler, (void*)&execCnt, &zErrMsg);
76
77 /* Cleanup and return */
78 sqlite3_free(zErrMsg);
79 sqlite3_free(zSql);
80 sqlite3_close(db);
81 return 0;
82}