Merge branch 'master' of ssh://www.aleph1.co.uk/home/aleph1/git/yaffs2
[yaffs2.git] / direct / tests / fuzzer.c
1 /*
2  * YAFFS: Yet another FFS. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2011 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 /*
15  * Fuzzer to fuzz a file
16  */
17
18 #include <string.h>
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <pthread.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <fcntl.h>
26                      
27 int main(int argc, char *argv[])
28 {
29         int prob = 10000;
30         int h;
31         int flen = 0;
32         int changesPerBuffer = 0;
33         int b;
34         char c;
35         unsigned char buffer[1000000];
36         int bufsize;
37         int x;
38         int i;
39         int nbuffers;
40
41         while((c = getopt(argc,argv,"p:")) != -1){
42                 switch(c){
43                         case 'p':
44                                 prob = atoi(optarg);
45                                 break;
46                 }
47         }
48         if(prob < 100){
49                 printf("-p value less than 100 is invalid\n");
50                 return 1;
51         }
52         
53         if(optind >= argc){
54                 printf(" Needs a file name to fuzz\n");
55                 return 1;
56         }
57         
58         h = open(argv[optind], O_RDWR);
59         flen = lseek(h,0,SEEK_END);
60         lseek(h,0,SEEK_SET);
61         if(flen < 1){
62                 printf(" File is too short\n");
63                 return 1;
64         }
65         
66         nbuffers = (flen + sizeof(buffer) - 1) / sizeof(buffer);
67
68         changesPerBuffer = 1+ (sizeof(buffer) * 8) / prob;
69
70         printf("Fuzzing file %s. Size %d, probablity 1/%d, changing %d bits in each of %d buffers\n",
71                 argv[optind],flen,prob,changesPerBuffer,nbuffers);
72
73         srand(time(0));
74
75         for(b = 0; b < nbuffers; b++){
76                 /* printf("buffer %d\n",b); */
77                 lseek(h,b * sizeof(buffer),SEEK_SET);
78                 bufsize = read(h,buffer,sizeof(buffer));
79                 for(i = 0; i < changesPerBuffer; i++){
80                         x = rand() % (sizeof(buffer) * 8);
81                         buffer[x >> 3] ^= (1 << (x & 7));
82                 }
83                 lseek(h,b * sizeof(buffer),SEEK_SET);
84                 write(h,buffer,bufsize);
85         }
86         close(h);
87         return 0;
88 }