Debian Codegraph @

tests/fuzzing/build-corpus.py

raw
1 #!/bin/python3
2
3 #
4 # liblouis Braille Translation and Back-Translation Library
5 #
6 # Copyright (C) 2022 Anna Stan, Nicolas Morel, Kalilou Mamadou Dramé
7 #
8 # This file is part of liblouis.
9 #
10 # liblouis is free software: you can redistribute it and/or modify it
11 # under the terms of the GNU Lesser General Public License as published
12 # by the Free Software Foundation, either version 2.1 of the License, or
13 # (at your option) any later version.
14 #
15 # liblouis is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
19 #
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with liblouis. If not, see <http://www.gnu.org/licenses/>.
22 #
23
24 import sys
25 import argparse
26 import os
27 from os import O_WRONLY, O_TRUNC, O_CREAT, SEEK_END, SEEK_CUR, SEEK_SET
28
29
30
31 '''from pwn import *
32 context.quiet'''
33
34 DEFAULT_BINARY_NAME = 'fuzz_voice'
35 DEFAULT_CORPUS_NAME = 'corpus.txt'
36
37 def fd_get_size(fd):
38 cur_off = os.lseek(fd, 0, SEEK_CUR)
39 size = os.lseek(fd, 0, SEEK_END)
40 os.lseek(fd, cur_off, SEEK_SET)
41 return size
42
43
44 '''
45 Check if a bytestring (should be a 2 letter bytestring) is an unicode character
46
47 (
48 As it doesn't check if the string passed (s) or a substring is a valid ascii
49 or utf value that we just added to corpus, it can add more characters than it
50 was originally contained in files.
51 However, it can be usefull to add more chars to corpus file so we dont fix this for now.
52 )
53
54 Returns the int value of the char and True if it is an unicode char, otherwise None and False
55 '''
56 def isUnicode(s):
57 c=None
58 try:
59 c=ord(s.decode('utf-8'))
60 if (c > 0 and c < 0xffff) or (c > 0xe000 and c < 0x10ffff):
61 return c, True
62 except:
63 pass
64 return None, False
65
66
67 def isAscii(c):
68 if c > 0 and c <= 127:
69 return True
70 return False
71
72
73 '''
74 Corpus class
75
76 Allows to create corpus file from xx_list
77 '''
78 class Corpus:
79
80 def __init__(self, files, output=DEFAULT_CORPUS_NAME, stdout=False):
81 self.files = files
82 self.output = output
83 if stdout is True:
84 self.output = None
85 self.dict = ""
86 self.dict_uni = ""
87 self.ascii_lut = [False for i in range(0, 128)]
88 self.unicode_lut = [False for i in range(0, 1112065)]
89
90 '''
91 build a dictonnary with all chars appearing in xx_list
92 '''
93 def retrieveDict(self):
94 for filename in self.files:
95 with open(filename, mode='rb') as fp:
96 for line in fp.readlines():
97 for i in range(0, len(line)):
98
99 if i != 0:
100 s = line[i-1: i+1]
101 c, ret = isUnicode(s)
102 if ret == True and self.unicode_lut[c] is False:
103 self.unicode_lut[c] = True
104 self.dict_uni += chr(c)
105 if i >= 2:
106 s = line[i-2: i+1]
107 c, ret = isUnicode(s)
108 if ret == True and self.unicode_lut[c] is False:
109 self.unicode_lut[c] = True
110 self.dict_uni += chr(c)
111 if i >= 3:
112 s = line[i-3: i+1]
113 c, ret = isUnicode(s)
114 if ret == True and self.unicode_lut[c] is False:
115 self.unicode_lut[c] = True
116 self.dict_uni += chr(c)
117
118 c = line[i]
119 if isAscii(c) and self.ascii_lut[c] is False:
120 self.ascii_lut[c] = True
121 self.dict += chr(c)
122
123
124
125 '''
126 Write dictionnary to output file
127 '''
128 def writeDictToFile(self):
129 if self.output is None:
130 print(self.dict)
131 print(self.dict_uni)
132 else:
133 fd = os.open(self.output, O_WRONLY|O_CREAT|O_TRUNC, 0o644)
134 os.write(fd, self.dict.encode())
135 os.write(fd, self.dict_uni.encode('utf-8'))
136 os.close(fd)
137
138 def main(argc, argv):
139 if argc < 3:
140 print('Summary: Build corpus from files', file=sys.stderr)
141 print(f'Usage: {argv[0]} -f <file(s)> (-o <output-filename>|--stdout)', file=sys.stderr)
142 exit(1)
143
144 ap = argparse.ArgumentParser()
145
146 # Add the arguments to the parser
147 ap.add_argument("-f", "--files", required=True,
148 help="the filenames list to extract char from and build corpus")
149 ap.add_argument("-o", "--output", required=False,
150 help="the output filename for the corpus file")
151 ap.add_argument("-s", "--stdout", required=False, action='store_true',
152 help="only display corpus to stdout")
153 args = vars(ap.parse_args())
154
155 files = []
156 for file in args['files'].split(','):
157 if file == '':
158 print('Error in --files format', file=sys.stderr)
159 print('Format is : --files=file0,file1,file2', file=sys.stderr)
160 exit(1)
161 files.append(file)
162
163 if args['stdout'] is False and args['output'] is None:
164 print('Error arguments: you need to specify an output option (file: --output|-o, stdout: --stdout|-s)', file=sys.stderr)
165 exit(1)
166
167 c=None
168 if args['stdout'] is True:
169 c = Corpus(files, stdout=True)
170 else:
171 c = Corpus(files, args['output'])
172 c.retrieveDict()
173 c.writeDictToFile()
174
175
176 if __name__ == "__main__":
177 main(len(sys.argv), sys.argv)
178