interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / misc / fuzzer.c

1195 lines · 36855 bytes Raw Blame History
1/*
2** 2011 March 24
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** Code for a demonstration virtual table that generates variations
14** on an input word at increasing edit distances from the original.
15**
16** A fuzzer virtual table is created like this:
17**
18** CREATE VIRTUAL TABLE f USING fuzzer(<fuzzer-data-table>);
19**
20** When it is created, the new fuzzer table must be supplied with the
21** name of a "fuzzer data table", which must reside in the same database
22** file as the new fuzzer table. The fuzzer data table contains the various
23** transformations and their costs that the fuzzer logic uses to generate
24** variations.
25**
26** The fuzzer data table must contain exactly four columns (more precisely,
27** the statement "SELECT * FROM <fuzzer_data_table>" must return records
28** that consist of four columns). It does not matter what the columns are
29** named.
30**
31** Each row in the fuzzer data table represents a single character
32** transformation. The left most column of the row (column 0) contains an
33** integer value - the identifier of the ruleset to which the transformation
34** rule belongs (see "MULTIPLE RULE SETS" below). The second column of the
35** row (column 0) contains the input character or characters. The third
36** column contains the output character or characters. And the fourth column
37** contains the integer cost of making the transformation. For example:
38**
39** CREATE TABLE f_data(ruleset, cFrom, cTo, Cost);
40** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, '', 'a', 100);
41** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'b', '', 87);
42** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'o', 'oe', 38);
43** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'oe', 'o', 40);
44**
45** The first row inserted into the fuzzer data table by the SQL script
46** above indicates that the cost of inserting a letter 'a' is 100. (All
47** costs are integers. We recommend that costs be scaled so that the
48** average cost is around 100.) The second INSERT statement creates a rule
49** saying that the cost of deleting a single letter 'b' is 87. The third
50** and fourth INSERT statements mean that the cost of transforming a
51** single letter "o" into the two-letter sequence "oe" is 38 and that the
52** cost of transforming "oe" back into "o" is 40.
53**
54** The contents of the fuzzer data table are loaded into main memory when
55** a fuzzer table is first created, and may be internally reloaded by the
56** system at any subsequent time. Therefore, the fuzzer data table should be
57** populated before the fuzzer table is created and not modified thereafter.
58** If you do need to modify the contents of the fuzzer data table, it is
59** recommended that the associated fuzzer table be dropped, the fuzzer data
60** table edited, and the fuzzer table recreated within a single transaction.
61** Alternatively, the fuzzer data table can be edited then the database
62** connection can be closed and reopened.
63**
64** Once it has been created, the fuzzer table can be queried as follows:
65**
66** SELECT word, distance FROM f
67** WHERE word MATCH 'abcdefg'
68** AND distance<200;
69**
70** This first query outputs the string "abcdefg" and all strings that
71** can be derived from that string by applying the specified transformations.
72** The strings are output together with their total transformation cost
73** (called "distance") and appear in order of increasing cost. No string
74** is output more than once. If there are multiple ways to transform the
75** target string into the output string then the lowest cost transform is
76** the one that is returned. In the example, the search is limited to
77** strings with a total distance of less than 200.
78**
79** The fuzzer is a read-only table. Any attempt to DELETE, INSERT, or
80** UPDATE on a fuzzer table will throw an error.
81**
82** It is important to put some kind of a limit on the fuzzer output. This
83** can be either in the form of a LIMIT clause at the end of the query,
84** or better, a "distance<NNN" constraint where NNN is some number. The
85** running time and memory requirement is exponential in the value of NNN
86** so you want to make sure that NNN is not too big. A value of NNN that
87** is about twice the average transformation cost seems to give good results.
88**
89** The fuzzer table can be useful for tasks such as spelling correction.
90** Suppose there is a second table vocabulary(w) where the w column contains
91** all correctly spelled words. Let $word be a word you want to look up.
92**
93** SELECT vocabulary.w FROM f, vocabulary
94** WHERE f.word MATCH $word
95** AND f.distance<=200
96** AND f.word=vocabulary.w
97** LIMIT 20
98**
99** The query above gives the 20 closest words to the $word being tested.
100** (Note that for good performance, the vocabulary.w column should be
101** indexed.)
102**
103** A similar query can be used to find all words in the dictionary that
104** begin with some prefix $prefix:
105**
106** SELECT vocabulary.w FROM f, vocabulary
107** WHERE f.word MATCH $prefix
108** AND f.distance<=200
109** AND vocabulary.w BETWEEN f.word AND (f.word || x'F7BFBFBF')
110** LIMIT 50
111**
112** This last query will show up to 50 words out of the vocabulary that
113** match or nearly match the $prefix.
114**
115** MULTIPLE RULE SETS
116**
117** Normally, the "ruleset" value associated with all character transformations
118** in the fuzzer data table is zero. However, if required, the fuzzer table
119** allows multiple rulesets to be defined. Each query uses only a single
120** ruleset. This allows, for example, a single fuzzer table to support
121** multiple languages.
122**
123** By default, only the rules from ruleset 0 are used. To specify an
124** alternative ruleset, a "ruleset = ?" expression must be added to the
125** WHERE clause of a SELECT, where ? is the identifier of the desired
126** ruleset. For example:
127**
128** SELECT vocabulary.w FROM f, vocabulary
129** WHERE f.word MATCH $word
130** AND f.distance<=200
131** AND f.word=vocabulary.w
132** AND f.ruleset=1 -- Specify the ruleset to use here
133** LIMIT 20
134**
135** If no "ruleset = ?" constraint is specified in the WHERE clause, ruleset
136** 0 is used.
137**
138** LIMITS
139**
140** The maximum ruleset number is 2147483647. The maximum length of either
141** of the strings in the second or third column of the fuzzer data table
142** is 50 bytes. The maximum cost on a rule is 1000.
143*/
144#include "sqlite3ext.h"
145SQLITE_EXTENSION_INIT1
146
147/* If SQLITE_DEBUG is not defined, disable assert statements. */
148#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
149# define NDEBUG
150#endif
151
152#include <stdlib.h>
153#include <string.h>
154#include <assert.h>
155#include <stdio.h>
156
157#ifndef SQLITE_OMIT_VIRTUALTABLE
158
159/*
160** Forward declaration of objects used by this implementation
161*/
162typedef struct fuzzer_vtab fuzzer_vtab;
163typedef struct fuzzer_cursor fuzzer_cursor;
164typedef struct fuzzer_rule fuzzer_rule;
165typedef struct fuzzer_seen fuzzer_seen;
166typedef struct fuzzer_stem fuzzer_stem;
167
168/*
169** Various types.
170**
171** fuzzer_cost is the "cost" of an edit operation.
172**
173** fuzzer_len is the length of a matching string.
174**
175** fuzzer_ruleid is an ruleset identifier.
176*/
177typedef int fuzzer_cost;
178typedef signed char fuzzer_len;
179typedef int fuzzer_ruleid;
180
181/*
182** Limits
183*/
184#define FUZZER_MX_LENGTH 50 /* Maximum length of a rule string */
185#define FUZZER_MX_RULEID 2147483647 /* Maximum rule ID */
186#define FUZZER_MX_COST 1000 /* Maximum single-rule cost */
187#define FUZZER_MX_OUTPUT_LENGTH 100 /* Maximum length of an output string */
188
189
190/*
191** Each transformation rule is stored as an instance of this object.
192** All rules are kept on a linked list sorted by rCost.
193*/
194struct fuzzer_rule {
195 fuzzer_rule *pNext; /* Next rule in order of increasing rCost */
196 char *zFrom; /* Transform from */
197 fuzzer_cost rCost; /* Cost of this transformation */
198 fuzzer_len nFrom, nTo; /* Length of the zFrom and zTo strings */
199 fuzzer_ruleid iRuleset; /* The rule set to which this rule belongs */
200 char zTo[4]; /* Transform to (extra space appended) */
201};
202
203/*
204** A stem object is used to generate variants. It is also used to record
205** previously generated outputs.
206**
207** Every stem is added to a hash table as it is output. Generation of
208** duplicate stems is suppressed.
209**
210** Active stems (those that might generate new outputs) are kept on a linked
211** list sorted by increasing cost. The cost is the sum of rBaseCost and
212** pRule->rCost.
213*/
214struct fuzzer_stem {
215 char *zBasis; /* Word being fuzzed */
216 const fuzzer_rule *pRule; /* Current rule to apply */
217 fuzzer_stem *pNext; /* Next stem in rCost order */
218 fuzzer_stem *pHash; /* Next stem with same hash on zBasis */
219 fuzzer_cost rBaseCost; /* Base cost of getting to zBasis */
220 fuzzer_cost rCostX; /* Precomputed rBaseCost + pRule->rCost */
221 fuzzer_len nBasis; /* Length of the zBasis string */
222 fuzzer_len n; /* Apply pRule at this character offset */
223};
224
225/*
226** A fuzzer virtual-table object
227*/
228struct fuzzer_vtab {
229 sqlite3_vtab base; /* Base class - must be first */
230 char *zClassName; /* Name of this class. Default: "fuzzer" */
231 fuzzer_rule *pRule; /* All active rules in this fuzzer */
232 int nCursor; /* Number of active cursors */
233};
234
235#define FUZZER_HASH 4001 /* Hash table size */
236#define FUZZER_NQUEUE 20 /* Number of slots on the stem queue */
237
238/* A fuzzer cursor object */
239struct fuzzer_cursor {
240 sqlite3_vtab_cursor base; /* Base class - must be first */
241 sqlite3_int64 iRowid; /* The rowid of the current word */
242 fuzzer_vtab *pVtab; /* The virtual table this cursor belongs to */
243 fuzzer_cost rLimit; /* Maximum cost of any term */
244 fuzzer_stem *pStem; /* Stem with smallest rCostX */
245 fuzzer_stem *pDone; /* Stems already processed to completion */
246 fuzzer_stem *aQueue[FUZZER_NQUEUE]; /* Queue of stems with higher rCostX */
247 int mxQueue; /* Largest used index in aQueue[] */
248 char *zBuf; /* Temporary use buffer */
249 int nBuf; /* Bytes allocated for zBuf */
250 int nStem; /* Number of stems allocated */
251 int iRuleset; /* Only process rules from this ruleset */
252 fuzzer_rule nullRule; /* Null rule used first */
253 fuzzer_stem *apHash[FUZZER_HASH]; /* Hash of previously generated terms */
254};
255
256/*
257** The two input rule lists are both sorted in order of increasing
258** cost. Merge them together into a single list, sorted by cost, and
259** return a pointer to the head of that list.
260*/
261static fuzzer_rule *fuzzerMergeRules(fuzzer_rule *pA, fuzzer_rule *pB){
262 fuzzer_rule head;
263 fuzzer_rule *pTail;
264
265 pTail = &head;
266 while( pA && pB ){
267 if( pA->rCost<=pB->rCost ){
268 pTail->pNext = pA;
269 pTail = pA;
270 pA = pA->pNext;
271 }else{
272 pTail->pNext = pB;
273 pTail = pB;
274 pB = pB->pNext;
275 }
276 }
277 if( pA==0 ){
278 pTail->pNext = pB;
279 }else{
280 pTail->pNext = pA;
281 }
282 return head.pNext;
283}
284
285/*
286** Statement pStmt currently points to a row in the fuzzer data table. This
287** function allocates and populates a fuzzer_rule structure according to
288** the content of the row.
289**
290** If successful, *ppRule is set to point to the new object and SQLITE_OK
291** is returned. Otherwise, *ppRule is zeroed, *pzErr may be set to point
292** to an error message and an SQLite error code returned.
293*/
294static int fuzzerLoadOneRule(
295 fuzzer_vtab *p, /* Fuzzer virtual table handle */
296 sqlite3_stmt *pStmt, /* Base rule on statements current row */
297 fuzzer_rule **ppRule, /* OUT: New rule object */
298 char **pzErr /* OUT: Error message */
299){
300 sqlite3_int64 iRuleset = sqlite3_column_int64(pStmt, 0);
301 const char *zFrom = (const char *)sqlite3_column_text(pStmt, 1);
302 const char *zTo = (const char *)sqlite3_column_text(pStmt, 2);
303 int nCost = sqlite3_column_int(pStmt, 3);
304
305 int rc = SQLITE_OK; /* Return code */
306 int nFrom; /* Size of string zFrom, in bytes */
307 int nTo; /* Size of string zTo, in bytes */
308 fuzzer_rule *pRule = 0; /* New rule object to return */
309
310 if( zFrom==0 ) zFrom = "";
311 if( zTo==0 ) zTo = "";
312 nFrom = (int)strlen(zFrom);
313 nTo = (int)strlen(zTo);
314
315 /* Silently ignore null transformations */
316 if( strcmp(zFrom, zTo)==0 ){
317 *ppRule = 0;
318 return SQLITE_OK;
319 }
320
321 if( nCost<=0 || nCost>FUZZER_MX_COST ){
322 *pzErr = sqlite3_mprintf("%s: cost must be between 1 and %d",
323 p->zClassName, FUZZER_MX_COST
324 );
325 rc = SQLITE_ERROR;
326 }else
327 if( nFrom>FUZZER_MX_LENGTH || nTo>FUZZER_MX_LENGTH ){
328 *pzErr = sqlite3_mprintf("%s: maximum string length is %d",
329 p->zClassName, FUZZER_MX_LENGTH
330 );
331 rc = SQLITE_ERROR;
332 }else
333 if( iRuleset<0 || iRuleset>FUZZER_MX_RULEID ){
334 *pzErr = sqlite3_mprintf("%s: ruleset must be between 0 and %d",
335 p->zClassName, FUZZER_MX_RULEID
336 );
337 rc = SQLITE_ERROR;
338 }else{
339
340 pRule = sqlite3_malloc64( sizeof(*pRule) + nFrom + nTo );
341 if( pRule==0 ){
342 rc = SQLITE_NOMEM;
343 }else{
344 memset(pRule, 0, sizeof(*pRule));
345 pRule->zFrom = pRule->zTo;
346 pRule->zFrom += nTo + 1;
347 pRule->nFrom = (fuzzer_len)nFrom;
348 memcpy(pRule->zFrom, zFrom, nFrom+1);
349 memcpy(pRule->zTo, zTo, nTo+1);
350 pRule->nTo = (fuzzer_len)nTo;
351 pRule->rCost = nCost;
352 pRule->iRuleset = (int)iRuleset;
353 }
354 }
355
356 *ppRule = pRule;
357 return rc;
358}
359
360/*
361** Load the content of the fuzzer data table into memory.
362*/
363static int fuzzerLoadRules(
364 sqlite3 *db, /* Database handle */
365 fuzzer_vtab *p, /* Virtual fuzzer table to configure */
366 const char *zDb, /* Database containing rules data */
367 const char *zData, /* Table containing rules data */
368 char **pzErr /* OUT: Error message */
369){
370 int rc = SQLITE_OK; /* Return code */
371 char *zSql; /* SELECT used to read from rules table */
372 fuzzer_rule *pHead = 0;
373
374 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zData);
375 if( zSql==0 ){
376 rc = SQLITE_NOMEM;
377 }else{
378 int rc2; /* finalize() return code */
379 sqlite3_stmt *pStmt = 0;
380 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
381 if( rc!=SQLITE_OK ){
382 *pzErr = sqlite3_mprintf("%s: %s", p->zClassName, sqlite3_errmsg(db));
383 }else if( sqlite3_column_count(pStmt)!=4 ){
384 *pzErr = sqlite3_mprintf("%s: %s has %d columns, expected 4",
385 p->zClassName, zData, sqlite3_column_count(pStmt)
386 );
387 rc = SQLITE_ERROR;
388 }else{
389 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
390 fuzzer_rule *pRule = 0;
391 rc = fuzzerLoadOneRule(p, pStmt, &pRule, pzErr);
392 if( pRule ){
393 pRule->pNext = pHead;
394 pHead = pRule;
395 }
396 }
397 }
398 rc2 = sqlite3_finalize(pStmt);
399 if( rc==SQLITE_OK ) rc = rc2;
400 }
401 sqlite3_free(zSql);
402
403 /* All rules are now in a singly linked list starting at pHead. This
404 ** block sorts them by cost and then sets fuzzer_vtab.pRule to point to
405 ** point to the head of the sorted list.
406 */
407 if( rc==SQLITE_OK ){
408 unsigned int i;
409 fuzzer_rule *pX;
410 fuzzer_rule *a[15];
411 for(i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = 0;
412 while( (pX = pHead)!=0 ){
413 pHead = pX->pNext;
414 pX->pNext = 0;
415 for(i=0; a[i] && i<sizeof(a)/sizeof(a[0])-1; i++){
416 pX = fuzzerMergeRules(a[i], pX);
417 a[i] = 0;
418 }
419 a[i] = fuzzerMergeRules(a[i], pX);
420 }
421 for(pX=a[0], i=1; i<sizeof(a)/sizeof(a[0]); i++){
422 pX = fuzzerMergeRules(a[i], pX);
423 }
424 p->pRule = fuzzerMergeRules(p->pRule, pX);
425 }else{
426 /* An error has occurred. Setting p->pRule to point to the head of the
427 ** allocated list ensures that the list will be cleaned up in this case.
428 */
429 assert( p->pRule==0 );
430 p->pRule = pHead;
431 }
432
433 return rc;
434}
435
436/*
437** This function converts an SQL quoted string into an unquoted string
438** and returns a pointer to a buffer allocated using sqlite3_malloc()
439** containing the result. The caller should eventually free this buffer
440** using sqlite3_free.
441**
442** Examples:
443**
444** "abc" becomes abc
445** 'xyz' becomes xyz
446** [pqr] becomes pqr
447** `mno` becomes mno
448*/
449static char *fuzzerDequote(const char *zIn){
450 sqlite3_int64 nIn; /* Size of input string, in bytes */
451 char *zOut; /* Output (dequoted) string */
452
453 nIn = strlen(zIn);
454 zOut = sqlite3_malloc64(nIn+1);
455 if( zOut ){
456 char q = zIn[0]; /* Quote character (if any ) */
457
458 if( q!='[' && q!= '\'' && q!='"' && q!='`' ){
459 memcpy(zOut, zIn, (size_t)(nIn+1));
460 }else{
461 int iOut = 0; /* Index of next byte to write to output */
462 int iIn; /* Index of next byte to read from input */
463
464 if( q=='[' ) q = ']';
465 for(iIn=1; iIn<nIn; iIn++){
466 if( zIn[iIn]==q ) iIn++;
467 zOut[iOut++] = zIn[iIn];
468 }
469 assert( iOut<=nIn );
470 zOut[iOut] = 0;
471 }
472 assert( (int)strlen(zOut)<=nIn );
473 }
474 return zOut;
475}
476
477/*
478** xDisconnect/xDestroy method for the fuzzer module.
479*/
480static int fuzzerDisconnect(sqlite3_vtab *pVtab){
481 fuzzer_vtab *p = (fuzzer_vtab*)pVtab;
482 assert( p->nCursor==0 );
483 while( p->pRule ){
484 fuzzer_rule *pRule = p->pRule;
485 p->pRule = pRule->pNext;
486 sqlite3_free(pRule);
487 }
488 sqlite3_free(p);
489 return SQLITE_OK;
490}
491
492/*
493** xConnect/xCreate method for the fuzzer module. Arguments are:
494**
495** argv[0] -> module name ("fuzzer")
496** argv[1] -> database name
497** argv[2] -> table name
498** argv[3] -> fuzzer rule table name
499*/
500static int fuzzerConnect(
501 sqlite3 *db,
502 void *pAux,
503 int argc, const char *const*argv,
504 sqlite3_vtab **ppVtab,
505 char **pzErr
506){
507 int rc = SQLITE_OK; /* Return code */
508 fuzzer_vtab *pNew = 0; /* New virtual table */
509 const char *zModule = argv[0];
510 const char *zDb = argv[1];
511
512 if( argc!=4 ){
513 *pzErr = sqlite3_mprintf(
514 "%s: wrong number of CREATE VIRTUAL TABLE arguments", zModule
515 );
516 rc = SQLITE_ERROR;
517 }else{
518 sqlite3_int64 nModule; /* Length of zModule, in bytes */
519
520 nModule = strlen(zModule);
521 pNew = sqlite3_malloc64( sizeof(*pNew) + nModule + 1);
522 if( pNew==0 ){
523 rc = SQLITE_NOMEM;
524 }else{
525 char *zTab; /* Dequoted name of fuzzer data table */
526
527 memset(pNew, 0, sizeof(*pNew));
528 pNew->zClassName = (char*)&pNew[1];
529 memcpy(pNew->zClassName, zModule, (size_t)(nModule+1));
530
531 zTab = fuzzerDequote(argv[3]);
532 if( zTab==0 ){
533 rc = SQLITE_NOMEM;
534 }else{
535 rc = fuzzerLoadRules(db, pNew, zDb, zTab, pzErr);
536 sqlite3_free(zTab);
537 }
538
539 if( rc==SQLITE_OK ){
540 rc = sqlite3_declare_vtab(db, "CREATE TABLE x(word,distance,ruleset)");
541 }
542 if( rc!=SQLITE_OK ){
543 fuzzerDisconnect((sqlite3_vtab *)pNew);
544 pNew = 0;
545 }else{
546 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
547 }
548 }
549 }
550
551 *ppVtab = (sqlite3_vtab *)pNew;
552 return rc;
553}
554
555/*
556** Open a new fuzzer cursor.
557*/
558static int fuzzerOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
559 fuzzer_vtab *p = (fuzzer_vtab*)pVTab;
560 fuzzer_cursor *pCur;
561 pCur = sqlite3_malloc64( sizeof(*pCur) );
562 if( pCur==0 ) return SQLITE_NOMEM;
563 memset(pCur, 0, sizeof(*pCur));
564 pCur->pVtab = p;
565 *ppCursor = &pCur->base;
566 p->nCursor++;
567 return SQLITE_OK;
568}
569
570/*
571** Free all stems in a list.
572*/
573static void fuzzerClearStemList(fuzzer_stem *pStem){
574 while( pStem ){
575 fuzzer_stem *pNext = pStem->pNext;
576 sqlite3_free(pStem);
577 pStem = pNext;
578 }
579}
580
581/*
582** Free up all the memory allocated by a cursor. Set it rLimit to 0
583** to indicate that it is at EOF.
584*/
585static void fuzzerClearCursor(fuzzer_cursor *pCur, int clearHash){
586 int i;
587 fuzzerClearStemList(pCur->pStem);
588 fuzzerClearStemList(pCur->pDone);
589 for(i=0; i<FUZZER_NQUEUE; i++) fuzzerClearStemList(pCur->aQueue[i]);
590 pCur->rLimit = (fuzzer_cost)0;
591 if( clearHash && pCur->nStem ){
592 pCur->mxQueue = 0;
593 pCur->pStem = 0;
594 pCur->pDone = 0;
595 memset(pCur->aQueue, 0, sizeof(pCur->aQueue));
596 memset(pCur->apHash, 0, sizeof(pCur->apHash));
597 }
598 pCur->nStem = 0;
599}
600
601/*
602** Close a fuzzer cursor.
603*/
604static int fuzzerClose(sqlite3_vtab_cursor *cur){
605 fuzzer_cursor *pCur = (fuzzer_cursor *)cur;
606 fuzzerClearCursor(pCur, 0);
607 sqlite3_free(pCur->zBuf);
608 pCur->pVtab->nCursor--;
609 sqlite3_free(pCur);
610 return SQLITE_OK;
611}
612
613/*
614** Compute the current output term for a fuzzer_stem.
615*/
616static int fuzzerRender(
617 fuzzer_stem *pStem, /* The stem to be rendered */
618 char **pzBuf, /* Write results into this buffer. realloc if needed */
619 int *pnBuf /* Size of the buffer */
620){
621 const fuzzer_rule *pRule = pStem->pRule;
622 sqlite3_int64 n; /* Size of output term without nul-term */
623 char *z; /* Buffer to assemble output term in */
624
625 n = pStem->nBasis + pRule->nTo - pRule->nFrom;
626 if( (*pnBuf)<n+1 ){
627 (*pzBuf) = sqlite3_realloc64((*pzBuf), n+100);
628 if( (*pzBuf)==0 ) return SQLITE_NOMEM;
629 (*pnBuf) = n+100;
630 }
631 n = pStem->n;
632 z = *pzBuf;
633 if( n<0 ){
634 memcpy(z, pStem->zBasis, pStem->nBasis+1);
635 }else{
636 memcpy(z, pStem->zBasis, n);
637 memcpy(&z[n], pRule->zTo, pRule->nTo);
638 memcpy(&z[n+pRule->nTo], &pStem->zBasis[n+pRule->nFrom],
639 pStem->nBasis-n-pRule->nFrom+1);
640 }
641
642 assert( z[pStem->nBasis + pRule->nTo - pRule->nFrom]==0 );
643 return SQLITE_OK;
644}
645
646/*
647** Compute a hash on zBasis.
648*/
649static unsigned int fuzzerHash(const char *z){
650 unsigned int h = 0;
651 while( *z ){ h = (h<<3) ^ (h>>29) ^ *(z++); }
652 return h % FUZZER_HASH;
653}
654
655/*
656** Current cost of a stem
657*/
658static fuzzer_cost fuzzerCost(fuzzer_stem *pStem){
659 return pStem->rCostX = pStem->rBaseCost + pStem->pRule->rCost;
660}
661
662#if 0
663/*
664** Print a description of a fuzzer_stem on stderr.
665*/
666static void fuzzerStemPrint(
667 const char *zPrefix,
668 fuzzer_stem *pStem,
669 const char *zSuffix
670){
671 if( pStem->n<0 ){
672 fprintf(stderr, "%s[%s](%d)-->self%s",
673 zPrefix,
674 pStem->zBasis, pStem->rBaseCost,
675 zSuffix
676 );
677 }else{
678 char *zBuf = 0;
679 int nBuf = 0;
680 if( fuzzerRender(pStem, &zBuf, &nBuf)!=SQLITE_OK ) return;
681 fprintf(stderr, "%s[%s](%d)-->{%s}(%d)%s",
682 zPrefix,
683 pStem->zBasis, pStem->rBaseCost, zBuf, pStem->,
684 zSuffix
685 );
686 sqlite3_free(zBuf);
687 }
688}
689#endif
690
691/*
692** Return 1 if the string to which the cursor is point has already
693** been emitted. Return 0 if not. Return -1 on a memory allocation
694** failures.
695*/
696static int fuzzerSeen(fuzzer_cursor *pCur, fuzzer_stem *pStem){
697 unsigned int h;
698 fuzzer_stem *pLookup;
699
700 if( fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){
701 return -1;
702 }
703 h = fuzzerHash(pCur->zBuf);
704 pLookup = pCur->apHash[h];
705 while( pLookup && strcmp(pLookup->zBasis, pCur->zBuf)!=0 ){
706 pLookup = pLookup->pHash;
707 }
708 return pLookup!=0;
709}
710
711/*
712** If argument pRule is NULL, this function returns false.
713**
714** Otherwise, it returns true if rule pRule should be skipped. A rule
715** should be skipped if it does not belong to rule-set iRuleset, or if
716** applying it to stem pStem would create a string longer than
717** FUZZER_MX_OUTPUT_LENGTH bytes.
718*/
719static int fuzzerSkipRule(
720 const fuzzer_rule *pRule, /* Determine whether or not to skip this */
721 fuzzer_stem *pStem, /* Stem rule may be applied to */
722 int iRuleset /* Rule-set used by the current query */
723){
724 return pRule && (
725 (pRule->iRuleset!=iRuleset)
726 || (pStem->nBasis + pRule->nTo - pRule->nFrom)>FUZZER_MX_OUTPUT_LENGTH
727 );
728}
729
730/*
731** Advance a fuzzer_stem to its next value. Return 0 if there are
732** no more values that can be generated by this fuzzer_stem. Return
733** -1 on a memory allocation failure.
734*/
735static int fuzzerAdvance(fuzzer_cursor *pCur, fuzzer_stem *pStem){
736 const fuzzer_rule *pRule;
737 while( (pRule = pStem->pRule)!=0 ){
738 assert( pRule==&pCur->nullRule || pRule->iRuleset==pCur->iRuleset );
739 while( pStem->n < pStem->nBasis - pRule->nFrom ){
740 pStem->n++;
741 if( pRule->nFrom==0
742 || memcmp(&pStem->zBasis[pStem->n], pRule->zFrom, pRule->nFrom)==0
743 ){
744 /* Found a rewrite case. Make sure it is not a duplicate */
745 int rc = fuzzerSeen(pCur, pStem);
746 if( rc<0 ) return -1;
747 if( rc==0 ){
748 fuzzerCost(pStem);
749 return 1;
750 }
751 }
752 }
753 pStem->n = -1;
754 do{
755 pRule = pRule->pNext;
756 }while( fuzzerSkipRule(pRule, pStem, pCur->iRuleset) );
757 pStem->pRule = pRule;
758 if( pRule && fuzzerCost(pStem)>pCur->rLimit ) pStem->pRule = 0;
759 }
760 return 0;
761}
762
763/*
764** The two input stem lists are both sorted in order of increasing
765** rCostX. Merge them together into a single list, sorted by rCostX, and
766** return a pointer to the head of that new list.
767*/
768static fuzzer_stem *fuzzerMergeStems(fuzzer_stem *pA, fuzzer_stem *pB){
769 fuzzer_stem head;
770 fuzzer_stem *pTail;
771
772 pTail = &head;
773 while( pA && pB ){
774 if( pA->rCostX<=pB->rCostX ){
775 pTail->pNext = pA;
776 pTail = pA;
777 pA = pA->pNext;
778 }else{
779 pTail->pNext = pB;
780 pTail = pB;
781 pB = pB->pNext;
782 }
783 }
784 if( pA==0 ){
785 pTail->pNext = pB;
786 }else{
787 pTail->pNext = pA;
788 }
789 return head.pNext;
790}
791
792/*
793** Load pCur->pStem with the lowest-cost stem. Return a pointer
794** to the lowest-cost stem.
795*/
796static fuzzer_stem *fuzzerLowestCostStem(fuzzer_cursor *pCur){
797 fuzzer_stem *pBest, *pX;
798 int iBest;
799 int i;
800
801 if( pCur->pStem==0 ){
802 iBest = -1;
803 pBest = 0;
804 for(i=0; i<=pCur->mxQueue; i++){
805 pX = pCur->aQueue[i];
806 if( pX==0 ) continue;
807 if( pBest==0 || pBest->rCostX>pX->rCostX ){
808 pBest = pX;
809 iBest = i;
810 }
811 }
812 if( pBest ){
813 pCur->aQueue[iBest] = pBest->pNext;
814 pBest->pNext = 0;
815 pCur->pStem = pBest;
816 }
817 }
818 return pCur->pStem;
819}
820
821/*
822** Insert pNew into queue of pending stems. Then find the stem
823** with the lowest rCostX and move it into pCur->pStem.
824** list. The insert is done such the pNew is in the correct order
825** according to fuzzer_stem.zBaseCost+fuzzer_stem.pRule->rCost.
826*/
827static fuzzer_stem *fuzzerInsert(fuzzer_cursor *pCur, fuzzer_stem *pNew){
828 fuzzer_stem *pX;
829 int i;
830
831 /* If pCur->pStem exists and is greater than pNew, then make pNew
832 ** the new pCur->pStem and insert the old pCur->pStem instead.
833 */
834 if( (pX = pCur->pStem)!=0 && pX->rCostX>pNew->rCostX ){
835 pNew->pNext = 0;
836 pCur->pStem = pNew;
837 pNew = pX;
838 }
839
840 /* Insert the new value */
841 pNew->pNext = 0;
842 pX = pNew;
843 for(i=0; i<=pCur->mxQueue; i++){
844 if( pCur->aQueue[i] ){
845 pX = fuzzerMergeStems(pX, pCur->aQueue[i]);
846 pCur->aQueue[i] = 0;
847 }else{
848 pCur->aQueue[i] = pX;
849 break;
850 }
851 }
852 if( i>pCur->mxQueue ){
853 if( i<FUZZER_NQUEUE ){
854 pCur->mxQueue = i;
855 pCur->aQueue[i] = pX;
856 }else{
857 assert( pCur->mxQueue==FUZZER_NQUEUE-1 );
858 pX = fuzzerMergeStems(pX, pCur->aQueue[FUZZER_NQUEUE-1]);
859 pCur->aQueue[FUZZER_NQUEUE-1] = pX;
860 }
861 }
862
863 return fuzzerLowestCostStem(pCur);
864}
865
866/*
867** Allocate a new fuzzer_stem. Add it to the hash table but do not
868** link it into either the pCur->pStem or pCur->pDone lists.
869*/
870static fuzzer_stem *fuzzerNewStem(
871 fuzzer_cursor *pCur,
872 const char *zWord,
873 fuzzer_cost rBaseCost
874){
875 fuzzer_stem *pNew;
876 fuzzer_rule *pRule;
877 unsigned int h;
878
879 pNew = sqlite3_malloc64( sizeof(*pNew) + strlen(zWord) + 1 );
880 if( pNew==0 ) return 0;
881 memset(pNew, 0, sizeof(*pNew));
882 pNew->zBasis = (char*)&pNew[1];
883 pNew->nBasis = (fuzzer_len)strlen(zWord);
884 memcpy(pNew->zBasis, zWord, pNew->nBasis+1);
885 pRule = pCur->pVtab->pRule;
886 while( fuzzerSkipRule(pRule, pNew, pCur->iRuleset) ){
887 pRule = pRule->pNext;
888 }
889 pNew->pRule = pRule;
890 pNew->n = -1;
891 pNew->rBaseCost = pNew->rCostX = rBaseCost;
892 h = fuzzerHash(pNew->zBasis);
893 pNew->pHash = pCur->apHash[h];
894 pCur->apHash[h] = pNew;
895 pCur->nStem++;
896 return pNew;
897}
898
899
900/*
901** Advance a cursor to its next row of output
902*/
903static int fuzzerNext(sqlite3_vtab_cursor *cur){
904 fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
905 int rc;
906 fuzzer_stem *pStem, *pNew;
907
908 pCur->iRowid++;
909
910 /* Use the element the cursor is currently point to to create
911 ** a new stem and insert the new stem into the priority queue.
912 */
913 pStem = pCur->pStem;
914 if( pStem->rCostX>0 ){
915 rc = fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf);
916 if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
917 pNew = fuzzerNewStem(pCur, pCur->zBuf, pStem->rCostX);
918 if( pNew ){
919 if( fuzzerAdvance(pCur, pNew)==0 ){
920 pNew->pNext = pCur->pDone;
921 pCur->pDone = pNew;
922 }else{
923 if( fuzzerInsert(pCur, pNew)==pNew ){
924 return SQLITE_OK;
925 }
926 }
927 }else{
928 return SQLITE_NOMEM;
929 }
930 }
931
932 /* Adjust the priority queue so that the first element of the
933 ** stem list is the next lowest cost word.
934 */
935 while( (pStem = pCur->pStem)!=0 ){
936 int res = fuzzerAdvance(pCur, pStem);
937 if( res<0 ){
938 return SQLITE_NOMEM;
939 }else if( res>0 ){
940 pCur->pStem = 0;
941 pStem = fuzzerInsert(pCur, pStem);
942 if( (rc = fuzzerSeen(pCur, pStem))!=0 ){
943 if( rc<0 ) return SQLITE_NOMEM;
944 continue;
945 }
946 return SQLITE_OK; /* New word found */
947 }
948 pCur->pStem = 0;
949 pStem->pNext = pCur->pDone;
950 pCur->pDone = pStem;
951 if( fuzzerLowestCostStem(pCur) ){
952 rc = fuzzerSeen(pCur, pCur->pStem);
953 if( rc<0 ) return SQLITE_NOMEM;
954 if( rc==0 ){
955 return SQLITE_OK;
956 }
957 }
958 }
959
960 /* Reach this point only if queue has been exhausted and there is
961 ** nothing left to be output. */
962 pCur->rLimit = (fuzzer_cost)0;
963 return SQLITE_OK;
964}
965
966/*
967** Called to "rewind" a cursor back to the beginning so that
968** it starts its output over again. Always called at least once
969** prior to any fuzzerColumn, fuzzerRowid, or fuzzerEof call.
970*/
971static int fuzzerFilter(
972 sqlite3_vtab_cursor *pVtabCursor,
973 int idxNum, const char *idxStr,
974 int argc, sqlite3_value **argv
975){
976 fuzzer_cursor *pCur = (fuzzer_cursor *)pVtabCursor;
977 const char *zWord = "";
978 fuzzer_stem *pStem;
979 int idx;
980
981 fuzzerClearCursor(pCur, 1);
982 pCur->rLimit = 2147483647;
983 idx = 0;
984 if( idxNum & 1 ){
985 zWord = (const char*)sqlite3_value_text(argv[0]);
986 if( zWord==0 ) zWord = "";
987 idx++;
988 }
989 if( idxNum & 2 ){
990 pCur->rLimit = (fuzzer_cost)sqlite3_value_int(argv[idx]);
991 idx++;
992 }
993 if( idxNum & 4 ){
994 pCur->iRuleset = (fuzzer_cost)sqlite3_value_int(argv[idx]);
995 idx++;
996 }
997 pCur->nullRule.pNext = pCur->pVtab->pRule;
998 pCur->nullRule.rCost = 0;
999 pCur->nullRule.nFrom = 0;
1000 pCur->nullRule.nTo = 0;
1001 pCur->nullRule.zFrom = "";
1002 pCur->iRowid = 1;
1003 assert( pCur->pStem==0 );
1004
1005 /* If the query term is longer than FUZZER_MX_OUTPUT_LENGTH bytes, this
1006 ** query will return zero rows. */
1007 if( (int)strlen(zWord)<FUZZER_MX_OUTPUT_LENGTH ){
1008 pCur->pStem = pStem = fuzzerNewStem(pCur, zWord, (fuzzer_cost)0);
1009 if( pStem==0 ) return SQLITE_NOMEM;
1010 pStem->pRule = &pCur->nullRule;
1011 pStem->n = pStem->nBasis;
1012 }else{
1013 pCur->rLimit = 0;
1014 }
1015
1016 return SQLITE_OK;
1017}
1018
1019/*
1020** Only the word and distance columns have values. All other columns
1021** return NULL
1022*/
1023static int fuzzerColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1024 fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
1025 if( i==0 ){
1026 /* the "word" column */
1027 if( fuzzerRender(pCur->pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){
1028 return SQLITE_NOMEM;
1029 }
1030 sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT);
1031 }else if( i==1 ){
1032 /* the "distance" column */
1033 sqlite3_result_int(ctx, pCur->pStem->rCostX);
1034 }else{
1035 /* All other columns are NULL */
1036 sqlite3_result_null(ctx);
1037 }
1038 return SQLITE_OK;
1039}
1040
1041/*
1042** The rowid.
1043*/
1044static int fuzzerRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1045 fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
1046 *pRowid = pCur->iRowid;
1047 return SQLITE_OK;
1048}
1049
1050/*
1051** When the fuzzer_cursor.rLimit value is 0 or less, that is a signal
1052** that the cursor has nothing more to output.
1053*/
1054static int fuzzerEof(sqlite3_vtab_cursor *cur){
1055 fuzzer_cursor *pCur = (fuzzer_cursor*)cur;
1056 return pCur->rLimit<=(fuzzer_cost)0;
1057}
1058
1059/*
1060** Search for terms of these forms:
1061**
1062** (A) word MATCH $str
1063** (B1) distance < $value
1064** (B2) distance <= $value
1065** (C) ruleid == $ruleid
1066**
1067** The distance< and distance<= are both treated as distance<=.
1068** The query plan number is a bit vector:
1069**
1070** bit 1: Term of the form (A) found
1071** bit 2: Term like (B1) or (B2) found
1072** bit 3: Term like (C) found
1073**
1074** If bit-1 is set, $str is always in filter.argv[0]. If bit-2 is set
1075** then $value is in filter.argv[0] if bit-1 is clear and is in
1076** filter.argv[1] if bit-1 is set. If bit-3 is set, then $ruleid is
1077** in filter.argv[0] if bit-1 and bit-2 are both zero, is in
1078** filter.argv[1] if exactly one of bit-1 and bit-2 are set, and is in
1079** filter.argv[2] if both bit-1 and bit-2 are set.
1080*/
1081static int fuzzerBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1082 int iPlan = 0;
1083 int iDistTerm = -1;
1084 int iRulesetTerm = -1;
1085 int i;
1086 int seenMatch = 0;
1087 const struct sqlite3_index_constraint *pConstraint;
1088 double rCost = 1e12;
1089
1090 pConstraint = pIdxInfo->aConstraint;
1091 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1092 if( pConstraint->iColumn==0
1093 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
1094 seenMatch = 1;
1095 }
1096 if( pConstraint->usable==0 ) continue;
1097 if( (iPlan & 1)==0
1098 && pConstraint->iColumn==0
1099 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH
1100 ){
1101 iPlan |= 1;
1102 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
1103 pIdxInfo->aConstraintUsage[i].omit = 1;
1104 rCost /= 1e6;
1105 }
1106 if( (iPlan & 2)==0
1107 && pConstraint->iColumn==1
1108 && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT
1109 || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE)
1110 ){
1111 iPlan |= 2;
1112 iDistTerm = i;
1113 rCost /= 10.0;
1114 }
1115 if( (iPlan & 4)==0
1116 && pConstraint->iColumn==2
1117 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ
1118 ){
1119 iPlan |= 4;
1120 pIdxInfo->aConstraintUsage[i].omit = 1;
1121 iRulesetTerm = i;
1122 rCost /= 10.0;
1123 }
1124 }
1125 if( iPlan & 2 ){
1126 pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 1+((iPlan&1)!=0);
1127 }
1128 if( iPlan & 4 ){
1129 int idx = 1;
1130 if( iPlan & 1 ) idx++;
1131 if( iPlan & 2 ) idx++;
1132 pIdxInfo->aConstraintUsage[iRulesetTerm].argvIndex = idx;
1133 }
1134 pIdxInfo->idxNum = iPlan;
1135 if( pIdxInfo->nOrderBy==1
1136 && pIdxInfo->aOrderBy[0].iColumn==1
1137 && pIdxInfo->aOrderBy[0].desc==0
1138 ){
1139 pIdxInfo->orderByConsumed = 1;
1140 }
1141 if( seenMatch && (iPlan&1)==0 ) rCost = 1e99;
1142 pIdxInfo->estimatedCost = rCost;
1143
1144 return SQLITE_OK;
1145}
1146
1147/*
1148** A virtual table module that implements the "fuzzer".
1149*/
1150static sqlite3_module fuzzerModule = {
1151 0, /* iVersion */
1152 fuzzerConnect,
1153 fuzzerConnect,
1154 fuzzerBestIndex,
1155 fuzzerDisconnect,
1156 fuzzerDisconnect,
1157 fuzzerOpen, /* xOpen - open a cursor */
1158 fuzzerClose, /* xClose - close a cursor */
1159 fuzzerFilter, /* xFilter - configure scan constraints */
1160 fuzzerNext, /* xNext - advance a cursor */
1161 fuzzerEof, /* xEof - check for end of scan */
1162 fuzzerColumn, /* xColumn - read data */
1163 fuzzerRowid, /* xRowid - read data */
1164 0, /* xUpdate */
1165 0, /* xBegin */
1166 0, /* xSync */
1167 0, /* xCommit */
1168 0, /* xRollback */
1169 0, /* xFindMethod */
1170 0, /* xRename */
1171 0, /* xSavepoint */
1172 0, /* xRelease */
1173 0, /* xRollbackTo */
1174 0, /* xShadowName */
1175 0 /* xIntegrity */
1176};
1177
1178#endif /* SQLITE_OMIT_VIRTUALTABLE */
1179
1180
1181#ifdef _WIN32
1182__declspec(dllexport)
1183#endif
1184int sqlite3_fuzzer_init(
1185 sqlite3 *db,
1186 char **pzErrMsg,
1187 const sqlite3_api_routines *pApi
1188){
1189 int rc = SQLITE_OK;
1190 SQLITE_EXTENSION_INIT2(pApi);
1191#ifndef SQLITE_OMIT_VIRTUALTABLE
1192 rc = sqlite3_create_module(db, "fuzzer", &fuzzerModule, 0);
1193#endif
1194 return rc;
1195}