fandango-fuzzer 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. evaluation/__init__.py +0 -0
  2. evaluation/experiments/__init__.py +0 -0
  3. evaluation/experiments/faker/__init__.py +0 -0
  4. evaluation/experiments/faker/faker_experiment.py +15 -0
  5. evaluation/experiments/hash/__init__.py +0 -0
  6. evaluation/experiments/hash/hash_experiment.py +18 -0
  7. evaluation/experiments/pixels/__init__.py +0 -0
  8. evaluation/experiments/pixels/pixels_experiment.py +15 -0
  9. evaluation/experiments/transactions/__init__.py +0 -0
  10. evaluation/experiments/transactions/transactions.py +18 -0
  11. evaluation/experiments/voltage/__init__.py +0 -0
  12. evaluation/experiments/voltage/voltage_experiment.py +18 -0
  13. evaluation/experiments/whitebox/__init__.py +0 -0
  14. evaluation/experiments/whitebox/whitebox.py +60 -0
  15. evaluation/vs_isla/__init__.py +0 -0
  16. evaluation/vs_isla/csv_evaluation/__init__.py +0 -0
  17. evaluation/vs_isla/csv_evaluation/csv_evaluation.py +63 -0
  18. evaluation/vs_isla/rest_evaluation/__init__.py +0 -0
  19. evaluation/vs_isla/rest_evaluation/rest_evaluation.py +66 -0
  20. evaluation/vs_isla/run_evaluation.py +43 -0
  21. evaluation/vs_isla/scriptsizec_evaluation/__init__.py +0 -0
  22. evaluation/vs_isla/scriptsizec_evaluation/scriptsizec_evaluation.py +123 -0
  23. evaluation/vs_isla/tar_evaluation/__init__.py +0 -0
  24. evaluation/vs_isla/tar_evaluation/tar_evaluation.py +61 -0
  25. evaluation/vs_isla/xml_evaluation/__init__.py +0 -0
  26. evaluation/vs_isla/xml_evaluation/xml_evaluation.py +52 -0
  27. fandango/__init__.py +0 -0
  28. fandango/cli/__init__.py +997 -0
  29. fandango/cli/progress.py +66 -0
  30. fandango/constraints/__init__.py +0 -0
  31. fandango/constraints/base.py +621 -0
  32. fandango/constraints/fitness.py +165 -0
  33. fandango/constraints/predicates.py +89 -0
  34. fandango/evolution/__init__.py +0 -0
  35. fandango/evolution/algorithm.py +427 -0
  36. fandango/framework.py +84 -0
  37. fandango/language/__init__.py +0 -0
  38. fandango/language/convert.py +1711 -0
  39. fandango/language/grammar.py +1092 -0
  40. fandango/language/parse.py +320 -0
  41. fandango/language/parser/FandangoLexer.py +11777 -0
  42. fandango/language/parser/FandangoLexerBase.py +118 -0
  43. fandango/language/parser/FandangoParser.py +43012 -0
  44. fandango/language/parser/FandangoParserListener.py +1899 -0
  45. fandango/language/parser/FandangoParserVisitor.py +958 -0
  46. fandango/language/parser/__init__.py +0 -0
  47. fandango/language/search.py +356 -0
  48. fandango/language/symbol.py +103 -0
  49. fandango/language/tree.py +269 -0
  50. fandango/logger.py +94 -0
  51. fandango_fuzzer-0.0.2.dist-info/LICENSE.md +274 -0
  52. fandango_fuzzer-0.0.2.dist-info/METADATA +135 -0
  53. fandango_fuzzer-0.0.2.dist-info/RECORD +56 -0
  54. fandango_fuzzer-0.0.2.dist-info/WHEEL +5 -0
  55. fandango_fuzzer-0.0.2.dist-info/entry_points.txt +2 -0
  56. fandango_fuzzer-0.0.2.dist-info/top_level.txt +2 -0
