SQLite

Check-in [ef6e071a62]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Enhance fuzzershell.c to read and execute SQL commands in the autoexec table of the database under test. Add the dbfuzz.c test program combining selected features of fuzzershell.c and fuzzcheck.c.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: ef6e071a62cd79a0edbbef9f41ca9482540e5cb8
User & Date: drh 2016-12-17 20:27:22.394
Context
2016-12-17
21:07
Refinements to the new dbfuzz test program. (check-in: 50325abe79 user: drh tags: trunk)
20:27
Enhance fuzzershell.c to read and execute SQL commands in the autoexec table of the database under test. Add the dbfuzz.c test program combining selected features of fuzzershell.c and fuzzcheck.c. (check-in: ef6e071a62 user: drh tags: trunk)
08:18
Fix a problem in the shell tools readfile() command causing blobs to be truncated at the first embedded 0x00 byte in release builds, or an assert() to fail in a debug build. (check-in: 8dedd6ad44 user: dan tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to Makefile.in.
563
564
565
566
567
568
569

570
571
572
573
574
575
576
SHELL_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_FTS4
# SHELL_OPT += -DSQLITE_ENABLE_FTS5
SHELL_OPT += -DSQLITE_ENABLE_EXPLAIN_COMMENTS
SHELL_OPT += -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
FUZZERSHELL_OPT = -DSQLITE_ENABLE_JSON1
FUZZCHECK_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MEMSYS5 -DSQLITE_OSS_FUZZ
FUZZCHECK_SRC = $(TOP)/test/fuzzcheck.c $(TOP)/test/ossfuzz.c


# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la)

Makefile: $(TOP)/Makefile.in







>







563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
SHELL_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_FTS4
# SHELL_OPT += -DSQLITE_ENABLE_FTS5
SHELL_OPT += -DSQLITE_ENABLE_EXPLAIN_COMMENTS
SHELL_OPT += -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
FUZZERSHELL_OPT = -DSQLITE_ENABLE_JSON1
FUZZCHECK_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MEMSYS5 -DSQLITE_OSS_FUZZ
FUZZCHECK_SRC = $(TOP)/test/fuzzcheck.c $(TOP)/test/ossfuzz.c
DBFUZZ_OPT = 

# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la)

Makefile: $(TOP)/Makefile.in
617
618
619
620
621
622
623



624
625
626
627
628
629
630

fuzzcheck$(TEXE):	$(FUZZCHECK_SRC) sqlite3.c sqlite3.h
	$(LTLINK) -o $@ $(FUZZCHECK_OPT) $(FUZZCHECK_SRC) sqlite3.c $(TLIBS)

ossshell$(TEXE):	$(TOP)/test/ossfuzz.c $(TOP)/test/ossshell.c sqlite3.c sqlite3.h
	$(LTLINK) -o $@ $(FUZZCHECK_OPT) $(TOP)/test/ossshell.c sqlite3.c sqlite3.h $(TLIBS)




mptester$(TEXE):	sqlite3.lo $(TOP)/mptest/mptest.c
	$(LTLINK) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.lo \
		$(TLIBS) -rpath "$(libdir)"

MPTEST1=./mptester$(TEXE) mptest.db $(TOP)/mptest/crash01.test --repeat 20
MPTEST2=./mptester$(TEXE) mptest.db $(TOP)/mptest/multiwrite01.test --repeat 20
mptest:	mptester$(TEXE)







>
>
>







618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634

fuzzcheck$(TEXE):	$(FUZZCHECK_SRC) sqlite3.c sqlite3.h
	$(LTLINK) -o $@ $(FUZZCHECK_OPT) $(FUZZCHECK_SRC) sqlite3.c $(TLIBS)

ossshell$(TEXE):	$(TOP)/test/ossfuzz.c $(TOP)/test/ossshell.c sqlite3.c sqlite3.h
	$(LTLINK) -o $@ $(FUZZCHECK_OPT) $(TOP)/test/ossshell.c sqlite3.c sqlite3.h $(TLIBS)

dbfuzz$(TEXE):	$(TOP)/test/dbfuzz.c sqlite3.c sqlite3.h
	$(LTLINK) -o $@ $(DBFUZZ_OPT) $(TOP)/test/dbfuzz.c sqlite3.c $(TLIBS)

mptester$(TEXE):	sqlite3.lo $(TOP)/mptest/mptest.c
	$(LTLINK) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.lo \
		$(TLIBS) -rpath "$(libdir)"

MPTEST1=./mptester$(TEXE) mptest.db $(TOP)/mptest/crash01.test --repeat 20
MPTEST2=./mptester$(TEXE) mptest.db $(TOP)/mptest/multiwrite01.test --repeat 20
mptest:	mptester$(TEXE)
Changes to main.mk.
473
474
475
476
477
478
479

480
481
482
483
484
485
486
# Extra compiler options for various shell tools
#
SHELL_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS5
SHELL_OPT += -DSQLITE_ENABLE_EXPLAIN_COMMENTS
SHELL_OPT += -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
FUZZERSHELL_OPT = -DSQLITE_ENABLE_JSON1
FUZZCHECK_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MEMSYS5


# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.a sqlite3$(EXE)

libsqlite3.a:	$(LIBOBJ)







>







473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# Extra compiler options for various shell tools
#
SHELL_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS5
SHELL_OPT += -DSQLITE_ENABLE_EXPLAIN_COMMENTS
SHELL_OPT += -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
FUZZERSHELL_OPT = -DSQLITE_ENABLE_JSON1
FUZZCHECK_OPT = -DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MEMSYS5
DBFUZZ_OPT =

# This is the default Makefile target.  The objects listed here
# are what get build when you type just "make" with no arguments.
#
all:	sqlite3.h libsqlite3.a sqlite3$(EXE)

libsqlite3.a:	$(LIBOBJ)
508
509
510
511
512
513
514





515
516
517
518
519
520
521
sourcetest:	srcck1$(EXE) sqlite3.c
	./srcck1 sqlite3.c

fuzzershell$(EXE):	$(TOP)/tool/fuzzershell.c sqlite3.c sqlite3.h
	$(TCCX) -o fuzzershell$(EXE) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \
	  $(FUZZERSHELL_OPT) $(TOP)/tool/fuzzershell.c sqlite3.c \
	  $(TLIBS) $(THREADLIB)






fuzzcheck$(EXE):	$(TOP)/test/fuzzcheck.c sqlite3.c sqlite3.h $(TOP)/test/ossfuzz.c
	$(TCCX) -o fuzzcheck$(EXE) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_ENABLE_MEMSYS5 $(FUZZCHECK_OPT) -DSQLITE_OSS_FUZZ \
		$(TOP)/test/fuzzcheck.c $(TOP)/test/ossfuzz.c sqlite3.c $(TLIBS) $(THREADLIB)

ossshell$(EXE):	$(TOP)/test/ossfuzz.c $(TOP)/test/ossshell.c sqlite3.c sqlite3.h







>
>
>
>
>







509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
sourcetest:	srcck1$(EXE) sqlite3.c
	./srcck1 sqlite3.c

fuzzershell$(EXE):	$(TOP)/tool/fuzzershell.c sqlite3.c sqlite3.h
	$(TCCX) -o fuzzershell$(EXE) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \
	  $(FUZZERSHELL_OPT) $(TOP)/tool/fuzzershell.c sqlite3.c \
	  $(TLIBS) $(THREADLIB)

dbfuzz$(EXE):	$(TOP)/test/dbfuzz.c sqlite3.c sqlite3.h
	$(TCCX) -o dbfuzz$(EXE) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \
	  $(DBFUZZ_OPT) $(TOP)/test/dbfuzz.c sqlite3.c \
	  $(TLIBS) $(THREADLIB)

fuzzcheck$(EXE):	$(TOP)/test/fuzzcheck.c sqlite3.c sqlite3.h $(TOP)/test/ossfuzz.c
	$(TCCX) -o fuzzcheck$(EXE) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_ENABLE_MEMSYS5 $(FUZZCHECK_OPT) -DSQLITE_OSS_FUZZ \
		$(TOP)/test/fuzzcheck.c $(TOP)/test/ossfuzz.c sqlite3.c $(TLIBS) $(THREADLIB)

ossshell$(EXE):	$(TOP)/test/ossfuzz.c $(TOP)/test/ossshell.c sqlite3.c sqlite3.h
Added test/dbfuzz.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
/*
** 2016-12-17
**
** 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 program is designed for fuzz-testing SQLite database files.
**
** This program reads fuzzed database files from the disk files named
** on the command-line.  Each database is loaded into an in-memory
** filesystem so that the original database file is unmolested.
**
** The fuzzed database is then opened, and series of SQL statements
** are run against the database to ensure that SQLite can safely handle
** the fuzzed database.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#define ISSPACE(X) isspace((unsigned char)(X))
#define ISDIGIT(X) isdigit((unsigned char)(X))
#include "sqlite3.h"
#ifdef __unix__
# include <signal.h>
# include <unistd.h>
#endif

/*
** Print sketchy documentation for this utility program
*/
static void showHelp(const char *zArgv0){
  printf("Usage: %s [options] DATABASE ...\n", zArgv0);
  printf(
"Read databases into an in-memory filesystem.  Run test SQL as specified\n"
"by command-line arguments or from\n"
"\n"
"    SELECT group_concat(sql) FROM autoexec;\n"
"\n"
"Options:\n"
"  --help              Show this help text\n"
"  -q|--quiet          Reduced output\n"
"  --limit-mem N       Limit memory used by test SQLite instances to N bytes\n"
"  --limit-vdbe        Panic if any test runs for more than 100,000 cycles\n"
"  --no-lookaside      Disable the lookaside memory allocator\n"
"  --timeout N         Timeout after N seconds.\n"
"  --trace             Show the results of each SQL command\n"
"  -v|--verbose        Increased output.  Repeat for more output.\n"
  );
  exit(0);
}

/*
** Print an error message and quit.
*/
static void fatalError(const char *zFormat, ...){
  va_list ap;
  va_start(ap, zFormat);
  vfprintf(stderr, zFormat, ap);
  va_end(ap);
  fprintf(stderr, "\n");
  exit(1);
}

/*
** Files in the virtual file system.
*/
typedef struct VFile VFile;
typedef struct VHandle VHandle;
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() */
};
struct VHandle {
  sqlite3_file base;    /* Base class.  Must be first */
  VFile *pVFile;        /* The underlying file */
};

