xref: /sqlite-3.40.0/test/optfuzz.c (revision 30f30133)
1 /*
2 ** 2018-03-21
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 program attempts to verify the correctness of the SQLite query
14 ** optimizer by fuzzing.
15 **
16 ** The input is an SQL script, presumably generated by a fuzzer.  The
17 ** argument is the name of the input.  If no files are named, standard
18 ** input is read.
19 **
20 ** The SQL script is run twice, once with optimization enabled, and again
21 ** with optimization disabled.  If the output is not equivalent, an error
22 ** is printed and the program returns non-zero.
23 */
24 
25 /* Include the SQLite amalgamation, after making appropriate #defines.
26 */
27 #define SQLITE_THREADSAFE 0
28 #define SQLITE_OMIT_LOAD_EXTENSION 1
29 #define SQLITE_ENABLE_DESERIALIZE 1
30 #include "sqlite3.c"
31 
32 /* Content of the read-only test database */
33 #include "optfuzz-db01.c"
34 
35 /*
36 ** Prepare a single SQL statement.  Panic if anything goes wrong
37 */
38 static sqlite3_stmt *prepare_sql(sqlite3 *db, const char *zFormat, ...){
39   char *zSql;
40   int rc;
41   sqlite3_stmt *pStmt = 0;
42   va_list ap;
43 
44   va_start(ap, zFormat);
45   zSql = sqlite3_vmprintf(zFormat, ap);
46   va_end(ap);
47   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
48   if( rc ){
49     printf("Error: %s\nSQL: %s\n",
50            sqlite3_errmsg(db), zSql);
51     exit(1);
52   }
53   sqlite3_free(zSql);
54   return pStmt;
55 }
56 
57 /*
58 ** Run SQL.  Panic if anything goes wrong
59 */
60 static void run_sql(sqlite3 *db, const char *zFormat, ...){
61   char *zSql;
62   int rc;
63   char *zErr = 0;
64   va_list ap;
65 
66   va_start(ap, zFormat);
67   zSql = sqlite3_vmprintf(zFormat, ap);
68   va_end(ap);
69   rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
70   if( rc || zErr ){
71     printf("Error: %s\nsqlite3_errmsg: %s\nSQL: %s\n",
72            zErr, sqlite3_errmsg(db), zSql);
73     exit(1);
74   }
75   sqlite3_free(zSql);
76 }
77 
78 /*
79 ** Run one or more SQL statements contained in zSql against database dbRun.
80 ** Store the input in database dbOut.
81 */
82 static int optfuzz_exec(
83   sqlite3 *dbRun,             /* The database on which the SQL executes */
84   const char *zSql,           /* The SQL to be executed */
85   sqlite3 *dbOut,             /* Store results in this database */
86   const char *zOutTab         /* Store results in this table of dbOut */
87 ){
88   int rc = SQLITE_OK;         /* Return code */
89   const char *zLeftover;      /* Tail of unprocessed SQL */
90   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
91   sqlite3_stmt *pIns = 0;     /* Statement to insert into dbOut */
92   const char *zCol;           /* Single column value */
93   int nCol;                   /* Number of output columns */
94   char zLine[4000];           /* Complete row value */
95 
96   run_sql(dbOut, "BEGIN");
97   run_sql(dbOut, "CREATE TABLE IF NOT EXISTS staging(x TEXT);");
98   run_sql(dbOut, "CREATE TABLE IF NOT EXISTS \"w\"(x TEXT);", zOutTab);
99   pIns = prepare_sql(dbOut, "INSERT INTO staging(x) VALUES(?1)");
100   while( rc==SQLITE_OK && zSql[0] ){
101     rc = sqlite3_prepare_v2(dbRun, zSql, -1, &pStmt, &zLeftover);
102     assert( rc==SQLITE_OK || pStmt==0 );
103     if( rc!=SQLITE_OK ) break;
104     if( !pStmt ) continue;
105     nCol = sqlite3_column_count(pStmt);
106     run_sql(dbOut, "DELETE FROM staging;");
107     while( 1 ){
108       int i, j;
109       rc = sqlite3_step(pStmt);
110       for(i=j=0; i<nCol && j<sizeof(zLine)-50; i++){
111         int eType = sqlite3_column_type(pStmt, i);
112         if( eType==SQLITE_NULL ){
113           zCol = "NULL";
114         }else{
115           zCol = (const char*)sqlite3_column_text(pStmt, i);
116         }
117         if( i ) zLine[j++] = ',';
118         if( eType==SQLITE_TEXT ){
119           sqlite3_snprintf(sizeof(zLine)-j, zLine+j, "'%q'", zCol);
120         }else{
121           sqlite3_snprintf(sizeof(zLine)-j, zLine+j, "%s", zCol);
122         }
123         j += (int)strlen(zLine+j);
124       }
125       /* Detect if any row is too large and throw an error, because we will
126       ** want to go back and look more closely at that case */
127       if( j>=sizeof(zLine)-100 ){
128         printf("Excessively long output line: %d bytes\n" ,j);
129         exit(1);
130       }
131       sqlite3_bind_text(pIns, 1, zLine, j, SQLITE_TRANSIENT);
132       rc = sqlite3_step(pIns);
133       assert( rc==SQLITE_DONE );
134       sqlite3_reset(pIns);
135     }
136     run_sql(dbOut,
137       "INSERT INTO \"%w\"(x) VALUES('### %q ###')",
138       sqlite3_sql(pStmt)
139     );
140     run_sql(dbOut,
141       "INSERT INTO \"%w\"(x) SELECT group_concat(x,char(10))"
142       "  FROM staging ORDER BY x",
143       zOutTab
144     );
145     run_sql(dbOut, "COMMIT");
146     sqlite3_finalize(pStmt);
147     pStmt = 0;
148     zSql = zLeftover;
149   }
150   sqlite3_finalize(pStmt);
151   sqlite3_finalize(pIns);
152   return rc;
153 }
154 
155 /*
156 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
157 ** and return a pointer to the buffer. The caller is responsible for freeing
158 ** the memory.
159 **
160 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
161 ** read.
162 **
163 ** For convenience, a nul-terminator byte is always appended to the data read
164 ** from the file before the buffer is returned. This byte is not included in
165 ** the final value of (*pnByte), if applicable.
166 **
167 ** NULL is returned if any error is encountered. The final value of *pnByte
168 ** is undefined in this case.
169 */
170 static char *readFile(const char *zName, int *pnByte){
171   FILE *in = fopen(zName, "rb");
172   long nIn;
173   size_t nRead;
174   char *pBuf;
175   if( in==0 ) return 0;
176   fseek(in, 0, SEEK_END);
177   nIn = ftell(in);
178   rewind(in);
179   pBuf = sqlite3_malloc64( nIn+1 );
180   if( pBuf==0 ) return 0;
181   nRead = fread(pBuf, nIn, 1, in);
182   fclose(in);
183   if( nRead!=1 ){
184     sqlite3_free(pBuf);
185     return 0;
186   }
187   pBuf[nIn] = 0;
188   if( pnByte ) *pnByte = nIn;
189   return pBuf;
190 }
191 
192 int main(int argc, char **argv){
193   int nIn = 0;               /* Number of input files */
194   char **azIn = 0;           /* Names of input files */
195   sqlite3 *dbOut = 0;        /* Database to hold results */
196   sqlite3 *dbRun = 0;        /* Database used for tests */
197   int i, rc;
198 
199   for(i=1; i<argc; i++){
200     const char *z = argv[i];
201     if( z[0]=='-' && z[1]=='-' ) z++;
202     if( strcmp(z,"-help")==0 ){
203       printf("Usage: %s FILENAME ...\n", argv[0]);
204       return 0;
205     }
206     else if( z[0]=='-' ){
207       printf("unknown option \"%s\".  Use --help for details\n", argv[i]);
208       return 1;
209     }
210     else {
211       nIn++;
212       azIn = realloc(azIn, sizeof(azIn[0])*nIn);
213       if( azIn==0 ){
214         printf("out of memory\n");
215         exit(1);
216       }
217       azIn[nIn-1] = argv[i];
218     }
219   }
220 
221   sqlite3_open(":memory:", &dbOut);
222   sqlite3_open(":memory:", &dbRun);
223   sqlite3_deserialize(dbRun, "main", data001, sizeof(data001),
224                       sizeof(data001), SQLITE_DESERIALIZE_READONLY);
225   for(i=0; i<nIn; i++){
226     char *zSql = readFile(azIn[i], 0);
227     sqlite3_stmt *pCk;
228     sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, dbRun, 0);
229     rc = optfuzz_exec(dbRun, zSql, dbOut, "opt");
230     if( rc==SQLITE_OK ){
231       sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, dbRun, 0xffff);
232       rc = optfuzz_exec(dbRun, zSql, dbOut, "noopt");
233       if( rc ){
234         printf("Non-optimized run failed.  Error: %s\n", sqlite3_errmsg(dbRun));
235         exit(1);
236       }
237       pCk = prepare_sql(dbOut,
238            "SELECT (SELECT group_concat(x) FROM opt)=="
239            "       (SELECT group_concat(x) FROM noopt)");
240       rc = sqlite3_step(pCk);
241       if( rc!=SQLITE_ROW ){
242         printf("Comparison failed. %s\n", sqlite3_errmsg(dbOut));
243         exit(1);
244       }
245       if( !sqlite3_column_int(pCk, 0) ){
246         printf("Opt/no-opt outputs differ for %s\n", azIn[i]);
247         exit(1);
248       }
249       sqlite3_finalize(pCk);
250     }
251     sqlite3_free(zSql);
252   }
253   sqlite3_close(dbRun);
254   sqlite3_close(dbOut);
255   free(azIn);
256   if( sqlite3_memory_used() ){
257     printf("Memory leak of %lld bytes\n", sqlite3_memory_used());
258     exit(1);
259   }
260   return 0;
261 }
262