evaluation/__init__.py ADDED
File without changes
File without changes
File without changes
@@ -0,0 +1,15 @@
1
+ from fandango.evolution.algorithm import Fandango
2
+ from fandango.language.parse import parse_file
3
+
4
+
5
+ def evaluate_faker():
6
+ grammar, constraints = parse_file("faker.fan")
7
+
8
+ fandango = Fandango(grammar, constraints)
9
+ fandango.evolve()
10
+
11
+ print(fandango.solution)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ evaluate_faker()
File without changes
@@ -0,0 +1,18 @@
1
+ from fandango.evolution.algorithm import Fandango
2
+ from fandango.language.parse import parse_file
3
+
4
+
5
+ def evaluate_hash():
6
+ grammar, constraints = parse_file("hash.fan")
7
+
8
+ print(grammar)
9
+ print(constraints)
10
+
11
+ fandango = Fandango(grammar, constraints)
12
+ fandango.evolve()
13
+
14
+ print(fandango.solution)
15
+
16
+
17
+ if __name__ == "__main__":
18
+ evaluate_hash()
File without changes
@@ -0,0 +1,15 @@
1
+ from fandango.evolution.algorithm import Fandango
2
+ from fandango.language.parse import parse_file
3
+
4
+
5
+ def evaluate_pixels():
6
+ grammar, constraints = parse_file("pixels.fan")
7
+
8
+ fandango = Fandango(grammar, constraints)
9
+ fandango.evolve()
10
+
11
+ print(fandango.solution)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ evaluate_pixels()
File without changes
@@ -0,0 +1,18 @@
1
+ from fandango.evolution.algorithm import Fandango
2
+ from fandango.language.parse import parse_file
3
+
4
+ import hashlib
5
+
6
+
7
+ def main():
8
+ # Load the fandango file
9
+ grammar, constraints = parse_file("transactions.fan")
10
+
11
+ fandango = Fandango(grammar, constraints)
12
+ fandango.evolve()
13
+
14
+ print(fandango.solution)
15
+
16
+
17
+ if __name__ == "__main__":
18
+ main()
File without changes
@@ -0,0 +1,18 @@
1
+ from fandango.evolution.algorithm import Fandango
2
+ from fandango.language.parse import parse_file
3
+
4
+
5
+ def evaluate_voltage():
6
+ grammar, constraints = parse_file("voltage.fan")
7
+
8
+ print(grammar)
9
+ print(constraints)
10
+
11
+ fandango = Fandango(grammar, constraints)
12
+ fandango.evolve()
13
+
14
+ print(fandango.solution)
15
+
16
+
17
+ if __name__ == "__main__":
18
+ evaluate_voltage()
File without changes
@@ -0,0 +1,60 @@
1
+ import warnings
2
+
3
+ from fandango.evolution.algorithm import Fandango
4
+ from fandango.language.parse import parse_file
5
+
6
+ warnings.filterwarnings("ignore")
7
+
8
+
9
+ def tree_to_binary(tree):
10
+ """
11
+ Convert a tree to a binary representation
12
+ :param tree: The tree to convert
13
+ :return: The binary representation of the tree
14
+
15
+ Example:
16
+ tree = '<x17>T</x17>'
17
+ tree_to_binary(tree) -> '001111000111100000110001001101110011111001010100001111000010111101111000001100010011011100111110'
18
+ """
19
+ return "".join(format(byte, "08b") for byte in str(tree).encode("utf-8"))
20
+
21
+
22
+ def binary_to_string(binary):
23
+ """
24
+ Convert a binary representation to a string
25
+ :param binary: The binary representation to convert
26
+ :return: The string representation of the binary
27
+
28
+ Example:
29
+ binary = '001111000111100000110001001101110011111001010100001111000010111101111000001100010011011100111110'
30
+ binary_to_string(binary) -> '<x17>T</x17>'
31
+ """
32
+ return "".join(chr(int(binary[i : i + 8], 2)) for i in range(0, len(binary), 8))
33
+
34
+
35
+ if __name__ == "__main__":
36
+ xml_grammar, xml_constraints = parse_file(
37
+ "xml.fan"
38
+ ) # Load the XML grammar and constraints
39
+ xml_files = Fandango(xml_grammar, xml_constraints).evolve() # Generate XML files
40
+ xml_binaries = [
41
+ tree_to_binary(xml) for xml in xml_files
42
+ ] # Convert XML files to binary
43
+
44
+ bytes_grammar, bytes_constraints = parse_file(
45
+ "bytes.fan"
46
+ ) # Load the bytes grammar and constraints
47
+ xml_binary_trees = [
48
+ bytes_grammar.parse(xml_binary) for xml_binary in xml_binaries
49
+ ] # Parse the binary repr into derivation trees
50
+
51
+ solutions = Fandango(
52
+ bytes_grammar,
53
+ bytes_constraints,
54
+ initial_population=xml_binary_trees,
55
+ ).evolve() # Generate bytes files
56
+
57
+ for solution in solutions:
58
+ print(
59
+ binary_to_string(str(solution))
60
+ ) # Convert the binary files to strings and print them
File without changes
File without changes
@@ -0,0 +1,63 @@
1
+ import csv
2
+ import time
3
+ from io import StringIO
4
+ from typing import Tuple
5
+
6
+ from fandango.evolution.algorithm import Fandango, LoggerLevel
7
+ from fandango.language.parse import parse_file
8
+ from fandango.logger import LOGGER
9
+
10
+
11
+ def is_syntactically_valid_csv(csv_string):
12
+ try:
13
+ # Create a file-like object from the string
14
+ csv_file = StringIO(csv_string)
15
+
16
+ # Create a CSV reader to parse the string
17
+ reader = csv.reader(csv_file)
18
+
19
+ # Iterate through the reader to trigger any parsing errors
20
+ for row in reader:
21
+ pass
22
+
23
+ # If no errors, it's a valid CSV syntactically
24
+ return True
25
+ except csv.Error as e:
26
+ # If there's a CSV parsing error, it's not valid
27
+ return False
28
+
29
+
30
+ def evaluate_csv(
31
+ seconds=60,
32
+ ) -> Tuple[str, int, int, float, Tuple[float, int, int], float, float]:
33
+ grammar, constraints = parse_file("csv_evaluation/csv.fan")
34
+ solutions = []
35
+
36
+ time_in_an_hour = time.time() + seconds
37
+
38
+ while time.time() < time_in_an_hour:
39
+ fandango = Fandango(
40
+ grammar, constraints, desired_solutions=100, logger_level=LoggerLevel.ERROR
41
+ )
42
+ fandango.evolve()
43
+ solutions.extend(fandango.solution)
44
+
45
+ coverage = grammar.compute_grammar_coverage(solutions, 4)
46
+
47
+ valid = []
48
+ for solution in solutions:
49
+ if is_syntactically_valid_csv(str(solution)):
50
+ valid.append(solution)
51
+
52
+ set_mean_length = sum(len(str(x)) for x in valid) / len(valid)
53
+ set_medium_length = sorted(len(str(x)) for x in valid)[len(valid) // 2]
54
+ valid_percentage = len(valid) / len(solutions) * 100
55
+ return (
56
+ "CSV",
57
+ len(solutions),
58
+ len(valid),
59
+ valid_percentage,
60
+ coverage,
61
+ set_mean_length,
62
+ set_medium_length,
63
+ )
File without changes
@@ -0,0 +1,66 @@
1
+ import time
2
+ from io import StringIO
3
+ from typing import Tuple
4
+
5
+ from docutils.core import publish_doctree
6
+
7
+ from fandango.evolution.algorithm import Fandango, LoggerLevel
8
+ from fandango.language.parse import parse_file
9
+
10
+
11
+ def is_syntactically_valid_rest(rst_string):
12
+ # StringIO to capture output messages (warnings, errors, etc.)
13
+ error_stream = StringIO()
14
+
15
+ try:
16
+ # Parse the reST string into a document tree, capturing system messages
17
+ doctree = publish_doctree(
18
+ rst_string, settings_overrides={"warning_stream": error_stream}
19
+ )
20
+
21
+ # Check if any errors or warnings were captured in the error stream
22
+ errors_warnings = error_stream.getvalue().strip()
23
+
24
+ if errors_warnings:
25
+ return False
26
+
27
+ return True
28
+
29
+ except:
30
+ return False
31
+
32
+
33
+ def evaluate_rest(
34
+ seconds=60,
35
+ ) -> Tuple[str, int, int, float, Tuple[float, int, int], float, float]:
36
+ grammar, constraints = parse_file("rest_evaluation/rest.fan")
37
+ solutions = []
38
+
39
+ time_in_an_hour = time.time() + seconds
40
+
41
+ while time.time() < time_in_an_hour:
42
+ fandango = Fandango(
43
+ grammar, constraints, desired_solutions=100, logger_level=LoggerLevel.ERROR
44
+ )
45
+ fandango.evolve()
46
+ solutions.extend(fandango.solution)
47
+
48
+ coverage = grammar.compute_grammar_coverage(solutions, 4)
49
+
50
+ valid = []
51
+ for solution in solutions:
52
+ if is_syntactically_valid_rest(str(solution)):
53
+ valid.append(solution)
54
+
55
+ set_mean_length = sum(len(str(x)) for x in valid) / len(valid)
56
+ set_medium_length = sorted(len(str(x)) for x in valid)[len(valid) // 2]
57
+ valid_percentage = len(valid) / len(solutions) * 100
58
+ return (
59
+ "REST",
60
+ len(solutions),
61
+ len(valid),
62
+ valid_percentage,
63
+ coverage,
64
+ set_mean_length,
65
+ set_medium_length,
66
+ )
@@ -0,0 +1,43 @@
1
+ import random
2
+ from typing import Tuple
3
+
4
+ from evaluation.vs_isla.csv_evaluation.csv_evaluation import evaluate_csv
5
+ from evaluation.vs_isla.rest_evaluation.rest_evaluation import evaluate_rest
6
+ from evaluation.vs_isla.scriptsizec_evaluation.scriptsizec_evaluation import (
7
+ evaluate_scriptsizec,
8
+ )
9
+ from evaluation.vs_isla.tar_evaluation.tar_evaluation import evaluate_tar
10
+ from evaluation.vs_isla.xml_evaluation.xml_evaluation import evaluate_xml
11
+
12
+
13
+ # Return the evaluation results as a tuple of values (subject, total, valid, percentage, diversity, mean_length, median)
14
+ def better_print_results(
15
+ results: Tuple[str, int, int, float, Tuple[float, int, int], float, float]
16
+ ):
17
+ print("================================")
18
+ print(f"{results[0]} Evaluation Results")
19
+ print("================================")
20
+ print(f"Total inputs: {results[1]}")
21
+ print(f"Valid {results[0]} solutions: {results[2]} ({results[3]:.2f}%)")
22
+ print(
23
+ f"Grammar coverage (0 to 1): {results[4][0]:.2f} ({results[4][1]} / {results[4][2]})"
24
+ )
25
+ print(f"Mean length: {results[5]:.2f}")
26
+ print(f"Median length: {results[6]:.2f}")
27
+ print("")
28
+ print("")
29
+
30
+
31
+ def run_evaluation(seconds: int = 3600, random_seed: int = 1):
32
+ # Set the random seed
33
+ random.seed(random_seed)
34
+
35
+ better_print_results(evaluate_csv(seconds))
36
+ better_print_results(evaluate_rest(seconds))
37
+ better_print_results(evaluate_scriptsizec(seconds))
38
+ better_print_results(evaluate_tar(seconds))
39
+ better_print_results(evaluate_xml(seconds))
40
+
41
+
42
+ if __name__ == "__main__":
43
+ run_evaluation()
File without changes
@@ -0,0 +1,123 @@
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import tempfile
5
+ import time
6
+ from typing import Tuple
7
+
8
+ from tccbox import tcc_bin_path
9
+
10
+ from fandango.evolution.algorithm import Fandango, LoggerLevel
11
+ from fandango.language.parse import parse_file
12
+
13
+
14
+ def declare_variables(c_code):
15
+ import re
16
+ import random
17
+
18
+ # Regular expressions to find variable usage and check for declarations
19
+ var_usage_pattern = r"\b([a-zA-Z])\b" # Matches single-letter variables
20
+ declaration_pattern = (
21
+ r"\bint\s+([a-zA-Z])\b" # Matches declared single-letter variables
22
+ )
23
+
24
+ # Find all single-letter variable uses in the code
25
+ var_usage = set(re.findall(var_usage_pattern, c_code))
26
+
27
+ # Find all declared single-letter variables
28
+ declared_vars = set(re.findall(declaration_pattern, c_code))
29
+
30
+ # Identify undeclared single-letter variables
31
+ undeclared_vars = (
32
+ var_usage - declared_vars - {"while", "if", "for", "return", "main"}
33
+ )
34
+
35
+ # Generate declarations for undeclared variables
36
+ declarations = ""
37
+ for var in undeclared_vars:
38
+ value = random.randint(1, 100000) # Random integer placeholder value
39
+ declarations += f" int {var} = {value};\n"
40
+
41
+ # Insert the declarations at the start of the main function
42
+ modified_code = re.sub(
43
+ r"(\bint main\(\) {)", r"\1\n" + declarations, c_code, count=1
44
+ )
45
+
46
+ return modified_code
47
+
48
+
49
+ def is_valid_tinyc_code(c_code: str) -> bool:
50
+ """
51
+ This function takes a string containing Tiny C code and checks if it is syntactically valid.
52
+ Returns True if valid, False otherwise.
53
+ """
54
+ # Create a temporary directory to store the C code and any generated files
55
+ temp_dir = tempfile.mkdtemp()
56
+ temp_file_path = os.path.join(temp_dir, "temp_code.c")
57
+
58
+ # Write the C code to a file in the temporary directory
59
+ with open(temp_file_path, "w") as temp_file:
60
+ temp_file.write(c_code)
61
+
62
+ try:
63
+ # Use tcc to try and compile the file without generating an output (-c option)
64
+ # This is equivalent to a syntax check
65
+ result = subprocess.run(
66
+ [tcc_bin_path(), "-c", temp_file_path],
67
+ stdout=subprocess.PIPE,
68
+ stderr=subprocess.PIPE,
69
+ cwd=temp_dir, # Set the working directory to the temp directory
70
+ )
71
+
72
+ # If return code is 0, the syntax is valid
73
+ if result.returncode == 0:
74
+ return True
75
+ if "include file" in result.stderr.decode():
76
+ return True
77
+ else:
78
+ return False
79
+ finally:
80
+ # Clean up the temporary directory and its contents
81
+ shutil.rmtree(temp_dir)
82
+
83
+
84
+ def evaluate_scriptsizec(
85
+ seconds=60,
86
+ ) -> Tuple[str, int, int, float, Tuple[float, int, int], float, float]:
87
+ grammar, constraints = parse_file("scriptsizec_evaluation/scriptsizec.fan")
88
+ solutions = []
89
+
90
+ time_in_an_hour = time.time() + seconds
91
+
92
+ while time.time() < time_in_an_hour:
93
+ fandango = Fandango(
94
+ grammar, constraints, desired_solutions=100, logger_level=LoggerLevel.ERROR
95
+ )
96
+ fandango.evolve()
97
+ solutions.extend(fandango.solution)
98
+
99
+ coverage = grammar.compute_grammar_coverage(solutions, 4)
100
+
101
+ valid = []
102
+ for solution in solutions:
103
+ parsed_solution = "int main() {\n"
104
+ parsed_solution += " " + str(solution).replace("\n", " \t")
105
+ parsed_solution += "\n" + "}"
106
+
107
+ fixed_solution = declare_variables(parsed_solution)
108
+
109
+ if is_valid_tinyc_code(str(fixed_solution)):
110
+ valid.append(solution)
111
+
112
+ set_mean_length = sum(len(str(x)) for x in valid) / len(valid)
113
+ set_medium_length = sorted(len(str(x)) for x in valid)[len(valid) // 2]
114
+ valid_percentage = len(valid) / len(solutions) * 100
115
+ return (
116
+ "SCRIPTSIZEC",
117
+ len(solutions),
118
+ len(valid),
119
+ valid_percentage,
120
+ coverage,
121
+ set_mean_length,
122
+ set_medium_length,
123
+ )
File without changes
@@ -0,0 +1,61 @@
1
+ import subprocess
2
+ import tempfile
3
+ import time
4
+ from typing import Tuple
5
+
6
+ from fandango.evolution.algorithm import Fandango, LoggerLevel
7
+ from fandango.language.parse import parse_file
8
+
9
+
10
+ def is_syntactically_valid_tar(tree: str):
11
+ with tempfile.NamedTemporaryFile(suffix=".tar") as outfile:
12
+ outfile.write(tree.encode())
13
+ outfile.flush()
14
+ cmd = ["bsdtar", "-tf", outfile.name]
15
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
16
+ (stdout, stderr) = process.communicate(timeout=10)
17
+ exit_code = process.wait()
18
+
19
+ if exit_code == 0:
20
+ return True
21
+ else:
22
+ return False
23
+
24
+
25
+ def evaluate_tar(
26
+ seconds=60,
27
+ ) -> Tuple[str, int, int, float, Tuple[float, int, int], float, float]:
28
+ grammar, constraints = parse_file("tar_evaluation/tar.fan")
29
+ solutions = []
30
+
31
+ time_in_an_hour = time.time() + seconds
32
+
33
+ while time.time() < time_in_an_hour:
34
+ fandango = Fandango(
35
+ grammar,
36
+ constraints,
37
+ desired_solutions=100,
38
+ logger_level=LoggerLevel.ERROR,
39
+ )
40
+ fandango.evolve()
41
+ solutions.extend(fandango.solution)
42
+
43
+ coverage = grammar.compute_grammar_coverage(solutions, 4)
44
+
45
+ valid = []
46
+ for solution in solutions:
47
+ if is_syntactically_valid_tar(str(solution)):
48
+ valid.append(solution)
49
+
50
+ set_mean_length = sum(len(str(x)) for x in valid) / len(valid)
51
+ set_medium_length = sorted(len(str(x)) for x in valid)[len(valid) // 2]
52
+ valid_percentage = len(valid) / len(solutions) * 100
53
+ return (
54
+ "TAR",
55
+ len(solutions),
56
+ len(valid),
57
+ valid_percentage,
58
+ coverage,
59
+ set_mean_length,
60
+ set_medium_length,
61
+ )
File without changes
@@ -0,0 +1,52 @@
1
+ import time
2
+ import xml.etree.ElementTree as ET
3
+ from typing import Tuple
4
+
5
+ from fandango.evolution.algorithm import Fandango, LoggerLevel
6
+ from fandango.language.parse import parse_file
7
+
8
+
9
+ def is_syntactically_valid_xml(xml_string):
10
+ try:
11
+ # Try to parse the XML string
12
+ ET.fromstring(xml_string)
13
+ return True
14
+ except ET.ParseError as e:
15
+ # If parsing fails, it's not a valid XML
16
+ return False
17
+
18
+
19
+ def evaluate_xml(
20
+ seconds=60,
21
+ ) -> Tuple[str, int, int, float, Tuple[float, int, int], float, float]:
22
+ grammar, constraints = parse_file("xml_evaluation/xml.fan")
23
+ solutions = []
24
+
25
+ time_in_an_hour = time.time() + seconds
26
+
27
+ while time.time() < time_in_an_hour:
28
+ fandango = Fandango(
29
+ grammar, constraints, desired_solutions=100, logger_level=LoggerLevel.ERROR
30
+ )
31
+ fandango.evolve()
32
+ solutions.extend(fandango.solution)
33
+
34
+ coverage = grammar.compute_grammar_coverage(solutions, 4)
35
+
36
+ valid = []
37
+ for solution in solutions:
38
+ if is_syntactically_valid_xml(str(solution)):
39
+ valid.append(solution)
40
+
41
+ set_mean_length = sum(len(str(x)) for x in valid) / len(valid)
42
+ set_medium_length = sorted(len(str(x)) for x in valid)[len(valid) // 2]
43
+ valid_percentage = len(valid) / len(solutions) * 100
44
+ return (
45
+ "XML",
46
+ len(solutions),
47
+ len(valid),
48
+ valid_percentage,
49
+ coverage,
50
+ set_mean_length,
51
+ set_medium_length,
52
+ )
fandango/__init__.py ADDED
File without changes