/*
** Maximum number of files in the in-memory virtual filesystem.
*/
#define MX_FILE  10

/*
** Maximum allowed file size
*/
#define MX_FILE_SZ 1000000

/*
** All global variables are gathered into the "g" singleton.
*/
static struct GlobalVars {
  VFile aFile[MX_FILE];            /* The virtual filesystem */
} g;


/*
** 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 called zName.  Initialize it to the content of
** disk file zDiskFile.
**
** Return NULL if the filesystem is full.
*/
static VFile *createVFile(const char *zName, const char *zDiskFile){
  VFile *pNew = findVFile(zName);
  int i;
  FILE *in = 0;
  long sz = 0;

  if( pNew ) return pNew;
  for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
  if( i>=MX_FILE ) return 0;
  if( zDiskFile ){
    in = fopen(zDiskFile, "rb");
    if( in==0 ) fatalError("no such file: \"%s\"", zDiskFile);
    fseek(in, 0, SEEK_END);
    sz = ftell(in);
    rewind(in);
  }
  pNew = &g.aFile[i];
  if( zName ){
    int nName = (int)strlen(zName)+1;
    pNew->zFilename = malloc(nName);
    if( pNew->zFilename==0 ){
      if( in ) fclose(in);
      return 0;
    }
    memcpy(pNew->zFilename, zName, nName);
  }else{
    pNew->zFilename = 0;
  }
  pNew->nRef = 0;
  pNew->sz = sz;
  pNew->a = malloc(sz);
  if( sz>0 ){
    if( pNew->a==0 || fread(pNew->a, sz, 1, in)<1 ){
      free(pNew->zFilename);
      free(pNew->a);
      pNew->a = 0;
      pNew->zFilename = 0;
      pNew->sz = -1;
      pNew = 0;
    }
  }
  if( in ) fclose(in);
  return pNew;
}

