Add fuzzer work in progress
[yaffs2.git] / direct / tests / fuzzer.c
1 /*
2  * Fuzzer to fuzz a file
3  */
4
5 #include <string.h>
6 #include <unistd.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <pthread.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <fcntl.h>
13                      
14 int main(int argc, char *argv[])
15 {
16         int prob = 10000;
17         int h;
18         int flen = 0;
19         int changesPerBuffer = 0;
20         int b;
21         char c;
22         unsigned char buffer[1000000];
23         int bufsize;
24         int x;
25         int i;
26         int nbuffers;
27
28         while((c = getopt(argc,argv,"p:")) != -1){
29                 switch(c){
30                         case 'p':
31                                 prob = atoi(optarg);
32                                 break;
33                 }
34         }
35         if(prob < 100){
36                 printf("-p value less than 100 is invalid\n");
37                 return 1;
38         }
39         
40         if(optind >= argc){
41                 printf(" Needs a file name to fuzz\n");
42                 return 1;
43         }
44         
45         h = open(argv[optind], O_RDWR);
46         flen = lseek(h,0,SEEK_END);
47         lseek(h,0,SEEK_SET);
48         if(flen < 1){
49                 printf(" File is too short\n");
50                 return 1;
51         }
52         
53         nbuffers = (flen + sizeof(buffer) - 1) / sizeof(buffer);
54
55         changesPerBuffer = 1+ (sizeof(buffer) * 8) / prob;
56
57         printf("Fuzzing file %s. Size %d, probablity 1/%d, changing %d bits in each of %d buffers\n",
58                 argv[optind],flen,prob,changesPerBuffer,nbuffers);
59
60         srand(time(0));
61
62         for(b = 0; b < nbuffers; b++){
63                 printf("buffer %d\n",b);
64                 lseek(h,b * sizeof(buffer),SEEK_SET);
65                 bufsize = read(h,buffer,sizeof(buffer));
66                 for(i = 0; i < changesPerBuffer; i++){
67                         x = rand() % (sizeof(buffer) * 8);
68                         buffer[x >> 3] ^= (1 << (x & 7));
69                 }
70                 lseek(h,b * sizeof(buffer),SEEK_SET);
71                 write(h,buffer,bufsize);
72         }
73         close(h);
74         return 0;
75 }