forked from sqlite/sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuzzcheck.c
2591 lines (2467 loc) · 80.8 KB
/
fuzzcheck.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** 2015-05-25
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a utility program designed to aid running regressions tests on
** the SQLite library using data from external fuzzers.
**
** This program reads content from an SQLite database file with the following
** schema:
**
** CREATE TABLE db(
** dbid INTEGER PRIMARY KEY, -- database id
** dbcontent BLOB -- database disk file image
** );
** CREATE TABLE xsql(
** sqlid INTEGER PRIMARY KEY, -- SQL script id
** sqltext TEXT -- Text of SQL statements to run
** );
** CREATE TABLE IF NOT EXISTS readme(
** msg TEXT -- Human-readable description of this test collection
** );
**
** For each database file in the DB table, the SQL text in the XSQL table
** is run against that database. All README.MSG values are printed prior
** to the start of the test (unless the --quiet option is used). If the
** DB table is empty, then all entries in XSQL are run against an empty
** in-memory database.
**
** This program is looking for crashes, assertion faults, and/or memory leaks.
** No attempt is made to verify the output. The assumption is that either all
** of the database files or all of the SQL statements are malformed inputs,
** generated by a fuzzer, that need to be checked to make sure they do not
** present a security risk.
**
** This program also includes some command-line options to help with
** creation and maintenance of the source content database. The command
**
** ./fuzzcheck database.db --load-sql FILE...
**
** Loads all FILE... arguments into the XSQL table. The --load-db option
** works the same but loads the files into the DB table. The -m option can
** be used to initialize the README table. The "database.db" file is created
** if it does not previously exist. Example:
**
** ./fuzzcheck new.db --load-sql *.sql
** ./fuzzcheck new.db --load-db *.db
** ./fuzzcheck new.db -m 'New test cases'
**
** The three commands above will create the "new.db" file and initialize all
** tables. Then do "./fuzzcheck new.db" to run the tests.
**
** DEBUGGING HINTS:
**
** If fuzzcheck does crash, it can be run in the debugger and the content
** of the global variable g.zTextName[] will identify the specific XSQL and
** DB values that were running when the crash occurred.
**
** DBSQLFUZZ: (Added 2020-02-25)
**
** The dbsqlfuzz fuzzer includes both a database file and SQL to run against
** that database in its input. This utility can now process dbsqlfuzz
** input files. Load such files using the "--load-dbsql FILE ..." command-line
** option.
**
** Dbsqlfuzz inputs are ordinary text. The first part of the file is text
** that describes the content of the database (using a lot of hexadecimal),
** then there is a divider line followed by the SQL to run against the
** database. Because they are ordinary text, dbsqlfuzz inputs are stored
** in the XSQL table, as if they were ordinary SQL inputs. The isDbSql()
** function can look at a text string and determine whether or not it is
** a valid dbsqlfuzz input.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <assert.h>
#include "sqlite3.h"
#include "sqlite3recover.h"
#define ISSPACE(X) isspace((unsigned char)(X))
#define ISDIGIT(X) isdigit((unsigned char)(X))
#ifdef __unix__
# include <signal.h>
# include <unistd.h>
#endif
#include <stddef.h>
#if !defined(_MSC_VER)
# include <stdint.h>
#endif
#if defined(_MSC_VER)
typedef unsigned char uint8_t;
#endif
/*
** Files in the virtual file system.
*/
typedef struct VFile VFile;
struct VFile {
char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
int sz; /* Size of the file in bytes */
int nRef; /* Number of references to this file */
unsigned char *a; /* Content of the file. From malloc() */
};
typedef struct VHandle VHandle;
struct VHandle {
sqlite3_file base; /* Base class. Must be first */
VFile *pVFile; /* The underlying file */
};
/*
** The value of a database file template, or of an SQL script
*/
typedef struct Blob Blob;
struct Blob {
Blob *pNext; /* Next in a list */
int id; /* Id of this Blob */
int seq; /* Sequence number */
int sz; /* Size of this Blob in bytes */
unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
};
/*
** Maximum number of files in the in-memory virtual filesystem.
*/
#define MX_FILE 10
/*
** Maximum allowed file size
*/
#define MX_FILE_SZ 10000000
/*
** All global variables are gathered into the "g" singleton.
*/
static struct GlobalVars {
const char *zArgv0; /* Name of program */
const char *zDbFile; /* Name of database file */
VFile aFile[MX_FILE]; /* The virtual filesystem */
int nDb; /* Number of template databases */
Blob *pFirstDb; /* Content of first template database */
int nSql; /* Number of SQL scripts */
Blob *pFirstSql; /* First SQL script */
unsigned int uRandom; /* Seed for the SQLite PRNG */
unsigned int nInvariant; /* Number of invariant checks run */
char zTestName[100]; /* Name of current test */
} g;
/*
** Include various extensions.
*/
extern int sqlite3_vt02_init(sqlite3*,char**,const sqlite3_api_routines*);
extern int sqlite3_randomjson_init(sqlite3*,char**,const sqlite3_api_routines*);
extern int sqlite3_percentile_init(sqlite3*,char**,const sqlite3_api_routines*);
/*
** Print an error message and quit.
*/
static void fatalError(const char *zFormat, ...){
va_list ap;
fprintf(stderr, "%s", g.zArgv0);
if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
fprintf(stderr, ": ");
va_start(ap, zFormat);
vfprintf(stderr, zFormat, ap);
va_end(ap);
fprintf(stderr, "\n");
exit(1);
}
/*
** signal handler
*/
#ifdef __unix__
static void signalHandler(int signum){
const char *zSig;
if( signum==SIGABRT ){
zSig = "abort";
}else if( signum==SIGALRM ){
zSig = "timeout";
}else if( signum==SIGSEGV ){
zSig = "segfault";
}else{
zSig = "signal";
}
fatalError(zSig);
}
#endif
/*
** Set the an alarm to go off after N seconds. Disable the alarm
** if N==0
*/
static void setAlarm(int N){
#ifdef __unix__
alarm(N);
#else
(void)N;
#endif
}
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
/*
** This an SQL progress handler. After an SQL statement has run for
** many steps, we want to interrupt it. This guards against infinite
** loops from recursive common table expressions.
**
** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
** In that case, hitting the progress handler is a fatal error.
*/
static int progressHandler(void *pVdbeLimitFlag){
if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
return 1;
}
#endif
/*
** Reallocate memory. Show an error and quit if unable.
*/
static void *safe_realloc(void *pOld, int szNew){
void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
return pNew;
}
/*
** Initialize the virtual file system.
*/
static void formatVfs(void){
int i;
for(i=0; i<MX_FILE; i++){
g.aFile[i].sz = -1;
g.aFile[i].zFilename = 0;
g.aFile[i].a = 0;
g.aFile[i].nRef = 0;
}
}
/*
** Erase all information in the virtual file system.
*/
static void reformatVfs(void){
int i;
for(i=0; i<MX_FILE; i++){
if( g.aFile[i].sz<0 ) continue;
if( g.aFile[i].zFilename ){
free(g.aFile[i].zFilename);
g.aFile[i].zFilename = 0;
}
if( g.aFile[i].nRef>0 ){
fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
}
g.aFile[i].sz = -1;
free(g.aFile[i].a);
g.aFile[i].a = 0;
g.aFile[i].nRef = 0;
}
}
/*
** Find a VFile by name
*/
static VFile *findVFile(const char *zName){
int i;
if( zName==0 ) return 0;
for(i=0; i<MX_FILE; i++){
if( g.aFile[i].zFilename==0 ) continue;
if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
}
return 0;
}
/*
** Find a VFile by name. Create it if it does not already exist and
** initialize it to the size and content given.
**
** Return NULL only if the filesystem is full.
*/
static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
VFile *pNew = findVFile(zName);
int i;
if( pNew ) return pNew;
for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
if( i>=MX_FILE ) return 0;
pNew = &g.aFile[i];
if( zName ){
int nName = (int)strlen(zName)+1;
pNew->zFilename = safe_realloc(0, nName);
memcpy(pNew->zFilename, zName, nName);
}else{
pNew->zFilename = 0;
}
pNew->nRef = 0;
pNew->sz = sz;
pNew->a = safe_realloc(0, sz);
if( sz>0 ) memcpy(pNew->a, pData, sz);
return pNew;
}
/* Return true if the line is all zeros */
static int allZero(unsigned char *aLine){
int i;
for(i=0; i<16 && aLine[i]==0; i++){}
return i==16;
}
/*
** Render a database and query as text that can be input into
** the CLI.
*/
static void renderDbSqlForCLI(
FILE *out, /* Write to this file */
const char *zFile, /* Name of the database file */
unsigned char *aDb, /* Database content */
int nDb, /* Number of bytes in aDb[] */
unsigned char *zSql, /* SQL content */
int nSql /* Bytes of SQL */
){
fprintf(out, ".print ******* %s *******\n", zFile);
if( nDb>100 ){
int i, j; /* Loop counters */
int pgsz; /* Size of each page */
int lastPage = 0; /* Last page number shown */
int iPage; /* Current page number */
unsigned char *aLine; /* Single line to display */
unsigned char buf[16]; /* Fake line */
unsigned char bShow[256]; /* Characters ok to display */
memset(bShow, '.', sizeof(bShow));
for(i=' '; i<='~'; i++){
if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
}
pgsz = (aDb[16]<<8) | aDb[17];
if( pgsz==0 ) pgsz = 65536;
if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
fprintf(out,".open --hexdb\n");
fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
for(i=0; i<nDb; i += 16){
if( i+16>nDb ){
memset(buf, 0, sizeof(buf));
memcpy(buf, aDb+i, nDb-i);
aLine = buf;
}else{
aLine = aDb + i;
}
if( allZero(aLine) ) continue;
iPage = i/pgsz + 1;
if( lastPage!=iPage ){
fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
lastPage = iPage;
}
fprintf(out,"| %5d:", i-(iPage-1)*pgsz);
for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
fprintf(out," ");
for(j=0; j<16; j++){
unsigned char c = (unsigned char)aLine[j];
fputc( bShow[c], stdout);
}
fputc('\n', stdout);
}
fprintf(out,"| end %s\n", zFile);
}else{
fprintf(out,".open :memory:\n");
}
fprintf(out,".testctrl prng_seed 1 db\n");
fprintf(out,".testctrl internal_functions\n");
fprintf(out,"%.*s", nSql, zSql);
if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
}
/*
** Read the complete content of a file into memory. Add a 0x00 terminator
** and return a pointer to the result.
**
** The file content is held in memory obtained from sqlite_malloc64() which
** should be freed by the caller.
*/
static char *readFile(const char *zFilename, long *sz){
FILE *in;
long nIn;
unsigned char *pBuf;
*sz = 0;
if( zFilename==0 ) return 0;
in = fopen(zFilename, "rb");
if( in==0 ) return 0;
fseek(in, 0, SEEK_END);
*sz = nIn = ftell(in);
rewind(in);
pBuf = sqlite3_malloc64( nIn+1 );
if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
pBuf[nIn] = 0;
fclose(in);
return (char*)pBuf;
}
sqlite3_free(pBuf);
*sz = 0;
fclose(in);
return 0;
}
/*
** Implementation of the "readfile(X)" SQL function. The entire content
** of the file named X is read and returned as a BLOB. NULL is returned
** if the file does not exist or is unreadable.
*/
static void readfileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
long nIn;
void *pBuf;
const char *zName = (const char*)sqlite3_value_text(argv[0]);
if( zName==0 ) return;
pBuf = readFile(zName, &nIn);
if( pBuf ){
sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
}
}
/*
** Implementation of the "readtextfile(X)" SQL function. The text content
** of the file named X through the end of the file or to the first \000
** character, whichever comes first, is read and returned as TEXT. NULL
** is returned if the file does not exist or is unreadable.
*/
static void readtextfileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const char *zName;
FILE *in;
long nIn;
char *pBuf;
zName = (const char*)sqlite3_value_text(argv[0]);
if( zName==0 ) return;
in = fopen(zName, "rb");
if( in==0 ) return;
fseek(in, 0, SEEK_END);
nIn = ftell(in);
rewind(in);
pBuf = sqlite3_malloc64( nIn+1 );
if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
pBuf[nIn] = 0;
sqlite3_result_text(context, pBuf, -1, sqlite3_free);
}else{
sqlite3_free(pBuf);
}
fclose(in);
}
/*
** Implementation of the "writefile(X,Y)" SQL function. The argument Y
** is written into file X. The number of bytes written is returned. Or
** NULL is returned if something goes wrong, such as being unable to open
** file X for writing.
*/
static void writefileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
FILE *out;
const char *z;
sqlite3_int64 rc;
const char *zFile;
(void)argc;
zFile = (const char*)sqlite3_value_text(argv[0]);
if( zFile==0 ) return;
out = fopen(zFile, "wb");
if( out==0 ) return;
z = (const char*)sqlite3_value_blob(argv[1]);
if( z==0 ){
rc = 0;
}else{
rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
}
fclose(out);
sqlite3_result_int64(context, rc);
}
/*
** Load a list of Blob objects from the database
*/
static void blobListLoadFromDb(
sqlite3 *db, /* Read from this database */
const char *zSql, /* Query used to extract the blobs */
int onlyId, /* Only load where id is this value */
int *pN, /* OUT: Write number of blobs loaded here */
Blob **ppList /* OUT: Write the head of the blob list here */
){
Blob head;
Blob *p;
sqlite3_stmt *pStmt;
int n = 0;
int rc;
char *z2;
if( onlyId>0 ){
z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
}else{
z2 = sqlite3_mprintf("%s", zSql);
}
rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
sqlite3_free(z2);
if( rc ) fatalError("%s", sqlite3_errmsg(db));
head.pNext = 0;
p = &head;
while( SQLITE_ROW==sqlite3_step(pStmt) ){
int sz = sqlite3_column_bytes(pStmt, 1);
Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
pNew->id = sqlite3_column_int(pStmt, 0);
pNew->sz = sz;
pNew->seq = n++;
pNew->pNext = 0;
memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
pNew->a[sz] = 0;
p->pNext = pNew;
p = pNew;
}
sqlite3_finalize(pStmt);
*pN = n;
*ppList = head.pNext;
}
/*
** Free a list of Blob objects
*/
static void blobListFree(Blob *p){
Blob *pNext;
while( p ){
pNext = p->pNext;
free(p);
p = pNext;
}
}
/* Return the current wall-clock time
**
** The number of milliseconds since the julian epoch.
** 1907-01-01 00:00:00 -> 210866716800000
** 2021-01-01 00:00:00 -> 212476176000000
*/
static sqlite3_int64 timeOfDay(void){
static sqlite3_vfs *clockVfs = 0;
sqlite3_int64 t;
if( clockVfs==0 ){
clockVfs = sqlite3_vfs_find(0);
if( clockVfs==0 ) return 0;
}
if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
clockVfs->xCurrentTimeInt64(clockVfs, &t);
}else{
double r;
clockVfs->xCurrentTime(clockVfs, &r);
t = (sqlite3_int64)(r*86400000.0);
}
return t;
}
/***************************************************************************
** Code to process combined database+SQL scripts generated by the
** dbsqlfuzz fuzzer.
*/
/* An instance of the following object is passed by pointer as the
** client data to various callbacks.
*/
typedef struct FuzzCtx {
sqlite3 *db; /* The database connection */
sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
unsigned nCb; /* Number of progress callbacks */
unsigned mxCb; /* Maximum number of progress callbacks allowed */
unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
int timeoutHit; /* True when reaching a timeout */
} FuzzCtx;
/* Verbosity level for the dbsqlfuzz test runner */
static int eVerbosity = 0;
/* True to activate PRAGMA vdbe_debug=on */
static int bVdbeDebug = 0;
/* Timeout for each fuzzing attempt, in milliseconds */
static int giTimeout = 10000; /* Defaults to 10 seconds */
/* Maximum number of progress handler callbacks */
static unsigned int mxProgressCb = 2000;
/* Maximum string length in SQLite */
static int lengthLimit = 1000000;
/* Maximum expression depth */
static int depthLimit = 500;
/* Limit on the amount of heap memory that can be used */
static sqlite3_int64 heapLimit = 100000000;
/* Maximum byte-code program length in SQLite */
static int vdbeOpLimit = 25000;
/* Maximum size of the in-memory database */
static sqlite3_int64 maxDbSize = 104857600;
/* OOM simulation parameters */
static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
/* Enable recovery */
static int bNoRecover = 0;
/* This routine is called when a simulated OOM occurs. It is broken
** out as a separate routine to make it easy to set a breakpoint on
** the OOM
*/
void oomFault(void){
if( eVerbosity ){
printf("Simulated OOM fault\n");
}
if( oomRepeat>0 ){
oomRepeat--;
}else{
oomCounter--;
}
}
/* This routine is a replacement malloc() that is used to simulate
** Out-Of-Memory (OOM) errors for testing purposes.
*/
static void *oomMalloc(int nByte){
if( oomCounter ){
if( oomCounter==1 ){
oomFault();
return 0;
}else{
oomCounter--;
}
}
return defaultMalloc(nByte);
}
/* Register the OOM simulator. This must occur before any memory
** allocations */
static void registerOomSimulator(void){
sqlite3_mem_methods mem;
sqlite3_shutdown();
sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
defaultMalloc = mem.xMalloc;
mem.xMalloc = oomMalloc;
sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
}
/* Turn off any pending OOM simulation */
static void disableOom(void){
oomCounter = 0;
oomRepeat = 0;
}
/*
** Translate a single byte of Hex into an integer.
** This routine only works if h really is a valid hexadecimal
** character: 0..9a..fA..F
*/
static unsigned char hexToInt(unsigned int h){
#ifdef SQLITE_EBCDIC
h += 9*(1&~(h>>4)); /* EBCDIC */
#else
h += 9*(1&(h>>6)); /* ASCII */
#endif
return h & 0xf;
}
/*
** The first character of buffer zIn[0..nIn-1] is a '['. This routine
** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
** does it makes corresponding changes to the *pK value and *pI value
** and returns true. If the input buffer does not match the patterns,
** no changes are made to either *pK or *pI and this routine returns false.
*/
static int isOffset(
const unsigned char *zIn, /* Text input */
int nIn, /* Bytes of input */
unsigned int *pK, /* half-byte cursor to adjust */
unsigned int *pI /* Input index to adjust */
){
int i;
unsigned int k = 0;
unsigned char c;
for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
if( !isxdigit(c) ) return 0;
k = k*16 + hexToInt(c);
}
if( i==nIn ) return 0;
*pK = 2*k;
*pI += i;
return 1;
}
/*
** Decode the text starting at zIn into a binary database file.
** The maximum length of zIn is nIn bytes. Store the binary database
** file in space obtained from sqlite3_malloc().
**
** Return the number of bytes of zIn consumed. Or return -1 if there
** is an error. One potential error is that the recipe specifies a
** database file larger than MX_FILE_SZ bytes.
**
** Abort on an OOM.
*/
static int decodeDatabase(
const unsigned char *zIn, /* Input text to be decoded */
int nIn, /* Bytes of input text */
unsigned char **paDecode, /* OUT: decoded database file */
int *pnDecode /* OUT: Size of decoded database */
){
unsigned char *a, *aNew; /* Database under construction */
int mx = 0; /* Current size of the database */
sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
unsigned int i; /* Next byte of zIn[] to read */
unsigned int j; /* Temporary integer */
unsigned int k; /* half-byte cursor index for output */
unsigned int n; /* Number of bytes of input */
unsigned char b = 0;
if( nIn<4 ) return -1;
n = (unsigned int)nIn;
a = sqlite3_malloc64( nAlloc );
if( a==0 ){
fprintf(stderr, "Out of memory!\n");
exit(1);
}
memset(a, 0, (size_t)nAlloc);
for(i=k=0; i<n; i++){
unsigned char c = (unsigned char)zIn[i];
if( isxdigit(c) ){
k++;
if( k & 1 ){
b = hexToInt(c)*16;
}else{
b += hexToInt(c);
j = k/2 - 1;
if( j>=nAlloc ){
sqlite3_uint64 newSize;
if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
if( eVerbosity ){
fprintf(stderr, "Input database too big: max %d bytes\n",
MX_FILE_SZ);
}
sqlite3_free(a);
return -1;
}
newSize = nAlloc*2;
if( newSize<=j ){
newSize = (j+4096)&~4095;
}
if( newSize>MX_FILE_SZ ){
if( j>=MX_FILE_SZ ){
sqlite3_free(a);
return -1;
}
newSize = MX_FILE_SZ;
}
aNew = sqlite3_realloc64( a, newSize );
if( aNew==0 ){
sqlite3_free(a);
return -1;
}
a = aNew;
assert( newSize > nAlloc );
memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
nAlloc = newSize;
}
if( j>=(unsigned)mx ){
mx = (j + 4095)&~4095;
if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
}
assert( j<nAlloc );
a[j] = b;
}
}else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
continue;
}else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
i += 4;
break;
}
}
*pnDecode = mx;
*paDecode = a;
return i;
}
/*
** Progress handler callback.
**
** The argument is the cutoff-time after which all processing should
** stop. So return non-zero if the cut-off time is exceeded.
*/
static int progress_handler(void *pClientData) {
FuzzCtx *p = (FuzzCtx*)pClientData;
sqlite3_int64 iNow = timeOfDay();
int rc = iNow>=p->iCutoffTime;
sqlite3_int64 iDiff = iNow - p->iLastCb;
/* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
p->nCb++;
if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
if( rc && !p->timeoutHit && eVerbosity>=2 ){
printf("Timeout on progress callback %d\n", p->nCb);
fflush(stdout);
p->timeoutHit = 1;
}
return rc;
}
/*
** Flag bits set by block_troublesome_sql()
*/
#define BTS_SELECT 0x000001
#define BTS_NONSELECT 0x000002
#define BTS_BADFUNC 0x000004
#define BTS_BADPRAGMA 0x000008 /* Sticky for rest of the script */
/*
** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
** "PRAGMA parser_trace" since they can dramatically increase the
** amount of output without actually testing anything useful.
**
** Also block ATTACH if attaching a file from the filesystem.
*/
static int block_troublesome_sql(
void *pClientData,
int eCode,
const char *zArg1,
const char *zArg2,
const char *zArg3,
const char *zArg4
){
unsigned int *pBtsFlags = (unsigned int*)pClientData;
(void)zArg3;
(void)zArg4;
switch( eCode ){
case SQLITE_PRAGMA: {
if( sqlite3_stricmp("busy_timeout",zArg1)==0
&& (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
){
return SQLITE_DENY;
}else if( sqlite3_stricmp("hard_heap_limit", zArg1)==0
|| sqlite3_stricmp("reverse_unordered_selects", zArg1)==0
){
/* BTS_BADPRAGMA is sticky. A hard_heap_limit or
** revert_unordered_selects should inhibit all future attempts
** at verifying query invariants */
*pBtsFlags |= BTS_BADPRAGMA;
}else if( eVerbosity==0 ){
if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
|| sqlite3_stricmp("parser_trace", zArg1)==0
|| sqlite3_stricmp("temp_store_directory", zArg1)==0
){
return SQLITE_DENY;
}
}else if( sqlite3_stricmp("oom",zArg1)==0
&& zArg2!=0 && zArg2[0]!=0 ){
oomCounter = atoi(zArg2);
}
*pBtsFlags |= BTS_NONSELECT;
break;
}
case SQLITE_ATTACH: {
/* Deny the ATTACH if it is attaching anything other than an in-memory
** database. */
*pBtsFlags |= BTS_NONSELECT;
if( zArg1==0 ) return SQLITE_DENY;
if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
&& sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
){
return SQLITE_OK;
}
return SQLITE_DENY;
}
case SQLITE_SELECT: {
*pBtsFlags |= BTS_SELECT;
break;
}
case SQLITE_FUNCTION: {
static const char *azBadFuncs[] = {
"avg",
"count",
"cume_dist",
"current_date",
"current_time",
"current_timestamp",
"date",
"datetime",
"decimal_sum",
"dense_rank",
"first_value",
"geopoly_group_bbox",
"group_concat",
"implies_nonnull_row",
"json_group_array",
"json_group_object",
"julianday",
"lag",
"last_value",
"lead",
"max",
"min",
"nth_value",
"ntile",
"percent_rank",
"random",
"randomblob",
"rank",
"row_number",
"sqlite_offset",
"strftime",
"sum",
"time",
"total",
"unixepoch",
};
int first, last;
first = 0;
last = sizeof(azBadFuncs)/sizeof(azBadFuncs[0]) - 1;
do{
int mid = (first+last)/2;
int c = sqlite3_stricmp(azBadFuncs[mid], zArg2);
if( c<0 ){
first = mid+1;
}else if( c>0 ){
last = mid-1;
}else{
*pBtsFlags |= BTS_BADFUNC;
break;
}
}while( first<=last );
break;
}
case SQLITE_READ: {
/* Benign */
break;
}
default: {
*pBtsFlags |= BTS_NONSELECT;
}
}
return SQLITE_OK;
}
/* Implementation found in fuzzinvariant.c */
extern int fuzz_invariant(
sqlite3 *db, /* The database connection */
sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */
int iCnt, /* Invariant sequence number, starting at 0 */
int iRow, /* The row number for pStmt */
int nRow, /* Total number of output rows */
int *pbCorrupt, /* IN/OUT: Flag indicating a corrupt database file */
int eVerbosity, /* How much debugging output */
unsigned int dbOpt /* Default optimization flags */
);
/* Implementation of sqlite_dbdata and sqlite_dbptr */
extern int sqlite3_dbdata_init(sqlite3*,const char**,void*);
/*
** This function is used as a callback by the recover extension. Simply
** print the supplied SQL statement to stdout.
*/
static int recoverSqlCb(void *pCtx, const char *zSql){
if( eVerbosity>=2 ){
printf("%s\n", zSql);
}
return SQLITE_OK;
}