/* Methods for the VHandle object
*/
static int inmemClose(sqlite3_file *pFile){
  VHandle *p = (VHandle*)pFile;
  VFile *pVFile = p->pVFile;
  pVFile->nRef--;
  if( pVFile->nRef==0 && pVFile->zFilename==0 ){
    pVFile->sz = -1;
    free(pVFile->a);
    pVFile->a = 0;
  }
  return SQLITE_OK;
}
static int inmemRead(
  sqlite3_file *pFile,   /* Read from this open file */
  void *pData,           /* Store content in this buffer */
  int iAmt,              /* Bytes of content */
  sqlite3_int64 iOfst    /* Start reading here */
){
  VHandle *pHandle = (VHandle*)pFile;
  VFile *pVFile = pHandle->pVFile;
  if( iOfst<0 || iOfst>=pVFile->sz ){
    memset(pData, 0, iAmt);
    return SQLITE_IOERR_SHORT_READ;
  }
  if( iOfst+iAmt>pVFile->sz ){
    memset(pData, 0, iAmt);
    iAmt = (int)(pVFile->sz - iOfst);
    memcpy(pData, pVFile->a, iAmt);
    return SQLITE_IOERR_SHORT_READ;
  }
  memcpy(pData, pVFile->a + iOfst, iAmt);
  return SQLITE_OK;
}
static int inmemWrite(
  sqlite3_file *pFile,   /* Write to this file */
  const void *pData,     /* Content to write */
  int iAmt,              /* bytes to write */
  sqlite3_int64 iOfst    /* Start writing here */
){
  VHandle *pHandle = (VHandle*)pFile;
  VFile *pVFile = pHandle->pVFile;
  if( iOfst+iAmt > pVFile->sz ){
    unsigned char *aNew;
    if( iOfst+iAmt >= MX_FILE_SZ ){
      return SQLITE_FULL;
    }
    aNew = realloc(pVFile->a, (int)(iOfst+iAmt));
    if( aNew==0 ){
      return SQLITE_FULL;
    }
    pVFile->a = aNew;
    if( iOfst > pVFile->sz ){
      memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
    }
    pVFile->sz = (int)(iOfst + iAmt);
  }
  memcpy(pVFile->a + iOfst, pData, iAmt);
  return SQLITE_OK;
}
static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
  VHandle *pHandle = (VHandle*)pFile;
  VFile *pVFile = pHandle->pVFile;
  if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
  return SQLITE_OK;
}
static int inmemSync(sqlite3_file *pFile, int flags){
  return SQLITE_OK;
}
static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
  *pSize = ((VHandle*)pFile)->pVFile->sz;
  return SQLITE_OK;
}
static int inmemLock(sqlite3_file *pFile, int type){
  return SQLITE_OK;
}
static int inmemUnlock(sqlite3_file *pFile, int type){
  return SQLITE_OK;
}
static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
  *pOut = 0;
  return SQLITE_OK;
}
static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
  return SQLITE_NOTFOUND;
}
static int inmemSectorSize(sqlite3_file *pFile){
  return 512;
}
static int inmemDeviceCharacteristics(sqlite3_file *pFile){
  return
      SQLITE_IOCAP_SAFE_APPEND |
      SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
      SQLITE_IOCAP_POWERSAFE_OVERWRITE;
}


