xref: /sqlite-3.40.0/test/fuzzinvariants.c (revision 3961b263)
1 /*
2 ** 2022-06-14
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 library is used by fuzzcheck to test query invariants.
14 **
15 ** An sqlite3_stmt is passed in that has just returned SQLITE_ROW.  This
16 ** routine does:
17 **
18 **     *   Record the output of the current row
19 **     *   Construct an alternative query that should return the same row
20 **     *   Run the alternative query and verify that it does in fact return
21 **         the same row
22 **
23 */
24 #include "sqlite3.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <ctype.h>
29 
30 /* Forward references */
31 static char *fuzz_invariant_sql(sqlite3_stmt*, int);
32 static int sameValue(sqlite3_stmt*,int,sqlite3_stmt*,int);
33 static void reportInvariantFailed(sqlite3_stmt*,sqlite3_stmt*,int);
34 
35 /*
36 ** Do an invariant check on pStmt.  iCnt determines which invariant check to
37 ** perform.  The first check is iCnt==0.
38 **
39 ** *pbCorrupt is a flag that, if true, indicates that the database file
40 ** is known to be corrupt.  A value of non-zero means "yes, the database
41 ** is corrupt".  A zero value means "we do not know whether or not the
42 ** database is corrupt".  The value might be set prior to entry, or this
43 ** routine might set the value.
44 **
45 ** Return values:
46 **
47 **     SQLITE_OK          This check was successful.
48 **
49 **     SQLITE_DONE        iCnt is out of range.
50 **
51 **     SQLITE_CORRUPT     The invariant failed, but the underlying database
52 **                        file is indicating that it is corrupt, which might
53 **                        be the cause of the malfunction.
54 **
55 **     SQLITE_INTERNAL    The invariant failed, and the database file is not
56 **                        corrupt.  (This never happens because this function
57 **                        will call abort() following an invariant failure.)
58 **
59 **     (other)            Some other kind of error occurred.
60 */
61 int fuzz_invariant(
62   sqlite3 *db,            /* The database connection */
63   sqlite3_stmt *pStmt,    /* Test statement stopped on an SQLITE_ROW */
64   int iCnt,               /* Invariant sequence number, starting at 0 */
65   int iRow,               /* Current row number */
66   int nRow,               /* Number of output rows from pStmt */
67   int *pbCorrupt,         /* IN/OUT: Flag indicating a corrupt database file */
68   int eVerbosity          /* How much debugging output */
69 ){
70   char *zTest;
71   sqlite3_stmt *pTestStmt = 0;
72   int rc;
73   int i;
74   int nCol;
75   int nParam;
76 
77   if( *pbCorrupt ) return SQLITE_DONE;
78   nParam = sqlite3_bind_parameter_count(pStmt);
79   if( nParam>100 ) return SQLITE_DONE;
80   zTest = fuzz_invariant_sql(pStmt, iCnt);
81   if( zTest==0 ) return SQLITE_DONE;
82   rc = sqlite3_prepare_v2(db, zTest, -1, &pTestStmt, 0);
83   if( rc ){
84     if( eVerbosity ){
85       printf("invariant compile failed: %s\n%s\n",
86              sqlite3_errmsg(db), zTest);
87     }
88     sqlite3_free(zTest);
89     sqlite3_finalize(pTestStmt);
90     return rc;
91   }
92   sqlite3_free(zTest);
93   nCol = sqlite3_column_count(pStmt);
94   for(i=0; i<nCol; i++){
95     rc = sqlite3_bind_value(pTestStmt,i+1+nParam,sqlite3_column_value(pStmt,i));
96     if( rc!=SQLITE_OK && rc!=SQLITE_RANGE ){
97       sqlite3_finalize(pTestStmt);
98       return rc;
99     }
100   }
101   if( eVerbosity>=2 ){
102     char *zSql = sqlite3_expanded_sql(pTestStmt);
103     printf("invariant-sql #%d:\n%s\n", iCnt, zSql);
104     sqlite3_free(zSql);
105   }
106   while( (rc = sqlite3_step(pTestStmt))==SQLITE_ROW ){
107     for(i=0; i<nCol; i++){
108       if( !sameValue(pStmt, i, pTestStmt, i) ) break;
109     }
110     if( i>=nCol ) break;
111   }
112   if( rc==SQLITE_DONE ){
113     /* No matching output row found */
114     sqlite3_stmt *pCk = 0;
115     rc = sqlite3_prepare_v2(db, "PRAGMA integrity_check", -1, &pCk, 0);
116     if( rc ){
117       sqlite3_finalize(pCk);
118       sqlite3_finalize(pTestStmt);
119       return rc;
120     }
121     rc = sqlite3_step(pCk);
122     if( rc!=SQLITE_ROW
123      || sqlite3_column_text(pCk, 0)==0
124      || strcmp((const char*)sqlite3_column_text(pCk,0),"ok")!=0
125     ){
126       *pbCorrupt = 1;
127       sqlite3_finalize(pCk);
128       sqlite3_finalize(pTestStmt);
129       return SQLITE_CORRUPT;
130     }
131     sqlite3_finalize(pCk);
132     rc = sqlite3_prepare_v2(db,
133             "SELECT 1 FROM bytecode(?1) WHERE opcode='VOpen'", -1, &pCk, 0);
134     if( rc==SQLITE_OK ){
135       sqlite3_bind_pointer(pCk, 1, pStmt, "stmt-pointer", 0);
136       rc = sqlite3_step(pCk);
137     }
138     sqlite3_finalize(pCk);
139     if( rc==SQLITE_DONE ){
140       reportInvariantFailed(pStmt, pTestStmt, iRow);
141       return SQLITE_INTERNAL;
142     }else if( eVerbosity>0 ){
143       printf("invariant-error ignored due to the use of virtual tables\n");
144     }
145   }
146   sqlite3_finalize(pTestStmt);
147   return SQLITE_OK;
148 }
149 
150 
151 /*
152 ** Generate SQL used to test a statement invariant.
153 **
154 ** Return 0 if the iCnt is out of range.
155 */
156 static char *fuzz_invariant_sql(sqlite3_stmt *pStmt, int iCnt){
157   const char *zIn;
158   size_t nIn;
159   const char *zAnd = "WHERE";
160   int i;
161   sqlite3_str *pTest;
162   sqlite3_stmt *pBase = 0;
163   sqlite3 *db = sqlite3_db_handle(pStmt);
164   int rc;
165   int nCol = sqlite3_column_count(pStmt);
166   int mxCnt;
167   int bDistinct = 0;
168   int bOrderBy = 0;
169   int nParam = sqlite3_bind_parameter_count(pStmt);
170 
171   iCnt++;
172   switch( iCnt % 4 ){
173     case 1:  bDistinct = 1;              break;
174     case 2:  bOrderBy = 1;               break;
175     case 3:  bDistinct = bOrderBy = 1;   break;
176   }
177   iCnt /= 4;
178   mxCnt = nCol;
179   if( iCnt<0 || iCnt>mxCnt ) return 0;
180   zIn = sqlite3_sql(pStmt);
181   if( zIn==0 ) return 0;
182   nIn = strlen(zIn);
183   while( nIn>0 && (isspace(zIn[nIn-1]) || zIn[nIn-1]==';') ) nIn--;
184   if( strchr(zIn, '?') ) return 0;
185   pTest = sqlite3_str_new(0);
186   sqlite3_str_appendf(pTest, "SELECT %s* FROM (%s",
187                       bDistinct ? "DISTINCT " : "", zIn);
188   sqlite3_str_appendf(pTest, ")");
189   rc = sqlite3_prepare_v2(db, sqlite3_str_value(pTest), -1, &pBase, 0);
190   if( rc ){
191     sqlite3_finalize(pBase);
192     pBase = pStmt;
193   }
194   for(i=0; i<sqlite3_column_count(pStmt); i++){
195     const char *zColName = sqlite3_column_name(pBase,i);
196     const char *zSuffix = zColName ? strrchr(zColName, ':') : 0;
197     if( zSuffix
198      && isdigit(zSuffix[1])
199      && (zSuffix[1]>'3' || isdigit(zSuffix[2]))
200     ){
201       /* This is a randomized column name and so cannot be used in the
202       ** WHERE clause. */
203       continue;
204     }
205     if( i+1!=iCnt ) continue;
206     if( zColName==0 ) continue;
207     if( sqlite3_column_type(pStmt, i)==SQLITE_NULL ){
208       sqlite3_str_appendf(pTest, " %s \"%w\" ISNULL", zAnd, zColName);
209     }else{
210       sqlite3_str_appendf(pTest, " %s \"%w\"=?%d", zAnd, zColName,
211                           i+1+nParam);
212     }
213     zAnd = "AND";
214   }
215   if( pBase!=pStmt ) sqlite3_finalize(pBase);
216   if( bOrderBy ){
217     sqlite3_str_appendf(pTest, " ORDER BY 1");
218   }
219   return sqlite3_str_finish(pTest);
220 }
221 
222 /*
223 ** Return true if and only if v1 and is the same as v2.
224 */
225 static int sameValue(sqlite3_stmt *pS1, int i1, sqlite3_stmt *pS2, int i2){
226   int x = 1;
227   int t1 = sqlite3_column_type(pS1,i1);
228   int t2 = sqlite3_column_type(pS2,i2);
229   if( t1!=t2 ){
230     if( (t1==SQLITE_INTEGER && t2==SQLITE_FLOAT)
231      || (t1==SQLITE_FLOAT && t2==SQLITE_INTEGER)
232     ){
233       /* Comparison of numerics is ok */
234     }else{
235       return 0;
236     }
237   }
238   switch( sqlite3_column_type(pS1,i1) ){
239     case SQLITE_INTEGER: {
240       x =  sqlite3_column_int64(pS1,i1)==sqlite3_column_int64(pS2,i2);
241       break;
242     }
243     case SQLITE_FLOAT: {
244       x = sqlite3_column_double(pS1,i1)==sqlite3_column_double(pS2,i2);
245       break;
246     }
247     case SQLITE_TEXT: {
248       const char *z1 = (const char*)sqlite3_column_text(pS1,i1);
249       const char *z2 = (const char*)sqlite3_column_text(pS2,i2);
250       x = ((z1==0 && z2==0) || (z1!=0 && z2!=0 && strcmp(z1,z1)==0));
251       break;
252     }
253     case SQLITE_BLOB: {
254       int len1 = sqlite3_column_bytes(pS1,i1);
255       const unsigned char *b1 = sqlite3_column_blob(pS1,i1);
256       int len2 = sqlite3_column_bytes(pS2,i2);
257       const unsigned char *b2 = sqlite3_column_blob(pS2,i2);
258       if( len1!=len2 ){
259         x = 0;
260       }else if( len1==0 ){
261         x = 1;
262       }else{
263         x = (b1!=0 && b2!=0 && memcmp(b1,b2,len1)==0);
264       }
265       break;
266     }
267   }
268   return x;
269 }
270 
271 /*
272 ** Print a single row from the prepared statement
273 */
274 static void printRow(sqlite3_stmt *pStmt, int iRow){
275   int i, nCol;
276   nCol = sqlite3_column_count(pStmt);
277   for(i=0; i<nCol; i++){
278     printf("row%d.col%d = ", iRow, i);
279     switch( sqlite3_column_type(pStmt, i) ){
280       case SQLITE_NULL: {
281         printf("NULL\n");
282         break;
283       }
284       case SQLITE_INTEGER: {
285         printf("(integer) %lld\n", sqlite3_column_int64(pStmt, i));
286         break;
287       }
288       case SQLITE_FLOAT: {
289         printf("(float) %f\n", sqlite3_column_double(pStmt, i));
290         break;
291       }
292       case SQLITE_TEXT: {
293         printf("(text) \"%s\"\n", sqlite3_column_text(pStmt, i));
294         break;
295       }
296       case SQLITE_BLOB: {
297         int n = sqlite3_column_bytes(pStmt, i);
298         int j;
299         unsigned const char *data = sqlite3_column_blob(pStmt, i);
300         printf("(blob %d bytes) x'", n);
301         for(j=0; j<20 && j<n; j++){
302           printf("%02x", data[j]);
303         }
304         if( j<n ) printf("...");
305         printf("'\n");
306         break;
307       }
308     }
309   }
310 }
311 
312 /*
313 ** Report a failure of the invariant:  The current output row of pOrig
314 ** does not appear in any row of the output from pTest.
315 */
316 static void reportInvariantFailed(
317   sqlite3_stmt *pOrig,   /* The original query */
318   sqlite3_stmt *pTest,   /* The alternative test query with a missing row */
319   int iRow               /* Row number in pOrig */
320 ){
321   int iTestRow = 0;
322   printf("Invariant check failed on row %d.\n", iRow);
323   printf("Original query --------------------------------------------------\n");
324   printf("%s\n", sqlite3_expanded_sql(pOrig));
325   printf("Alternative query -----------------------------------------------\n");
326   printf("%s\n", sqlite3_expanded_sql(pTest));
327   printf("Result row that is missing from the alternative -----------------\n");
328   printRow(pOrig, iRow);
329   printf("Complete results from the alternative query ---------------------\n");
330   sqlite3_reset(pTest);
331   while( sqlite3_step(pTest)==SQLITE_ROW ){
332     iTestRow++;
333     printRow(pTest, iTestRow);
334   }
335   sqlite3_finalize(pTest);
336   abort();
337 }
338