/* Method table for VHandle
*/
static sqlite3_io_methods VHandleMethods = {
  /* iVersion    */  1,
  /* xClose      */  inmemClose,
  /* xRead       */  inmemRead,
  /* xWrite      */  inmemWrite,
  /* xTruncate   */  inmemTruncate,
  /* xSync       */  inmemSync,
  /* xFileSize   */  inmemFileSize,
  /* xLock       */  inmemLock,
  /* xUnlock     */  inmemUnlock,
  /* xCheck...   */  inmemCheckReservedLock,
  /* xFileCtrl   */  inmemFileControl,
  /* xSectorSz   */  inmemSectorSize,
  /* xDevchar    */  inmemDeviceCharacteristics,
  /* xShmMap     */  0,
  /* xShmLock    */  0,
  /* xShmBarrier */  0,
  /* xShmUnmap   */  0,
  /* xFetch      */  0,
  /* xUnfetch    */  0
};

/*
** Open a new file in the inmem VFS.  All files are anonymous and are
** delete-on-close.
*/
static int inmemOpen(
  sqlite3_vfs *pVfs,
  const char *zFilename,
  sqlite3_file *pFile,
  int openFlags,
  int *pOutFlags
){
  VFile *pVFile = createVFile(zFilename, 0);
  VHandle *pHandle = (VHandle*)pFile;
  if( pVFile==0 ){
    return SQLITE_FULL;
  }
  pHandle->pVFile = pVFile;
  pVFile->nRef++;
  pFile->pMethods = &VHandleMethods;
  if( pOutFlags ) *pOutFlags = openFlags;
  return SQLITE_OK;
}

/*
** Delete a file by name
*/
static int inmemDelete(
  sqlite3_vfs *pVfs,
  const char *zFilename,
  int syncdir
){
  VFile *pVFile = findVFile(zFilename);
  if( pVFile==0 ) return SQLITE_OK;
  if( pVFile->nRef==0 ){
    free(pVFile->zFilename);
    pVFile->zFilename = 0;
    pVFile->sz = -1;
    free(pVFile->a);
    pVFile->a = 0;
    return SQLITE_OK;
  }
  return SQLITE_IOERR_DELETE;
}

/* Check for the existance of a file
*/
static int inmemAccess(
  sqlite3_vfs *pVfs,
  const char *zFilename,
  int flags,
  int *pResOut
){
  VFile *pVFile = findVFile(zFilename);
  *pResOut =  pVFile!=0;
  return SQLITE_OK;
}

/* Get the canonical pathname for a file
*/
static int inmemFullPathname(
  sqlite3_vfs *pVfs,
  const char *zFilename,
  int nOut,
  char *zOut
){
  sqlite3_snprintf(nOut, zOut, "%s", zFilename);
  return SQLITE_OK;
}

/*
** Register the VFS that reads from the g.aFile[] set of files.
*/
static void inmemVfsRegister(void){
  static sqlite3_vfs inmemVfs;
  sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
  inmemVfs.iVersion = 3;
  inmemVfs.szOsFile = sizeof(VHandle);
  inmemVfs.mxPathname = 200;
  inmemVfs.zName = "inmem";
  inmemVfs.xOpen = inmemOpen;
  inmemVfs.xDelete = inmemDelete;
  inmemVfs.xAccess = inmemAccess;
  inmemVfs.xFullPathname = inmemFullPathname;
  inmemVfs.xRandomness = pDefault->xRandomness;
  inmemVfs.xSleep = pDefault->xSleep;
  inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
  sqlite3_vfs_register(&inmemVfs, 0);
};

/*
** Timeout handler
*/
#ifdef __unix__
static void timeoutHandler(int NotUsed){
  (void)NotUsed;
  fatalError("timeout\n");
}
#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
}
/***************************************************************************
** String accumulator object
*/
typedef struct Str Str;
struct Str {
  char *z;                /* The string.  Memory from malloc() */
  sqlite3_uint64 n;       /* Bytes of input used */
  sqlite3_uint64 nAlloc;  /* Bytes allocated to z[] */
  int oomErr;             /* OOM error has been seen */
};

/* Initialize a Str object */
static void StrInit(Str *p){
  memset(p, 0, sizeof(*p));
}

/* Append text to the end of a Str object */
static void StrAppend(Str *p, const char *z){
  sqlite3_uint64 n = strlen(z);
  if( p->n + n >= p->nAlloc ){
    char *zNew;
    sqlite3_uint64 nNew;
    if( p->oomErr ) return;
    nNew = p->nAlloc*2 + 100 + n;
    zNew = sqlite3_realloc(p->z, nNew);
    if( zNew==0 ){
      sqlite3_free(p->z);
      memset(p, 0, sizeof(*p));
      p->oomErr = 1;
      return;
    }
    p->z = zNew;
    p->nAlloc = nNew;
  }
  memcpy(p->z + p->n, z, n);
  p->n += n;
  p->z[p->n] = 0;
}

/* Return the current string content */
static char *StrStr(Str *p){
 return p->z;
}

/* Free the string */
static void StrFree(Str *p){
  sqlite3_free(p->z);
  StrInit(p);
}

/*
** Return the value of a hexadecimal digit.  Return -1 if the input
** is not a hex digit.
*/
static int hexDigitValue(char c){
  if( c>='0' && c<='9' ) return c - '0';
  if( c>='a' && c<='f' ) return c - 'a' + 10;
  if( c>='A' && c<='F' ) return c - 'A' + 10;
  return -1;
}

/*
** Interpret zArg as an integer value, possibly with suffixes.
*/
static int integerValue(const char *zArg){
  sqlite3_int64 v = 0;
  static const struct { char *zSuffix; int iMult; } aMult[] = {
    { "KiB", 1024 },
    { "MiB", 1024*1024 },
    { "GiB", 1024*1024*1024 },
    { "KB",  1000 },
    { "MB",  1000000 },
    { "GB",  1000000000 },
    { "K",   1000 },
    { "M",   1000000 },
    { "G",   1000000000 },
  };
  int i;
  int isNeg = 0;
  if( zArg[0]=='-' ){
    isNeg = 1;
    zArg++;
  }else if( zArg[0]=='+' ){
    zArg++;
  }
  if( zArg[0]=='0' && zArg[1]=='x' ){
    int x;
    zArg += 2;
    while( (x = hexDigitValue(zArg[0]))>=0 ){
      v = (v<<4) + x;
      zArg++;
    }
  }else{
    while( ISDIGIT(zArg[0]) ){
      v = v*10 + zArg[0] - '0';
      zArg++;
    }
  }
  for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
      v *= aMult[i].iMult;
      break;
    }
  }
  if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
  return (int)(isNeg? -v : v);
}

/*
** This callback is invoked by sqlite3_exec() to return query results.
*/
static int execCallback(void *NotUsed, int argc, char **argv, char **colv){
  int i;
  static unsigned cnt = 0;
  printf("ROW #%u:\n", ++cnt);
  if( argv ){
    for(i=0; i<argc; i++){
      printf(" %s=", colv[i]);
      if( argv[i] ){
        printf("[%s]\n", argv[i]);
      }else{
        printf("NULL\n");
      }
    }
  }
  fflush(stdout);
  return 0;
}
static int execNoop(void *NotUsed, int argc, char **argv, char **colv){
  return 0;
}

/*
** This callback is invoked by sqlite3_log().
*/
static void sqlLog(void *pNotUsed, int iErrCode, const char *zMsg){
  printf("LOG: (%d) %s\n", iErrCode, zMsg);
  fflush(stdout);
}

#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



int main(int argc, char **argv){
  int i;                 /* Loop counter */
  int nDb;               /* Number of databases to fuzz */
  const char **azDb = 0; /* Names of the databases (limit: 20) */
  int verboseFlag = 0;   /* True for extra output */
  int traceFlag = 0;     /* True to trace results */
  int noLookaside = 0;   /* Disable lookaside if true */
  int vdbeLimitFlag = 0; /* Stop after 100,000 VDBE ops */
  int nHeap = 0;         /* True for fixed heap size */
  int iTimeout = 0;      /* Timeout delay in seconds */
  int rc;                /* Result code from SQLite3 API calls */
  sqlite3 *db;           /* The database connection */
  sqlite3_stmt *pStmt;   /* A single SQL statement */
  Str sql;               /* SQL to run */

  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]!='-' ){
      azDb = realloc(azDb, sizeof(azDb[0])*(nDb+1));
      if( azDb==0 ) fatalError("out of memory");
      azDb[nDb++] = z;
      continue;
    }
    z++;
    if( z[0]=='-' ) z++;
    if( strcmp(z, "help")==0 ){
      showHelp(argv[0]);
    }else if( strcmp(z, "limit-mem")==0 ){
      if( i==argc-1 ) fatalError("missing argument to %s", argv[i]);
      nHeap = integerValue(argv[++i]);
    }else if( strcmp(z, "no-lookaside")==0 ){
      noLookaside = 1;
    }else if( strcmp(z, "timeout")==0 ){
      if( i==argc-1 ) fatalError("missing argument to %s", argv[i]);
      iTimeout = integerValue(argv[++i]);
    }else if( strcmp(z, "trace")==0 ){
      traceFlag = 1;
    }else if( strcmp(z, "limit-vdbe")==0 ){
      vdbeLimitFlag = 1;
    }else if( strcmp(z, "v")==0 || strcmp(z, "verbose")==0 ){
      verboseFlag = 1;
    }else{
      fatalError("unknown command-line option: \"%s\"\n", argv[i]);
    }
  }
  if( nDb==0 ){
    showHelp(argv[0]);
  }
  if( verboseFlag ){
    sqlite3_config(SQLITE_CONFIG_LOG, sqlLog);
  }
  if( nHeap>0 ){
    void *pHeap = malloc( nHeap );
    if( pHeap==0 ) fatalError("cannot allocate %d-byte heap\n", nHeap);
    rc = sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nHeap, 32);
    if( rc ) fatalError("heap configuration failed: %d\n", rc);
  }
  if( noLookaside ){
    sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
  }
  inmemVfsRegister();
  formatVfs();
  StrInit(&sql);
#ifdef __unix__
  signal(SIGALRM, timeoutHandler);
#endif
  for(i=0; i<nDb; i++){
    StrFree(&sql);

    if( verboseFlag && nDb>1 ){
      printf("DATABASE-FILE: %s\n", azDb[i]);
      fflush(stdout);
    }
    if( iTimeout ) setAlarm(iTimeout);
    createVFile("test.db", azDb[i]);
    rc = sqlite3_open_v2("test.db", &db, SQLITE_OPEN_READWRITE, "inmem");
    if( rc ){
      printf("cannot open test.db for \"%s\"\n", azDb[i]);
      reformatVfs();
      continue;
    }
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
    if( vdbeLimitFlag ){
      sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
    }
#endif
    rc = sqlite3_prepare_v2(db, "SELECT sql FROM autoexec", -1, &pStmt, 0);
    if( rc==SQLITE_OK ){
      while( SQLITE_ROW==sqlite3_step(pStmt) ){
        StrAppend(&sql, (const char*)sqlite3_column_text(pStmt, 0));
        StrAppend(&sql, "\n");
      }
    }
    sqlite3_finalize(pStmt);
    StrAppend(&sql, "PRAGMA integrity_check;\n");
    if( traceFlag ){
      char *zErrMsg = 0;
      rc = sqlite3_exec(db, StrStr(&sql), execCallback, 0, &zErrMsg);
      if( zErrMsg ){
        printf("ERRMSG: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
      }
    }else {
      rc = sqlite3_exec(db, StrStr(&sql), execNoop, 0, 0);
    }
    sqlite3_close(db);
    reformatVfs();
    StrFree(&sql);
    if( sqlite3_memory_used()>0 ){
      free(azDb);
      reformatVfs();
      fatalError("memory leak of %lld bytes", sqlite3_memory_used());
    }
  }
  StrFree(&sql);
  reformatVfs();
  return 0;
}
Changes to tool/fuzzershell.c.
221
222
223
224
225
226
227


















































228
229
230
231
232
233
234
  printf("TRACE: %s\n", zMsg);
  fflush(stdout);
}
static void traceNoop(void *NotUsed, const char *zMsg){
  return;
}
#endif



















































/***************************************************************************
** eval() implementation copied from ../ext/misc/eval.c
*/
/*
** Structure used to accumulate the output
*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
  printf("TRACE: %s\n", zMsg);
  fflush(stdout);
}
static void traceNoop(void *NotUsed, const char *zMsg){
  return;
}
#endif

/***************************************************************************
** String accumulator object
*/
typedef struct Str Str;
struct Str {
  char *z;                /* The string.  Memory from malloc() */
  sqlite3_uint64 n;       /* Bytes of input used */
  sqlite3_uint64 nAlloc;  /* Bytes allocated to z[] */
  int oomErr;             /* OOM error has been seen */
};

/* Initialize a Str object */
static void StrInit(Str *p){
  memset(p, 0, sizeof(*p));
}

/* Append text to the end of a Str object */
static void StrAppend(Str *p, const char *z){
  sqlite3_uint64 n = strlen(z);
  if( p->n + n >= p->nAlloc ){
    char *zNew;
    sqlite3_uint64 nNew;
    if( p->oomErr ) return;
    nNew = p->nAlloc*2 + 100 + n;
    zNew = sqlite3_realloc(p->z, nNew);
    if( zNew==0 ){
      sqlite3_free(p->z);
      memset(p, 0, sizeof(*p));
      p->oomErr = 1;
      return;
    }
    p->z = zNew;
    p->nAlloc = nNew;
  }
  memcpy(p->z + p->n, z, n);
  p->n += n;
  p->z[p->n] = 0;
}

/* Return the current string content */
static char *StrStr(Str *p){
 return p->z;
}

/* Free the string */
static void StrFree(Str *p){
  sqlite3_free(p->z);
  StrInit(p);
}

/***************************************************************************
** eval() implementation copied from ../ext/misc/eval.c
*/
/*
** Structure used to accumulate the output
*/
1024
1025
1026
1027
1028
1029
1030


1031
1032
1033
1034
1035
1036
1037
          printf("Once.%d\n", oomCnt);
          fflush(stdout);
        }
      }else{
        oomCnt = 0;
      }
      do{


        if( zDbName ){
          rc = sqlite3_open_v2(zDbName, &db, SQLITE_OPEN_READWRITE, 0);
          if( rc!=SQLITE_OK ){
            abendError("Cannot open database file %s", zDbName);
          }
        }else{
          rc = sqlite3_open_v2(







>
>







1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
          printf("Once.%d\n", oomCnt);
          fflush(stdout);
        }
      }else{
        oomCnt = 0;
      }
      do{
        Str sql;
        StrInit(&sql);
        if( zDbName ){
          rc = sqlite3_open_v2(zDbName, &db, SQLITE_OPEN_READWRITE, 0);
          if( rc!=SQLITE_OK ){
            abendError("Cannot open database file %s", zDbName);
          }
        }else{
          rc = sqlite3_open_v2(
1053
1054
1055
1056
1057
1058
1059



















1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

1073
1074
1075
1076
1077
1078
1079
        sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
        sqlite3_create_module(db, "generate_series", &seriesModule, 0);
        sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
        if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
        if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
        if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
        iStart = timeOfDay();



















        g.bOomEnable = 1;
        if( verboseFlag ){
          zErrMsg = 0;
          rc = sqlite3_exec(db, zSql, execCallback, 0, &zErrMsg);
          if( zErrMsg ){
            sqlite3_snprintf(sizeof(zErrBuf),zErrBuf,"%z", zErrMsg);
            zErrMsg = 0;
          }
        }else {
          rc = sqlite3_exec(db, zSql, execNoop, 0, 0);
        }
        g.bOomEnable = 0;
        iEnd = timeOfDay();

        rc = sqlite3_close(db);
        if( rc ){
          abendError("sqlite3_close() failed with rc=%d", rc);
        }
        if( !zDataOut && sqlite3_memory_used()>0 ){
          abendError("memory in use after close: %lld bytes",sqlite3_memory_used());
        }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>













>







1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
        sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
        sqlite3_create_module(db, "generate_series", &seriesModule, 0);
        sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
        if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
        if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
        if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
        iStart = timeOfDay();

        /* If using an input database file and that database contains a table
        ** named "autoexec" with a column "sql", then replace the input SQL
        ** with the concatenated text of the autoexec table.  In this way,
        ** if the database file is the input being fuzzed, the SQL text is
        ** fuzzed at the same time. */
        if( sqlite3_table_column_metadata(db,0,"autoexec","sql",0,0,0,0,0)==0 ){
          sqlite3_stmt *pStmt;
          rc = sqlite3_prepare_v2(db, "SELECT sql FROM autoexec", -1, &pStmt, 0);
          if( rc==SQLITE_OK ){
            while( sqlite3_step(pStmt)==SQLITE_ROW ){
              StrAppend(&sql, (const char*)sqlite3_column_text(pStmt, 0));
              StrAppend(&sql, "\n");
            }
          }
          sqlite3_finalize(pStmt);
          zSql = StrStr(&sql);
        }

        g.bOomEnable = 1;
        if( verboseFlag ){
          zErrMsg = 0;
          rc = sqlite3_exec(db, zSql, execCallback, 0, &zErrMsg);
          if( zErrMsg ){
            sqlite3_snprintf(sizeof(zErrBuf),zErrBuf,"%z", zErrMsg);
            zErrMsg = 0;
          }
        }else {
          rc = sqlite3_exec(db, zSql, execNoop, 0, 0);
        }
        g.bOomEnable = 0;
        iEnd = timeOfDay();
        StrFree(&sql);
        rc = sqlite3_close(db);
        if( rc ){
          abendError("sqlite3_close() failed with rc=%d", rc);
        }
        if( !zDataOut && sqlite3_memory_used()>0 ){
          abendError("memory in use after close: %lld bytes",sqlite3_memory_used());
        }