Kitxuuu commited on
Commit
6b535d6
·
verified ·
1 Parent(s): 3fb76b5

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-python/Dockerfile +20 -0
  2. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/bash_parser.py +235 -0
  3. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh +126 -0
  4. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz +33 -0
  5. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer +60 -0
  6. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/debug_afl +40 -0
  7. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh +25 -0
  8. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_rust.sh +22 -0
  9. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go +69 -0
  10. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/precompile_afl +35 -0
  11. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz +45 -0
  12. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py +120 -0
  13. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/write_labels.py +40 -0
  14. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-image/Dockerfile +46 -0
  15. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/Dockerfile +139 -0
  16. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/bad_build_check +494 -0
  17. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_javascript.sh +30 -0
  18. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/parse_options.py +58 -0
  19. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_all.py +295 -0
  20. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_all_test.py +38 -0
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-python/Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+
17
+ ARG IMG_TAG=latest
18
+ FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG}
19
+
20
+ RUN install_python.sh
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/bash_parser.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # Copyright 2024 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ import sys
18
+
19
+ from glob import glob
20
+
21
+ import bashlex
22
+
23
+
24
+ def find_all_bash_scripts_in_src():
25
+ """Finds all bash scripts that exist in SRC/. This is used to idenfiy scripts
26
+ that may be needed for reading during the AST parsing. This is the case
27
+ when a given build script calls another build script, then we need to
28
+ read those."""
29
+ all_local_scripts = [
30
+ y for x in os.walk('/src/') for y in glob(os.path.join(x[0], '*.sh'))
31
+ ]
32
+ scripts_we_care_about = []
33
+ to_ignore = {'aflplusplus', 'honggfuzz', '/fuzztest', '/centipede'}
34
+ for s in all_local_scripts:
35
+ if any([x for x in to_ignore if x in s]):
36
+ continue
37
+ scripts_we_care_about.append(s)
38
+
39
+ print(scripts_we_care_about)
40
+ return scripts_we_care_about
41
+
42
+
43
+ def should_discard_command(ast_tree) -> bool:
44
+ """Returns True if the command shuold be avoided, otherwise False"""
45
+ try:
46
+ first_word = ast_tree.parts[0].word
47
+ except: # pylint: disable=bare-except
48
+ return False
49
+
50
+ if ('cmake' in first_word and
51
+ any('--build' in part.word for part in ast_tree.parts)):
52
+ return False
53
+
54
+ cmds_to_avoid_replaying = {
55
+ 'configure', 'autoheader', 'autoconf', 'autoreconf', 'cmake', 'autogen.sh'
56
+ }
57
+ if any([cmd for cmd in cmds_to_avoid_replaying if cmd in first_word]):
58
+ return True
59
+
60
+ # Avoid all "make clean" calls. We dont want to erase previously build
61
+ # files.
62
+ try:
63
+ second_word = ast_tree.parts[1].word
64
+ except: # pylint: disable=bare-except
65
+ return False
66
+ if 'make' in first_word and 'clean' in second_word:
67
+ return True
68
+
69
+ # No match was found to commands we dont want to build. There is no
70
+ # indication we shuold avoid.
71
+ return False
72
+
73
+
74
+ def is_local_redirection(ast_node, all_local_scripts):
75
+ """Return the list of scripts corresponding to the command, in case
76
+ the command is an execution of a local script."""
77
+ # print("Checking")
78
+
79
+ # Capture local script called with ./random/path/build.sh
80
+
81
+ if len(ast_node.parts) >= 2:
82
+ try:
83
+ ast_node.parts[0].word
84
+ except:
85
+ return []
86
+ if ast_node.parts[0].word == '.':
87
+ suffixes_matching = []
88
+ #print(ast_node.parts[1].word)
89
+ for bash_script in all_local_scripts:
90
+ #print("- %s"%(bash_script))
91
+ cmd_to_exec = ast_node.parts[1].word.replace('$SRC', 'src')
92
+ if bash_script.endswith(cmd_to_exec):
93
+ suffixes_matching.append(bash_script)
94
+ #print(suffixes_matching)
95
+ return suffixes_matching
96
+ # Capture a local script called with $SRC/random/path/build.sh
97
+ if len(ast_node.parts) >= 1:
98
+ if '$SRC' in ast_node.parts[0].word:
99
+ suffixes_matching = []
100
+ print(ast_node.parts[0].word)
101
+ for bash_script in all_local_scripts:
102
+ print("- %s" % (bash_script))
103
+ cmd_to_exec = ast_node.parts[0].word.replace('$SRC', 'src')
104
+ if bash_script.endswith(cmd_to_exec):
105
+ suffixes_matching.append(bash_script)
106
+ print(suffixes_matching)
107
+ return suffixes_matching
108
+
109
+ return []
110
+
111
+
112
+ def handle_ast_command(ast_node, all_scripts_in_fs, raw_script):
113
+ """Generate bash script string for command node"""
114
+ new_script = ''
115
+ if should_discard_command(ast_node):
116
+ return ''
117
+
118
+ matches = is_local_redirection(ast_node, all_scripts_in_fs)
119
+ if len(matches) == 1:
120
+ new_script += parse_script(matches[0], all_scripts_in_fs) + '\n'
121
+ return ''
122
+
123
+ # Extract the command from the script string
124
+ idx_start = ast_node.pos[0]
125
+ idx_end = ast_node.pos[1]
126
+ new_script += raw_script[idx_start:idx_end]
127
+ #new_script += '\n'
128
+
129
+ # If mkdir is used, then ensure that '-p' is provided, as
130
+ # otherwise we will run into failures. We don't have to worry
131
+ # about multiple uses of -p as `mkdir -p -p -p`` is valid.
132
+ new_script = new_script.replace('mkdir', 'mkdir -p')
133
+ return new_script
134
+
135
+
136
+ def handle_ast_list(ast_node, all_scripts_in_fs, raw_script):
137
+ """Handles bashlex AST list."""
138
+ new_script = ''
139
+ try_hard = 1
140
+
141
+ if not try_hard:
142
+ list_start = ast_node.pos[0]
143
+ list_end = ast_node.pos[1]
144
+ new_script += raw_script[list_start:list_end] # + '\n'
145
+ else:
146
+ # This is more refined logic. Ideally, this should work, but it's a bit
147
+ # more intricate to get right due to e.g. white-space between positions
148
+ # and more extensive parsing needed. We don't neccesarily need this
149
+ # level of success rate for what we're trying to achieve, so am disabling
150
+ # this for now.
151
+ for part in ast_node.parts:
152
+ if part.kind == 'list':
153
+ new_script += handle_ast_list(part, all_scripts_in_fs, raw_script)
154
+ elif part.kind == 'command':
155
+ new_script += handle_ast_command(part, all_scripts_in_fs, raw_script)
156
+ else:
157
+ idx_start = part.pos[0]
158
+ idx_end = part.pos[1]
159
+ new_script += raw_script[idx_start:idx_end]
160
+ new_script += ' '
161
+
162
+ # Make sure what was created is valid syntax, and otherwise return empty
163
+ try:
164
+ bashlex.parse(new_script)
165
+ except: # pylint: disable=bare-except
166
+ # Maybe return the original here instead of skipping?
167
+ return ''
168
+ return new_script
169
+
170
+
171
+ def handle_ast_compound(ast_node, all_scripts_in_fs, raw_script):
172
+ """Handles bashlex compound AST node."""
173
+ new_script = ''
174
+ list_start = ast_node.pos[0]
175
+ list_end = ast_node.pos[1]
176
+ new_script += raw_script[list_start:list_end] + '\n'
177
+ return new_script
178
+
179
+
180
+ def handle_node(ast_node, all_scripts_in_fs, build_script):
181
+ """Generates a bash script string for a given node"""
182
+ if ast_node.kind == 'command':
183
+ return handle_ast_command(ast_node, all_scripts_in_fs, build_script)
184
+ elif ast_node.kind == 'list':
185
+ return handle_ast_list(ast_node, all_scripts_in_fs, build_script)
186
+ elif ast_node.kind == 'compound':
187
+ print('todo: handle compound')
188
+ return handle_ast_compound(ast_node, all_scripts_in_fs, build_script)
189
+ elif ast_node.kind == 'pipeline':
190
+ # Not supported
191
+ return ''
192
+ else:
193
+ raise Exception(f'Missing node handling: {ast_node.kind}')
194
+
195
+
196
+ def parse_script(bash_script, all_scripts) -> str:
197
+ """Top-level bash script parser"""
198
+ new_script = ''
199
+ with open(bash_script, 'r', encoding='utf-8') as f:
200
+ build_script = f.read()
201
+ try:
202
+ parts = bashlex.parse(build_script)
203
+ except bashlex.errors.ParsingError:
204
+ return ''
205
+ for part in parts:
206
+ new_script += handle_node(part, all_scripts, build_script)
207
+ new_script += '\n'
208
+ print("-" * 45)
209
+ print(part.kind)
210
+ print(part.dump())
211
+
212
+ return new_script
213
+
214
+
215
+ def main():
216
+ """Main function"""
217
+ all_scripts = find_all_bash_scripts_in_src()
218
+ replay_bash_script = parse_script(sys.argv[1], all_scripts)
219
+
220
+ print("REPLAYABLE BASH SCRIPT")
221
+ print("#" * 60)
222
+ print(replay_bash_script)
223
+ print("#" * 60)
224
+
225
+ out_dir = os.getenv('OUT', '/out')
226
+ with open(f'{out_dir}/replay-build-script.sh', 'w', encoding='utf-8') as f:
227
+ f.write(replay_bash_script)
228
+
229
+ src_dir = os.getenv('SRC', '/src')
230
+ with open(f'{src_dir}/replay_build.sh', 'w', encoding='utf-8') as f:
231
+ f.write(replay_bash_script)
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ set -x
19
+
20
+ # In order to identify fuzztest test case "bazel query" is used to search
21
+ # the project. A search of the entire project is done with a default "...",
22
+ # however, some projects may fail to, or have very long processing time, if
23
+ # searching the entire project. Additionally, it may include fuzzers in
24
+ # dependencies, which should not be build as part of a given project.
25
+ # Tensorflow is an example project that will fail when the entire project is
26
+ # queried. FUZZTEST_TARGET_FOLDER makes it posible to specify the folder
27
+ # where fuzztest fuzzers should be search for. FUZZTEST_TARGET_FOLDER is passed
28
+ # to "bazel query" below.
29
+ if [[ ${FUZZTEST_TARGET_FOLDER:-"unset"} == "unset" ]];
30
+ then
31
+ export TARGET_FOLDER="..."
32
+ else
33
+ TARGET_FOLDER=${FUZZTEST_TARGET_FOLDER}
34
+ fi
35
+
36
+ BUILD_ARGS="--config=oss-fuzz --subcommands"
37
+ if [[ ${FUZZTEST_EXTRA_ARGS:-"unset"} != "unset" ]];
38
+ then
39
+ BUILD_ARGS="$BUILD_ARGS ${FUZZTEST_EXTRA_ARGS}"
40
+ fi
41
+
42
+ # Trigger setup_configs rule of fuzztest as it generates the necessary
43
+ # configuration file based on OSS-Fuzz environment variables.
44
+ bazel run @com_google_fuzztest//bazel:setup_configs >> /etc/bazel.bazelrc
45
+
46
+ # Bazel target names of the fuzz binaries.
47
+ FUZZ_TEST_BINARIES=$(bazel query "kind(\"cc_test\", rdeps(${TARGET_FOLDER}, @com_google_fuzztest//fuzztest:fuzztest_gtest_main))")
48
+
49
+ # Bazel output paths of the fuzz binaries.
50
+ FUZZ_TEST_BINARIES_OUT_PATHS=$(bazel cquery "kind(\"cc_test\", rdeps(${TARGET_FOLDER}, @com_google_fuzztest//fuzztest:fuzztest_gtest_main))" --output=files)
51
+
52
+ # Build the project and fuzz binaries
53
+ # Expose `FUZZTEST_EXTRA_TARGETS` environment variable, in the event a project
54
+ # includes non-FuzzTest fuzzers then this can be used to compile these in the
55
+ # same `bazel build` command as when building the FuzzTest fuzzers.
56
+ # This is to avoid having to call `bazel build` twice.
57
+ bazel build $BUILD_ARGS -- ${FUZZ_TEST_BINARIES[*]} ${FUZZTEST_EXTRA_TARGETS:-}
58
+
59
+ # Iterate the fuzz binaries and list each fuzz entrypoint in the binary. For
60
+ # each entrypoint create a wrapper script that calls into the binaries the
61
+ # given entrypoint as argument.
62
+ # The scripts will be named:
63
+ # {binary_name}@{fuzztest_entrypoint}
64
+ for fuzz_main_file in $FUZZ_TEST_BINARIES_OUT_PATHS; do
65
+ FUZZ_TESTS=$($fuzz_main_file --list_fuzz_tests)
66
+ cp ${fuzz_main_file} $OUT/
67
+ fuzz_basename=$(basename $fuzz_main_file)
68
+ chmod -x $OUT/$fuzz_basename
69
+ for fuzz_entrypoint in $FUZZ_TESTS; do
70
+ TARGET_FUZZER="${fuzz_basename}@$fuzz_entrypoint"
71
+
72
+ # Write executer script
73
+ echo "#!/bin/sh
74
+ # LLVMFuzzerTestOneInput for fuzzer detection.
75
+ this_dir=\$(dirname \"\$0\")
76
+ chmod +x \$this_dir/$fuzz_basename
77
+ \$this_dir/$fuzz_basename --fuzz=$fuzz_entrypoint -- \$@" > $OUT/$TARGET_FUZZER
78
+ chmod +x $OUT/$TARGET_FUZZER
79
+ done
80
+ done
81
+
82
+ # Synchronise coverage directory to bazel output artifacts. This is a
83
+ # best-effort basis in that it will include source code in common
84
+ # bazel output folders.
85
+ # For projects that store results in non-standard folders or want to
86
+ # manage what code to include in the coverage report more specifically,
87
+ # the FUZZTEST_DO_SYNC environment variable is made available. Projects
88
+ # can then implement a custom way of synchronising source code with the
89
+ # coverage build. Set FUZZTEST_DO_SYNC to something other than "yes" and
90
+ # no effort will be made to automatically synchronise the source code with
91
+ # the code coverage visualisation utility.
92
+ if [[ "$SANITIZER" = "coverage" && ${FUZZTEST_DO_SYNC:-"yes"} == "yes" ]]
93
+ then
94
+ # Synchronize bazel source files to coverage collection.
95
+ declare -r REMAP_PATH="${OUT}/proc/self/cwd"
96
+ mkdir -p "${REMAP_PATH}"
97
+
98
+ # Synchronize the folder bazel-BAZEL_OUT_PROJECT.
99
+ declare -r RSYNC_FILTER_ARGS=("--include" "*.h" "--include" "*.cc" "--include" \
100
+ "*.hpp" "--include" "*.cpp" "--include" "*.c" "--include" "*/" "--include" "*.inc" \
101
+ "--exclude" "*")
102
+
103
+ project_folders="$(find . -name 'bazel-*' -type l -printf '%P\n' | \
104
+ grep -v -x -F \
105
+ -e 'bazel-bin' \
106
+ -e 'bazel-testlogs')"
107
+ for link in $project_folders; do
108
+ if [[ -d "${PWD}"/$link/external ]]
109
+ then
110
+ rsync -avLk "${RSYNC_FILTER_ARGS[@]}" "${PWD}"/$link/external "${REMAP_PATH}"
111
+ fi
112
+ # k8-opt is a common path for storing bazel output artifacts, e.g. bazel-out/k8-opt.
113
+ # It's the output folder for default amd-64 builds, but projects may specify custom
114
+ # platform output directories, see: https://github.com/bazelbuild/bazel/issues/13818
115
+ # We support the default at the moment, and if a project needs custom synchronizing of
116
+ # output artifacts and code coverage we currently recommend using FUZZTEST_DO_SYNC.
117
+ if [[ -d "${PWD}"/$link/k8-opt ]]
118
+ then
119
+ rsync -avLk "${RSYNC_FILTER_ARGS[@]}" "${PWD}"/$link/k8-opt "${REMAP_PATH}"/$link
120
+ fi
121
+ done
122
+
123
+ # Delete symlinks and sync the current folder.
124
+ find . -type l -ls -delete
125
+ rsync -av ${PWD}/ "${REMAP_PATH}"
126
+ fi
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2016 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ echo "Skipping compilation; using precompiled honggfuzz"
19
+
20
+ cp $SRC/honggfuzz/honggfuzz.a $LIB_FUZZING_ENGINE
21
+ cp $SRC/honggfuzz/honggfuzz $OUT/
22
+
23
+ # Set flags necessary for netdriver compilation.
24
+ export LIB_HFND="-Wl,-u,LIBHFNETDRIVER_module_netdriver -Wl,--start-group $SRC/honggfuzz/libhfnetdriver/libhfnetdriver.a $SRC/honggfuzz/libhfcommon/libhfcommon.a -Wl,--end-group"
25
+
26
+ export HFND_CXXFLAGS='-DHFND_FUZZING_ENTRY_FUNCTION_CXX(x,y)=extern const char* LIBHFNETDRIVER_module_netdriver;const char** LIBHFNETDRIVER_tmp1 = &LIBHFNETDRIVER_module_netdriver;extern "C" int HonggfuzzNetDriver_main(x,y);int HonggfuzzNetDriver_main(x,y)'
27
+ export HFND_CFLAGS='-DHFND_FUZZING_ENTRY_FUNCTION(x,y)=extern const char* LIBHFNETDRIVER_module_netdriver;const char** LIBHFNETDRIVER_tmp1 = &LIBHFNETDRIVER_module_netdriver;int HonggfuzzNetDriver_main(x,y);int HonggfuzzNetDriver_main(x,y)'
28
+
29
+ # Custom coverage flags, roughly in sync with:
30
+ # https://github.com/google/honggfuzz/blob/oss-fuzz/hfuzz_cc/hfuzz-cc.c
31
+ export COVERAGE_FLAGS="-fsanitize-coverage=trace-pc-guard,indirect-calls,trace-cmp"
32
+
33
+ echo " done."
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ function build_native_go_fuzzer() {
19
+ fuzzer=$1
20
+ function=$2
21
+ path=$3
22
+ tags="-tags gofuzz"
23
+
24
+ if [[ $SANITIZER == *coverage* ]]; then
25
+ current_dir=$(pwd)
26
+ mkdir $OUT/rawfuzzers || true
27
+ cd $abs_file_dir
28
+ go test $tags -c -run $fuzzer -o $OUT/$fuzzer -cover
29
+ cp "${fuzzer_filename}" "${OUT}/rawfuzzers/${fuzzer}"
30
+
31
+ fuzzed_repo=$(go list $tags -f {{.Module}} "$path")
32
+ abspath_repo=`go list -m $tags -f {{.Dir}} $fuzzed_repo || go list $tags -f {{.Dir}} $fuzzed_repo`
33
+ # give equivalence to absolute paths in another file, as go test -cover uses golangish pkg.Dir
34
+ echo "s=$fuzzed_repo"="$abspath_repo"= > $OUT/$fuzzer.gocovpath
35
+
36
+ cd $current_dir
37
+ else
38
+ go-118-fuzz-build $tags -o $fuzzer.a -func $function $abs_file_dir
39
+ $CXX $CXXFLAGS $LIB_FUZZING_ENGINE $fuzzer.a -o $OUT/$fuzzer
40
+ fi
41
+ }
42
+
43
+ path=$1
44
+ function=$2
45
+ fuzzer=$3
46
+ tags="-tags gofuzz"
47
+
48
+ # Get absolute path.
49
+ abs_file_dir=$(go list $tags -f {{.Dir}} $path)
50
+
51
+ # TODO(adamkorcz): Get rid of "-r" flag here.
52
+ fuzzer_filename=$(grep -r -l --include='*.go' -s "$function" "${abs_file_dir}")
53
+
54
+ # Test if file contains a line with "func $function" and "testing.F".
55
+ if [ $(grep -r "func $function" $fuzzer_filename | grep "testing.F" | wc -l) -eq 1 ]
56
+ then
57
+ build_native_go_fuzzer $fuzzer $function $abs_file_dir
58
+ else
59
+ echo "Could not find the function: func ${function}(f *testing.F)"
60
+ fi
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/debug_afl ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Copyright 2021 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ # Source this file for afl++ debug sessions.
19
+ apt-get update
20
+ apt-get install -y strace gdb vim joe psmisc
21
+
22
+ pushd $SRC/aflplusplus > /dev/null
23
+ git checkout dev
24
+ git pull
25
+ test -n "$1" && { git checkout "$1" ; git pull ; }
26
+ CFLAGS_SAVE="$CFLAGS"
27
+ CXXFLAGS_SAVE="$CXXFLAGS"
28
+ unset CFLAGS
29
+ unset CXXFLAGS
30
+ make
31
+ export CFLAGS="$CFLAGS_SAVE"
32
+ export CXXFLAGS="$CXXFLAGS_SAVE"
33
+ popd > /dev/null
34
+
35
+ export ASAN_OPTIONS="detect_leaks=0:symbolize=0:detect_odr_violation=0:abort_on_error=1"
36
+ export AFL_LLVM_LAF_ALL=1
37
+ export AFL_LLVM_CMPLOG=1
38
+ touch "$OUT/afl_cmplog.txt"
39
+ export AFL_LLVM_DICT2FILE=$OUT/afl++.dict
40
+ ulimit -c unlimited
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Copyright 2024 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ apt update
19
+ apt install -y lsb-release software-properties-common gnupg2 binutils xz-utils libyaml-dev
20
+ gpg2 --keyserver keyserver.ubuntu.com --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
21
+ curl -sSL https://get.rvm.io | bash
22
+
23
+ . /etc/profile.d/rvm.sh
24
+
25
+ rvm install ruby-3.3.1
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_rust.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
2
+ # Copyright 2021 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=$RUSTUP_TOOLCHAIN --profile=minimal
19
+ cargo install cargo-fuzz --locked && rm -rf /rust/registry
20
+ # Needed to recompile rust std library for MSAN
21
+ rustup component add rust-src
22
+ cp -r /usr/local/lib/x86_64-unknown-linux-gnu/* /usr/local/lib/
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package mypackagebeingfuzzed
16
+
17
+ import (
18
+ "io/ioutil"
19
+ "os"
20
+ "runtime/pprof"
21
+ "testing"
22
+ )
23
+
24
+ func TestFuzzCorpus(t *testing.T) {
25
+ dir := os.Getenv("FUZZ_CORPUS_DIR")
26
+ if dir == "" {
27
+ t.Logf("No fuzzing corpus directory set")
28
+ return
29
+ }
30
+ infos, err := ioutil.ReadDir(dir)
31
+ if err != nil {
32
+ t.Logf("Not fuzzing corpus directory %s", err)
33
+ return
34
+ }
35
+ filename := ""
36
+ defer func() {
37
+ if r := recover(); r != nil {
38
+ t.Error("Fuzz panicked in "+filename, r)
39
+ }
40
+ }()
41
+ profname := os.Getenv("FUZZ_PROFILE_NAME")
42
+ if profname != "" {
43
+ f, err := os.Create(profname + ".cpu.prof")
44
+ if err != nil {
45
+ t.Logf("error creating profile file %s\n", err)
46
+ } else {
47
+ _ = pprof.StartCPUProfile(f)
48
+ }
49
+ }
50
+ for i := range infos {
51
+ filename = dir + infos[i].Name()
52
+ data, err := ioutil.ReadFile(filename)
53
+ if err != nil {
54
+ t.Error("Failed to read corpus file", err)
55
+ }
56
+ FuzzFunction(data)
57
+ }
58
+ if profname != "" {
59
+ pprof.StopCPUProfile()
60
+ f, err := os.Create(profname + ".heap.prof")
61
+ if err != nil {
62
+ t.Logf("error creating heap profile file %s\n", err)
63
+ }
64
+ if err = pprof.WriteHeapProfile(f); err != nil {
65
+ t.Logf("error writing heap profile file %s\n", err)
66
+ }
67
+ f.Close()
68
+ }
69
+ }
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/precompile_afl ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2021 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ echo "Precompiling AFLplusplus"
19
+
20
+ pushd $SRC/aflplusplus > /dev/null
21
+ make clean
22
+ # Unset CFLAGS and CXXFLAGS while building AFL since we don't want to slow it
23
+ # down with sanitizers.
24
+ SAVE_CXXFLAGS=$CXXFLAGS
25
+ SAVE_CFLAGS=$CFLAGS
26
+ unset CXXFLAGS
27
+ unset CFLAGS
28
+ export AFL_IGNORE_UNKNOWN_ENVS=1
29
+ make clean
30
+ AFL_NO_X86=1 PYTHON_INCLUDE=/ make
31
+ make -C utils/aflpp_driver
32
+
33
+ popd > /dev/null
34
+
35
+ echo "Done."
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2019 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ echo "Precompiling honggfuzz"
19
+ export BUILD_OSSFUZZ_STATIC=true
20
+
21
+ PACKAGES=(
22
+ libunwind8-dev
23
+ libblocksruntime-dev
24
+ liblzma-dev
25
+ libiberty-dev
26
+ zlib1g-dev
27
+ pkg-config)
28
+
29
+ apt-get update && apt-get install -y ${PACKAGES[@]}
30
+
31
+ pushd $SRC/honggfuzz > /dev/null
32
+ make clean
33
+ # These CFLAGs match honggfuzz's default, with the exception of -mtune to
34
+ # improve portability and `-D_HF_LINUX_NO_BFD` to remove assembly instructions
35
+ # from the filenames.
36
+ CC=clang CFLAGS="-O3 -funroll-loops -D_HF_LINUX_NO_BFD" make
37
+
38
+ # libhfuzz.a will be added by CC/CXX linker directly during linking,
39
+ # but it's defined here to satisfy the build infrastructure
40
+ ar rcs honggfuzz.a libhfuzz/*.o libhfcommon/*.o
41
+ popd > /dev/null
42
+
43
+ apt-get remove -y --purge ${PACKAGES[@]}
44
+ apt-get autoremove -y
45
+ echo "Done."
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Extracts file paths to copy files from pyinstaller-generated executables"""
15
+ import os
16
+ import sys
17
+ import shutil
18
+ import zipfile
19
+
20
+
21
+ # Finds all *.toc files in ./workpath and reads these files in order to
22
+ # identify Python files associated with a pyinstaller packaged executable.
23
+ # Copies all of the Python files to a temporary directory (/medio) following
24
+ # the original directory structure.
25
+ def get_all_files_from_toc(toc_file, file_path_set):
26
+ """
27
+ Extract filepaths from a .toc file and add to file_path_set
28
+ """
29
+ with open(toc_file, 'rb') as toc_file_fd:
30
+ for line in toc_file_fd:
31
+ try:
32
+ line = line.decode()
33
+ except: # pylint:disable=bare-except
34
+ continue
35
+ if '.py' not in line:
36
+ continue
37
+
38
+ split_line = line.split(' ')
39
+ for word in split_line:
40
+ word = word.replace('\'', '').replace(',', '').replace('\n', '')
41
+ if '.py' not in word:
42
+ continue
43
+ # Check if .egg is in the path and if so we need to split it
44
+ if os.path.isfile(word):
45
+ file_path_set.add(word)
46
+ elif '.egg' in word: # check if this is an egg
47
+ egg_path_split = word.split('.egg')
48
+ if len(egg_path_split) != 2:
49
+ continue
50
+ egg_path = egg_path_split[0] + '.egg'
51
+ if not os.path.isfile(egg_path):
52
+ continue
53
+
54
+ print('Unzipping contents of %s' % egg_path)
55
+
56
+ # We have an egg. This needs to be unzipped and then replaced
57
+ # with the unzipped data.
58
+ tmp_dir_name = 'zipdcontents'
59
+ if os.path.isdir(tmp_dir_name):
60
+ shutil.rmtree(tmp_dir_name)
61
+
62
+ # unzip egg and replace path with unzipped content
63
+ with zipfile.ZipFile(egg_path, 'r') as zip_f:
64
+ zip_f.extractall(tmp_dir_name)
65
+ os.remove(egg_path)
66
+ shutil.copytree(tmp_dir_name, egg_path)
67
+
68
+ # Now the lines should be accessible, so check again
69
+ if os.path.isfile(word):
70
+ file_path_set.add(word)
71
+
72
+
73
+ def create_file_structure_from_tocs(work_path, out_path):
74
+ """
75
+ Extract the Python files that are added as paths in the output of
76
+ a pyinstaller operation. The files are determined by reading through
77
+ all of the *.toc files in the workpath of pyinstaller.
78
+
79
+ The files will be copied into the out_path using a similar file path
80
+ as they originally are. If any archive (.egg) files are present in the
81
+ .toc files, then unzip the archives and substitute the archive for the
82
+ unzipped content, i.e. we will extract the archives and collect the source
83
+ files.
84
+ """
85
+ print('Extracts files from the pyinstaller workpath')
86
+ file_path_set = set()
87
+ for path1 in os.listdir(work_path):
88
+ full_path = os.path.join(work_path, path1)
89
+ if not os.path.isdir(full_path):
90
+ continue
91
+
92
+ # We have a directory
93
+ for path2 in os.listdir(full_path):
94
+ if not '.toc' in path2:
95
+ continue
96
+ full_toc_file = os.path.join(full_path, path2)
97
+ get_all_files_from_toc(full_toc_file, file_path_set)
98
+
99
+ for file_path in file_path_set:
100
+ relative_src = file_path[1:] if file_path[0] == '/' else file_path
101
+ dst_path = os.path.join(out_path, relative_src)
102
+ os.makedirs(os.path.dirname(dst_path), exist_ok=True)
103
+ shutil.copy(file_path, dst_path)
104
+
105
+
106
+ def main():
107
+ """
108
+ Main handler.
109
+ """
110
+ if len(sys.argv) != 3:
111
+ print('Use: python3 python_coverage_helper.py pyinstaller_workpath '
112
+ 'destination_for_output')
113
+ sys.exit(1)
114
+ work_path = sys.argv[1]
115
+ out_path = sys.argv[2]
116
+ create_file_structure_from_tocs(work_path, out_path)
117
+
118
+
119
+ if __name__ == '__main__':
120
+ main()
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/write_labels.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2021 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Script for writing from project.yaml to .labels file."""
16
+
17
+ import os
18
+ import json
19
+ import sys
20
+
21
+
22
+ def main():
23
+ """Writes labels."""
24
+ if len(sys.argv) != 3:
25
+ print('Usage: write_labels.py labels_json out_dir', file=sys.stderr)
26
+ sys.exit(1)
27
+
28
+ labels_by_target = json.loads(sys.argv[1])
29
+ out = sys.argv[2]
30
+
31
+ for target_name, labels in labels_by_target.items():
32
+ # Skip over wildcard value applying to all fuzz targets
33
+ if target_name == '*':
34
+ continue
35
+ with open(os.path.join(out, target_name + '.labels'), 'w') as file_handle:
36
+ file_handle.write('\n'.join(labels))
37
+
38
+
39
+ if __name__ == '__main__':
40
+ main()
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-image/Dockerfile ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+
17
+ # Base image for all other images.
18
+
19
+ ARG parent_image=ubuntu:20.04@sha256:4a45212e9518f35983a976eead0de5eecc555a2f047134e9dd2cfc589076a00d
20
+
21
+ FROM $parent_image
22
+
23
+ ENV DEBIAN_FRONTEND noninteractive
24
+ # Install tzadata to match ClusterFuzz
25
+ # (https://github.com/google/oss-fuzz/issues/9280).
26
+
27
+ # Use Azure mirrors for consistent apt repository access.
28
+ RUN cp /etc/apt/sources.list /etc/apt/sources.list.backup && \
29
+ sed -i 's|http://archive.ubuntu.com/ubuntu/|http://azure.archive.ubuntu.com/ubuntu/|g' /etc/apt/sources.list && \
30
+ sed -i 's|http://security.ubuntu.com/ubuntu/|http://azure.archive.ubuntu.com/ubuntu/|g' /etc/apt/sources.list
31
+
32
+
33
+ RUN apt-get update && \
34
+ apt-get upgrade -y && \
35
+ apt-get install -y libc6-dev binutils libgcc-9-dev tzdata locales locales-all && \
36
+ apt-get autoremove -y
37
+
38
+ ENV OUT=/out
39
+ ENV SRC=/src
40
+ ENV WORK=/work
41
+ ENV PATH="$PATH:/out"
42
+ ENV HWASAN_OPTIONS=random_tags=0
43
+ #set locale to utf8
44
+ ENV LC_ALL=C.UTF-8
45
+
46
+ RUN mkdir -p $OUT $SRC $WORK && chmod a+rwx $OUT $SRC $WORK
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/Dockerfile ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+
17
+ # Build rust stuff in its own image. We only need the resulting binaries.
18
+ # Keeping the rust toolchain in the image wastes 1 GB.
19
+ ARG IMG_TAG=latest
20
+ FROM ghcr.io/aixcc-finals/base-image:${IMG_TAG} as temp-runner-binary-builder
21
+
22
+ RUN apt-get update && apt-get install -y cargo libyaml-dev
23
+ RUN cargo install rustfilt
24
+
25
+ # Using multi-stage build to copy some LLVM binaries needed in the runner image.
26
+ FROM ghcr.io/aixcc-finals/base-clang:${IMG_TAG} AS base-clang
27
+ FROM ghcr.io/aixcc-finals/base-builder-ruby:${IMG_TAG} AS base-ruby
28
+
29
+ # The base builder image compiles a specific Python version. Using a multi-stage build
30
+ # to copy that same Python interpreter into the runner image saves build time and keeps
31
+ # the Python versions in sync.
32
+ FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} AS base-builder
33
+
34
+ # Real image that will be used later.
35
+ FROM ghcr.io/aixcc-finals/base-image:${IMG_TAG}
36
+
37
+ COPY --from=temp-runner-binary-builder /root/.cargo/bin/rustfilt /usr/local/bin
38
+
39
+ # Copy the binaries needed for code coverage and crash symbolization.
40
+ COPY --from=base-clang /usr/local/bin/llvm-cov \
41
+ /usr/local/bin/llvm-profdata \
42
+ /usr/local/bin/llvm-symbolizer \
43
+ /usr/local/bin/
44
+
45
+ # Copy the pre-compiled Python binaries and libraries
46
+ COPY --from=base-builder /usr/local/bin/python3.10 /usr/local/bin/python3.10
47
+ COPY --from=base-builder /usr/local/lib/libpython3.10.so.1.0 /usr/local/lib/libpython3.10.so.1.0
48
+ COPY --from=base-builder /usr/local/include/python3.10 /usr/local/include/python3.10
49
+ COPY --from=base-builder /usr/local/lib/python3.10 /usr/local/lib/python3.10
50
+ COPY --from=base-builder /usr/local/bin/pip3 /usr/local/bin/pip3
51
+
52
+ # Create symbolic links to ensure compatibility
53
+ RUN ldconfig && \
54
+ ln -s /usr/local/bin/python3.10 /usr/local/bin/python3 && \
55
+ ln -s /usr/local/bin/python3.10 /usr/local/bin/python
56
+
57
+ COPY install_deps.sh /
58
+ RUN /install_deps.sh && rm /install_deps.sh
59
+
60
+ ENV CODE_COVERAGE_SRC=/opt/code_coverage
61
+ # Pin coverage to the same as in the base builder:
62
+ # https://github.com/google/oss-fuzz/blob/master/infra/base-images/base-builder/install_python.sh#L22
63
+ RUN git clone https://chromium.googlesource.com/chromium/src/tools/code_coverage $CODE_COVERAGE_SRC && \
64
+ cd /opt/code_coverage && \
65
+ git checkout edba4873b5e8a390e977a64c522db2df18a8b27d && \
66
+ pip3 install wheel && \
67
+ # If version "Jinja2==2.10" is in requirements.txt, bump it to a patch version that
68
+ # supports upgrading its MarkupSafe dependency to a Python 3.10 compatible release:
69
+ sed -i 's/Jinja2==2.10/Jinja2==2.10.3/' requirements.txt && \
70
+ pip3 install -r requirements.txt && \
71
+ pip3 install MarkupSafe==2.0.1 && \
72
+ pip3 install coverage==6.3.2
73
+
74
+ # Default environment options for various sanitizers.
75
+ # Note that these match the settings used in ClusterFuzz and
76
+ # shouldn't be changed unless a corresponding change is made on
77
+ # ClusterFuzz side as well.
78
+ ENV ASAN_OPTIONS="alloc_dealloc_mismatch=0:allocator_may_return_null=1:allocator_release_to_os_interval_ms=500:check_malloc_usable_size=0:detect_container_overflow=1:detect_odr_violation=0:detect_leaks=1:detect_stack_use_after_return=1:fast_unwind_on_fatal=0:handle_abort=1:handle_segv=1:handle_sigill=1:max_uar_stack_size_log=16:print_scariness=1:quarantine_size_mb=10:strict_memcmp=1:strip_path_prefix=/workspace/:symbolize=1:use_sigaltstack=1:dedup_token_length=3"
79
+ ENV MSAN_OPTIONS="print_stats=1:strip_path_prefix=/workspace/:symbolize=1:dedup_token_length=3"
80
+ ENV UBSAN_OPTIONS="print_stacktrace=1:print_summary=1:silence_unsigned_overflow=1:strip_path_prefix=/workspace/:symbolize=1:dedup_token_length=3"
81
+ ENV FUZZER_ARGS="-rss_limit_mb=2560 -timeout=25"
82
+ ENV AFL_FUZZER_ARGS="-m none"
83
+
84
+ # Set up Golang environment variables (copied from /root/.bash_profile).
85
+ ENV GOPATH /root/go
86
+
87
+ # /root/.go/bin is for the standard Go binaries (i.e. go, gofmt, etc).
88
+ # $GOPATH/bin is for the binaries from the dependencies installed via "go get".
89
+ ENV PATH $PATH:$GOPATH/bin
90
+ COPY gocoverage $GOPATH/gocoverage
91
+
92
+ COPY install_go.sh /
93
+ RUN /install_go.sh && rm -rf /install_go.sh /root/.go
94
+
95
+ # Install OpenJDK 15 and trim its size by removing unused components.
96
+ ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
97
+ ENV JAVA_15_HOME=/usr/lib/jvm/java-15-openjdk-amd64
98
+ ENV JVM_LD_LIBRARY_PATH=$JAVA_HOME/lib/server
99
+ ENV PATH=$PATH:$JAVA_HOME/bin
100
+
101
+ COPY install_java.sh /
102
+ RUN /install_java.sh && rm /install_java.sh
103
+
104
+ # Install JaCoCo for JVM coverage.
105
+ RUN wget https://repo1.maven.org/maven2/org/jacoco/org.jacoco.cli/0.8.7/org.jacoco.cli-0.8.7-nodeps.jar -O /opt/jacoco-cli.jar && \
106
+ wget https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.8.7/org.jacoco.agent-0.8.7-runtime.jar -O /opt/jacoco-agent.jar && \
107
+ echo "37df187b76888101ecd745282e9cd1ad4ea508d6 /opt/jacoco-agent.jar" | shasum --check && \
108
+ echo "c1814e7bba5fd8786224b09b43c84fd6156db690 /opt/jacoco-cli.jar" | shasum --check
109
+
110
+ COPY install_javascript.sh /
111
+ RUN /install_javascript.sh && rm /install_javascript.sh
112
+
113
+ # Copy built ruby and ruzzy from builder
114
+ COPY --from=base-ruby /usr/local/rvm /usr/local/rvm
115
+ COPY --from=base-ruby /install/ruzzy /install/ruzzy
116
+ COPY ruzzy /usr/bin/ruzzy
117
+ ENV PATH="$PATH:/usr/local/rvm/rubies/ruby-3.3.1/bin"
118
+ # RubyGems installation directory
119
+ ENV GEM_HOME="$OUT/fuzz-gem"
120
+ ENV GEM_PATH="/install/ruzzy"
121
+
122
+ # Do this last to make developing these files easier/faster due to caching.
123
+ COPY bad_build_check \
124
+ coverage \
125
+ coverage_helper \
126
+ download_corpus \
127
+ jacoco_report_converter.py \
128
+ nyc_report_converter.py \
129
+ rcfilt \
130
+ reproduce \
131
+ run_fuzzer \
132
+ parse_options.py \
133
+ generate_differential_cov_report.py \
134
+ profraw_update.py \
135
+ targets_list \
136
+ test_all.py \
137
+ test_one.py \
138
+ python_coverage_runner_help.py \
139
+ /usr/local/bin/
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/bad_build_check ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -u
2
+ # Copyright 2017 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ # A minimal number of runs to test fuzz target with a non-empty input.
19
+ MIN_NUMBER_OF_RUNS=4
20
+
21
+ # The "example" target has 73 with ASan, 65 with UBSan, and 6648 with MSan.
22
+ # Real world targets have greater values (arduinojson: 407, zlib: 664).
23
+ # Mercurial's bdiff_fuzzer has 116 PCs when built with ASan.
24
+ THRESHOLD_FOR_NUMBER_OF_EDGES=100
25
+
26
+ # A fuzz target is supposed to have at least two functions, such as
27
+ # LLVMFuzzerTestOneInput and an API that is being called from there.
28
+ THRESHOLD_FOR_NUMBER_OF_FUNCTIONS=2
29
+
30
+ # Threshold values for different sanitizers used by instrumentation checks.
31
+ ASAN_CALLS_THRESHOLD_FOR_ASAN_BUILD=1000
32
+ ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD=0
33
+
34
+ # The value below can definitely be higher (like 500-1000), but avoid being too
35
+ # agressive here while still evaluating the DFT-based fuzzing approach.
36
+ DFSAN_CALLS_THRESHOLD_FOR_DFSAN_BUILD=100
37
+ DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD=0
38
+
39
+ MSAN_CALLS_THRESHOLD_FOR_MSAN_BUILD=1000
40
+ # Some engines (e.g. honggfuzz) may make a very small number of calls to msan
41
+ # for memory poisoning.
42
+ MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD=3
43
+
44
+ # Usually, a non UBSan build (e.g. ASan) has 165 calls to UBSan runtime. The
45
+ # majority of targets built with UBSan have 200+ UBSan calls, but there are
46
+ # some very small targets that may have < 200 UBSan calls even in a UBSan build.
47
+ # Use the threshold value of 168 (slightly > 165) for UBSan build.
48
+ UBSAN_CALLS_THRESHOLD_FOR_UBSAN_BUILD=168
49
+
50
+ # It would be risky to use the threshold value close to 165 for non UBSan build,
51
+ # as UBSan runtime may change any time and thus we could have different number
52
+ # of calls to UBSan runtime even in ASan build. With that, we use the threshold
53
+ # value of 200 that would detect unnecessary UBSan instrumentation in the vast
54
+ # majority of targets, except of a handful very small ones, which would not be
55
+ # a big concern either way as the overhead for them would not be significant.
56
+ UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD=200
57
+
58
+ # ASan builds on i386 generally have about 250 UBSan runtime calls.
59
+ if [[ $ARCHITECTURE == 'i386' ]]
60
+ then
61
+ UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD=280
62
+ fi
63
+
64
+
65
+ # Verify that the given fuzz target is correctly built to run with a particular
66
+ # engine.
67
+ function check_engine {
68
+ local FUZZER=$1
69
+ local FUZZER_NAME=$(basename $FUZZER)
70
+ local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output"
71
+ local CHECK_FAILED=0
72
+
73
+ if [[ "$FUZZING_ENGINE" == libfuzzer ]]; then
74
+ # Store fuzz target's output into a temp file to be used for further checks.
75
+ $FUZZER -seed=1337 -runs=$MIN_NUMBER_OF_RUNS &>$FUZZER_OUTPUT
76
+ CHECK_FAILED=$(egrep "ERROR: no interesting inputs were found. Is the code instrumented" -c $FUZZER_OUTPUT)
77
+ if (( $CHECK_FAILED > 0 )); then
78
+ echo "BAD BUILD: $FUZZER does not seem to have coverage instrumentation."
79
+ cat $FUZZER_OUTPUT
80
+ # Bail out as the further check does not make any sense, there are 0 PCs.
81
+ return 1
82
+ fi
83
+
84
+ local NUMBER_OF_EDGES=$(grep -Po "INFO: Loaded [[:digit:]]+ module.*\(.*(counters|guards)\):[[:space:]]+\K[[:digit:]]+" $FUZZER_OUTPUT)
85
+
86
+ # If a fuzz target fails to start, grep won't find anything, so bail out early to let check_startup_crash deal with it.
87
+ [[ -z "$NUMBER_OF_EDGES" ]] && return
88
+
89
+ if (( $NUMBER_OF_EDGES < $THRESHOLD_FOR_NUMBER_OF_EDGES )); then
90
+ echo "BAD BUILD: $FUZZER seems to have only partial coverage instrumentation."
91
+ fi
92
+ elif [[ "$FUZZING_ENGINE" == afl ]]; then
93
+ AFL_FORKSRV_INIT_TMOUT=30000 AFL_NO_UI=1 SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 35s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT
94
+ CHECK_PASSED=$(egrep "All set and ready to roll" -c $FUZZER_OUTPUT)
95
+ if (( $CHECK_PASSED == 0 )); then
96
+ echo "BAD BUILD: fuzzing $FUZZER with afl-fuzz failed."
97
+ cat $FUZZER_OUTPUT
98
+ return 1
99
+ fi
100
+ elif [[ "$FUZZING_ENGINE" == honggfuzz ]]; then
101
+ SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 20s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT
102
+ CHECK_PASSED=$(egrep "^Sz:[0-9]+ Tm:[0-9]+" -c $FUZZER_OUTPUT)
103
+ if (( $CHECK_PASSED == 0 )); then
104
+ echo "BAD BUILD: fuzzing $FUZZER with honggfuzz failed."
105
+ cat $FUZZER_OUTPUT
106
+ return 1
107
+ fi
108
+ elif [[ "$FUZZING_ENGINE" == dataflow ]]; then
109
+ $FUZZER &> $FUZZER_OUTPUT
110
+ local NUMBER_OF_FUNCTIONS=$(grep -Po "INFO:\s+\K[[:digit:]]+(?=\s+instrumented function.*)" $FUZZER_OUTPUT)
111
+ [[ -z "$NUMBER_OF_FUNCTIONS" ]] && NUMBER_OF_FUNCTIONS=0
112
+ if (( $NUMBER_OF_FUNCTIONS < $THRESHOLD_FOR_NUMBER_OF_FUNCTIONS )); then
113
+ echo "BAD BUILD: $FUZZER does not seem to be properly built in 'dataflow' config."
114
+ cat $FUZZER_OUTPUT
115
+ return 1
116
+ fi
117
+ elif [[ "$FUZZING_ENGINE" == centipede \
118
+ && ("${HELPER:-}" == True || "$SANITIZER" == none ) ]]; then
119
+ # Performs run test on unsanitized binaries with auxiliary sanitized
120
+ # binaries if they are built with helper.py.
121
+ # Performs run test on unsanitized binaries without auxiliary sanitized
122
+ # binaries if they are from trial build and production build.
123
+ # TODO(Dongge): Support run test with sanitized binaries for trial and
124
+ # production build.
125
+ SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 20s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT
126
+ CHECK_PASSED=$(egrep "\[S0.0] begin-fuzz: ft: 0 corp: 0/0" -c $FUZZER_OUTPUT)
127
+ if (( $CHECK_PASSED == 0 )); then
128
+ echo "BAD BUILD: fuzzing $FUZZER with centipede failed."
129
+ cat $FUZZER_OUTPUT
130
+ return 1
131
+ fi
132
+ fi
133
+
134
+ return 0
135
+ }
136
+
137
+ # Verify that the given fuzz target has been built properly and works.
138
+ function check_startup_crash {
139
+ local FUZZER=$1
140
+ local FUZZER_NAME=$(basename $FUZZER)
141
+ local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output"
142
+ local CHECK_PASSED=0
143
+
144
+ if [[ "$FUZZING_ENGINE" = libfuzzer ]]; then
145
+ # Skip seed corpus as there is another explicit check that uses seed corpora.
146
+ SKIP_SEED_CORPUS=1 run_fuzzer $FUZZER_NAME -seed=1337 -runs=$MIN_NUMBER_OF_RUNS &>$FUZZER_OUTPUT
147
+ CHECK_PASSED=$(egrep "Done $MIN_NUMBER_OF_RUNS runs" -c $FUZZER_OUTPUT)
148
+ elif [[ "$FUZZING_ENGINE" = afl ]]; then
149
+ AFL_FORKSRV_INIT_TMOUT=30000 AFL_NO_UI=1 SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 35s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT
150
+ if [ $(egrep "target binary (crashed|terminated)" -c $FUZZER_OUTPUT) -eq 0 ]; then
151
+ CHECK_PASSED=1
152
+ fi
153
+ elif [[ "$FUZZING_ENGINE" = dataflow ]]; then
154
+ # TODO(https://github.com/google/oss-fuzz/issues/1632): add check for
155
+ # binaries compiled with dataflow engine when the interface becomes stable.
156
+ CHECK_PASSED=1
157
+ else
158
+ # TODO: add checks for another fuzzing engines if possible.
159
+ CHECK_PASSED=1
160
+ fi
161
+
162
+ if [ "$CHECK_PASSED" -eq "0" ]; then
163
+ echo "BAD BUILD: $FUZZER seems to have either startup crash or exit:"
164
+ cat $FUZZER_OUTPUT
165
+ return 1
166
+ fi
167
+
168
+ return 0
169
+ }
170
+
171
+ # Mixed sanitizers check for ASan build.
172
+ function check_asan_build {
173
+ local FUZZER=$1
174
+ local ASAN_CALLS=$2
175
+ local DFSAN_CALLS=$3
176
+ local MSAN_CALLS=$4
177
+ local UBSAN_CALLS=$5
178
+
179
+ # Perform all the checks for more detailed error message.
180
+ if (( $ASAN_CALLS < $ASAN_CALLS_THRESHOLD_FOR_ASAN_BUILD )); then
181
+ echo "BAD BUILD: $FUZZER does not seem to be compiled with ASan."
182
+ return 1
183
+ fi
184
+
185
+ if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then
186
+ echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with DFSan."
187
+ return 1
188
+ fi
189
+
190
+ if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then
191
+ echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with MSan."
192
+ return 1
193
+ fi
194
+
195
+ if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then
196
+ echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with UBSan."
197
+ return 1
198
+ fi
199
+
200
+ return 0
201
+ }
202
+
203
+ # Mixed sanitizers check for DFSan build.
204
+ function check_dfsan_build {
205
+ local FUZZER=$1
206
+ local ASAN_CALLS=$2
207
+ local DFSAN_CALLS=$3
208
+ local MSAN_CALLS=$4
209
+ local UBSAN_CALLS=$5
210
+
211
+ # Perform all the checks for more detailed error message.
212
+ if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then
213
+ echo "BAD BUILD: DFSan build of $FUZZER seems to be compiled with ASan."
214
+ return 1
215
+ fi
216
+
217
+ if (( $DFSAN_CALLS < $DFSAN_CALLS_THRESHOLD_FOR_DFSAN_BUILD )); then
218
+ echo "BAD BUILD: $FUZZER does not seem to be compiled with DFSan."
219
+ return 1
220
+ fi
221
+
222
+ if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then
223
+ echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with MSan."
224
+ return 1
225
+ fi
226
+
227
+ if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then
228
+ echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with UBSan."
229
+ return 1
230
+ fi
231
+
232
+ return 0
233
+ }
234
+
235
+
236
+ # Mixed sanitizers check for MSan build.
237
+ function check_msan_build {
238
+ local FUZZER=$1
239
+ local ASAN_CALLS=$2
240
+ local DFSAN_CALLS=$3
241
+ local MSAN_CALLS=$4
242
+ local UBSAN_CALLS=$5
243
+
244
+ # Perform all the checks for more detailed error message.
245
+ if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then
246
+ echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with ASan."
247
+ return 1
248
+ fi
249
+
250
+ if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then
251
+ echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with DFSan."
252
+ return 1
253
+ fi
254
+
255
+ if (( $MSAN_CALLS < $MSAN_CALLS_THRESHOLD_FOR_MSAN_BUILD )); then
256
+ echo "BAD BUILD: $FUZZER does not seem to be compiled with MSan."
257
+ return 1
258
+ fi
259
+
260
+ if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then
261
+ echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with UBSan."
262
+ return 1
263
+ fi
264
+
265
+ return 0
266
+ }
267
+
268
+ # Mixed sanitizers check for UBSan build.
269
+ function check_ubsan_build {
270
+ local FUZZER=$1
271
+ local ASAN_CALLS=$2
272
+ local DFSAN_CALLS=$3
273
+ local MSAN_CALLS=$4
274
+ local UBSAN_CALLS=$5
275
+
276
+ if [[ "$FUZZING_ENGINE" != libfuzzer ]]; then
277
+ # Ignore UBSan checks for fuzzing engines other than libFuzzer because:
278
+ # A) we (probably) are not going to use those with UBSan
279
+ # B) such builds show indistinguishable number of calls to UBSan
280
+ return 0
281
+ fi
282
+
283
+ # Perform all the checks for more detailed error message.
284
+ if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then
285
+ echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with ASan."
286
+ return 1
287
+ fi
288
+
289
+ if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then
290
+ echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with DFSan."
291
+ return 1
292
+ fi
293
+
294
+ if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then
295
+ echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with MSan."
296
+ return 1
297
+ fi
298
+
299
+ if (( $UBSAN_CALLS < $UBSAN_CALLS_THRESHOLD_FOR_UBSAN_BUILD )); then
300
+ echo "BAD BUILD: $FUZZER does not seem to be compiled with UBSan."
301
+ return 1
302
+ fi
303
+ }
304
+
305
+ # Verify that the given fuzz target is compiled with correct sanitizer.
306
+ function check_mixed_sanitizers {
307
+ local FUZZER=$1
308
+ local result=0
309
+ local CALL_INSN=
310
+
311
+ if [ "${FUZZING_LANGUAGE:-}" = "jvm" ]; then
312
+ # Sanitizer runtime is linked into the Jazzer driver, so this check does not
313
+ # apply.
314
+ return 0
315
+ fi
316
+
317
+ if [ "${FUZZING_LANGUAGE:-}" = "javascript" ]; then
318
+ # Jazzer.js currently does not support using sanitizers with native Node.js addons.
319
+ # This is not relevant anyways since supporting this will be done by preloading
320
+ # the sanitizers in the wrapper script starting Jazzer.js.
321
+ return 0
322
+ fi
323
+
324
+ if [ "${FUZZING_LANGUAGE:-}" = "python" ]; then
325
+ # Sanitizer runtime is loaded via LD_PRELOAD, so this check does not apply.
326
+ return 0
327
+ fi
328
+
329
+ # For fuzztest fuzzers point to the binary instead of launcher script.
330
+ if [[ $FUZZER == *"@"* ]]; then
331
+ FUZZER=(${FUZZER//@/ }[0])
332
+ fi
333
+
334
+ CALL_INSN=
335
+ if [[ $ARCHITECTURE == "x86_64" ]]
336
+ then
337
+ CALL_INSN="callq?\s+[0-9a-f]+\s+<"
338
+ elif [[ $ARCHITECTURE == "i386" ]]
339
+ then
340
+ CALL_INSN="call\s+[0-9a-f]+\s+<"
341
+ elif [[ $ARCHITECTURE == "aarch64" ]]
342
+ then
343
+ CALL_INSN="bl\s+[0-9a-f]+\s+<"
344
+ else
345
+ echo "UNSUPPORTED ARCHITECTURE"
346
+ exit 1
347
+ fi
348
+ local ASAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__asan" -c)
349
+ local DFSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__dfsan" -c)
350
+ local MSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__msan" -c)
351
+ local UBSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__ubsan" -c)
352
+
353
+
354
+ if [[ "$SANITIZER" = address ]]; then
355
+ check_asan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS
356
+ result=$?
357
+ elif [[ "$SANITIZER" = dataflow ]]; then
358
+ check_dfsan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS
359
+ result=$?
360
+ elif [[ "$SANITIZER" = memory ]]; then
361
+ check_msan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS
362
+ result=$?
363
+ elif [[ "$SANITIZER" = undefined ]]; then
364
+ check_ubsan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS
365
+ result=$?
366
+ elif [[ "$SANITIZER" = thread ]]; then
367
+ # TODO(metzman): Implement this.
368
+ result=0
369
+ fi
370
+
371
+ return $result
372
+ }
373
+
374
+ # Verify that the given fuzz target doesn't crash on the seed corpus.
375
+ function check_seed_corpus {
376
+ local FUZZER=$1
377
+ local FUZZER_NAME="$(basename $FUZZER)"
378
+ local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output"
379
+
380
+ if [[ "$FUZZING_ENGINE" != libfuzzer ]]; then
381
+ return 0
382
+ fi
383
+
384
+ # Set up common fuzzing arguments, otherwise "run_fuzzer" errors out.
385
+ if [ -z "$FUZZER_ARGS" ]; then
386
+ export FUZZER_ARGS="-rss_limit_mb=2560 -timeout=25"
387
+ fi
388
+
389
+ bash -c "run_fuzzer $FUZZER_NAME -runs=0" &> $FUZZER_OUTPUT
390
+
391
+ # Don't output anything if fuzz target hasn't crashed.
392
+ if [ $? -ne 0 ]; then
393
+ echo "BAD BUILD: $FUZZER has a crashing input in its seed corpus:"
394
+ cat $FUZZER_OUTPUT
395
+ return 1
396
+ fi
397
+
398
+ return 0
399
+ }
400
+
401
+ function check_architecture {
402
+ local FUZZER=$1
403
+ local FUZZER_NAME=$(basename $FUZZER)
404
+
405
+ if [ "${FUZZING_LANGUAGE:-}" = "jvm" ]; then
406
+ # The native dependencies of a JVM project are not packaged, but loaded
407
+ # dynamically at runtime and thus cannot be checked here.
408
+ return 0;
409
+ fi
410
+
411
+ if [ "${FUZZING_LANGUAGE:-}" = "javascript" ]; then
412
+ # Jazzer.js fuzzers are wrapper scripts that start the fuzz target with
413
+ # the Jazzer.js CLI.
414
+ return 0;
415
+ fi
416
+
417
+ if [ "${FUZZING_LANGUAGE:-}" = "python" ]; then
418
+ FUZZER=${FUZZER}.pkg
419
+ fi
420
+
421
+ # For fuzztest fuzzers point to the binary instead of launcher script.
422
+ if [[ $FUZZER == *"@"* ]]; then
423
+ FUZZER=(${FUZZER//@/ }[0])
424
+ fi
425
+
426
+ FILE_OUTPUT=$(file $FUZZER)
427
+ if [[ $ARCHITECTURE == "x86_64" ]]
428
+ then
429
+ echo $FILE_OUTPUT | grep "x86-64" > /dev/null
430
+ elif [[ $ARCHITECTURE == "i386" ]]
431
+ then
432
+ echo $FILE_OUTPUT | grep "80386" > /dev/null
433
+ elif [[ $ARCHITECTURE == "aarch64" ]]
434
+ then
435
+ echo $FILE_OUTPUT | grep "aarch64" > /dev/null
436
+ else
437
+ echo "UNSUPPORTED ARCHITECTURE"
438
+ return 1
439
+ fi
440
+ result=$?
441
+ if [[ $result != 0 ]]
442
+ then
443
+ echo "BAD BUILD $FUZZER is not built for architecture: $ARCHITECTURE"
444
+ echo "file command output: $FILE_OUTPUT"
445
+ echo "check_mixed_sanitizers test will fail."
446
+ fi
447
+ return $result
448
+ }
449
+
450
+ function main {
451
+ local FUZZER=$1
452
+ local AUXILIARY_FUZZER=${2:-}
453
+ local checks_failed=0
454
+ local result=0
455
+
456
+ export RUN_FUZZER_MODE="batch"
457
+ check_engine $FUZZER
458
+ result=$?
459
+ checks_failed=$(( $checks_failed + $result ))
460
+
461
+ check_architecture $FUZZER
462
+ result=$?
463
+ checks_failed=$(( $checks_failed + $result ))
464
+
465
+ if [[ "$FUZZING_ENGINE" == centipede \
466
+ && "$SANITIZER" != none && "${HELPER:-}" == True ]]; then
467
+ check_mixed_sanitizers $AUXILIARY_FUZZER
468
+ else
469
+ check_mixed_sanitizers $FUZZER
470
+ fi
471
+ result=$?
472
+ checks_failed=$(( $checks_failed + $result ))
473
+
474
+ check_startup_crash $FUZZER
475
+ result=$?
476
+ checks_failed=$(( $checks_failed + $result ))
477
+
478
+ # TODO: re-enable after introducing bug auto-filing for bad builds.
479
+ # check_seed_corpus $FUZZER
480
+ return $checks_failed
481
+ }
482
+
483
+
484
+ if [ $# -ne 1 -a $# -ne 2 ]; then
485
+ echo "Usage: $0 <fuzz_target_binary> [<auxiliary_binary>]"
486
+ exit 1
487
+ fi
488
+
489
+ # Fuzz target path.
490
+ FUZZER=$1
491
+ AUXILIARY_FUZZER=${2:-}
492
+
493
+ main $FUZZER $AUXILIARY_FUZZER
494
+ exit $?
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_javascript.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ # see installation instructions: https://github.com/nodesource/distributions#available-architectures
18
+ apt-get update
19
+ apt-get install -y ca-certificates curl gnupg
20
+ mkdir -p /etc/apt/keyrings
21
+ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
22
+
23
+ NODE_MAJOR=20
24
+ echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
25
+
26
+ apt-get update
27
+ apt-get install nodejs -y
28
+
29
+ # Install latest versions of nyc for source-based coverage reporting
30
+ npm install --global nyc
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/parse_options.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2020 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Helper script for parsing custom fuzzing options."""
18
+ import configparser
19
+ import sys
20
+
21
+
22
+ def parse_options(options_file_path, options_section):
23
+ """Parses the given file and returns options from the given section."""
24
+ parser = configparser.ConfigParser()
25
+ parser.read(options_file_path)
26
+
27
+ if not parser.has_section(options_section):
28
+ return None
29
+
30
+ options = parser[options_section]
31
+
32
+ if options_section == 'libfuzzer':
33
+ options_string = ' '.join(
34
+ '-%s=%s' % (key, value) for key, value in options.items())
35
+ else:
36
+ # Sanitizer options.
37
+ options_string = ':'.join(
38
+ '%s=%s' % (key, value) for key, value in options.items())
39
+
40
+ return options_string
41
+
42
+
43
+ def main():
44
+ """Processes the arguments and prints the options in the correct format."""
45
+ if len(sys.argv) < 3:
46
+ sys.stderr.write('Usage: %s <path_to_options_file> <options_section>\n' %
47
+ sys.argv[0])
48
+ return 1
49
+
50
+ options = parse_options(sys.argv[1], sys.argv[2])
51
+ if options is not None:
52
+ print(options)
53
+
54
+ return 0
55
+
56
+
57
+ if __name__ == "__main__":
58
+ sys.exit(main())
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_all.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2020 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Does bad_build_check on all fuzz targets in $OUT."""
18
+
19
+ import contextlib
20
+ import multiprocessing
21
+ import os
22
+ import re
23
+ import subprocess
24
+ import stat
25
+ import sys
26
+ import tempfile
27
+
28
+ BASE_TMP_FUZZER_DIR = '/tmp/not-out'
29
+
30
+ EXECUTABLE = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH
31
+
32
+ IGNORED_TARGETS = [
33
+ r'do_stuff_fuzzer', r'checksum_fuzzer', r'fuzz_dump', r'fuzz_keyring',
34
+ r'xmltest', r'fuzz_compression_sas_rle', r'ares_*_fuzzer'
35
+ ]
36
+
37
+ IGNORED_TARGETS_RE = re.compile('^' + r'$|^'.join(IGNORED_TARGETS) + '$')
38
+
39
+
40
+ def move_directory_contents(src_directory, dst_directory):
41
+ """Moves contents of |src_directory| to |dst_directory|."""
42
+ # Use mv because mv preserves file permissions. If we don't preserve file
43
+ # permissions that can mess up CheckFuzzerBuildTest in cifuzz_test.py and
44
+ # other cases where one is calling test_all on files not in OSS-Fuzz's real
45
+ # out directory.
46
+ src_contents = [
47
+ os.path.join(src_directory, filename)
48
+ for filename in os.listdir(src_directory)
49
+ ]
50
+ command = ['mv'] + src_contents + [dst_directory]
51
+ subprocess.check_call(command)
52
+
53
+
54
+ def is_elf(filepath):
55
+ """Returns True if |filepath| is an ELF file."""
56
+ result = subprocess.run(['file', filepath],
57
+ stdout=subprocess.PIPE,
58
+ check=False)
59
+ return b'ELF' in result.stdout
60
+
61
+
62
+ def is_shell_script(filepath):
63
+ """Returns True if |filepath| is a shell script."""
64
+ result = subprocess.run(['file', filepath],
65
+ stdout=subprocess.PIPE,
66
+ check=False)
67
+ return b'shell script' in result.stdout
68
+
69
+
70
+ def find_fuzz_targets(directory):
71
+ """Returns paths to fuzz targets in |directory|."""
72
+ # TODO(https://github.com/google/oss-fuzz/issues/4585): Use libClusterFuzz for
73
+ # this.
74
+ fuzz_targets = []
75
+ for filename in os.listdir(directory):
76
+ path = os.path.join(directory, filename)
77
+ if filename == 'llvm-symbolizer':
78
+ continue
79
+ if filename.startswith('afl-'):
80
+ continue
81
+ if filename.startswith('jazzer_'):
82
+ continue
83
+ if not os.path.isfile(path):
84
+ continue
85
+ if not os.stat(path).st_mode & EXECUTABLE:
86
+ continue
87
+ # Fuzz targets can either be ELF binaries or shell scripts (e.g. wrapper
88
+ # scripts for Python and JVM targets or rules_fuzzing builds with runfiles
89
+ # trees).
90
+ if not is_elf(path) and not is_shell_script(path):
91
+ continue
92
+ if os.getenv('FUZZING_ENGINE') not in {'none', 'wycheproof'}:
93
+ with open(path, 'rb') as file_handle:
94
+ binary_contents = file_handle.read()
95
+ if b'LLVMFuzzerTestOneInput' not in binary_contents:
96
+ continue
97
+ fuzz_targets.append(path)
98
+ return fuzz_targets
99
+
100
+
101
+ def do_bad_build_check(fuzz_target):
102
+ """Runs bad_build_check on |fuzz_target|. Returns a
103
+ Subprocess.ProcessResult."""
104
+ print('INFO: performing bad build checks for', fuzz_target)
105
+ if centipede_needs_auxiliaries():
106
+ print('INFO: Finding Centipede\'s auxiliary for target', fuzz_target)
107
+ auxiliary_path = find_centipede_auxiliary(fuzz_target)
108
+ print('INFO: Using auxiliary binary:', auxiliary_path)
109
+ auxiliary = [auxiliary_path]
110
+ else:
111
+ auxiliary = []
112
+
113
+ command = ['bad_build_check', fuzz_target] + auxiliary
114
+ with tempfile.TemporaryDirectory() as temp_centipede_workdir:
115
+ # Do this so that centipede doesn't fill up the disk during bad build check
116
+ env = os.environ.copy()
117
+ env['CENTIPEDE_WORKDIR'] = temp_centipede_workdir
118
+ return subprocess.run(command,
119
+ stderr=subprocess.PIPE,
120
+ stdout=subprocess.PIPE,
121
+ env=env,
122
+ check=False)
123
+
124
+
125
+ def get_broken_fuzz_targets(bad_build_results, fuzz_targets):
126
+ """Returns a list of broken fuzz targets and their process results in
127
+ |fuzz_targets| where each item in |bad_build_results| is the result of
128
+ bad_build_check on the corresponding element in |fuzz_targets|."""
129
+ broken = []
130
+ for result, fuzz_target in zip(bad_build_results, fuzz_targets):
131
+ if result.returncode != 0:
132
+ broken.append((fuzz_target, result))
133
+ return broken
134
+
135
+
136
+ def has_ignored_targets(out_dir):
137
+ """Returns True if |out_dir| has any fuzz targets we are supposed to ignore
138
+ bad build checks of."""
139
+ out_files = set(os.listdir(out_dir))
140
+ for filename in out_files:
141
+ if re.match(IGNORED_TARGETS_RE, filename):
142
+ return True
143
+ return False
144
+
145
+
146
+ @contextlib.contextmanager
147
+ def use_different_out_dir():
148
+ """Context manager that moves OUT to subdirectory of BASE_TMP_FUZZER_DIR. This
149
+ is useful for catching hardcoding. Note that this sets the environment
150
+ variable OUT and therefore must be run before multiprocessing.Pool is created.
151
+ Resets OUT at the end."""
152
+ # Use a fake OUT directory to catch path hardcoding that breaks on
153
+ # ClusterFuzz.
154
+ initial_out = os.getenv('OUT')
155
+ os.makedirs(BASE_TMP_FUZZER_DIR, exist_ok=True)
156
+ # Use a random subdirectory of BASE_TMP_FUZZER_DIR to allow running multiple
157
+ # instances of test_all in parallel (useful for integration testing).
158
+ with tempfile.TemporaryDirectory(dir=BASE_TMP_FUZZER_DIR) as out:
159
+ # Set this so that run_fuzzer which is called by bad_build_check works
160
+ # properly.
161
+ os.environ['OUT'] = out
162
+ # We move the contents of the directory because we can't move the
163
+ # directory itself because it is a mount.
164
+ move_directory_contents(initial_out, out)
165
+ try:
166
+ yield out
167
+ finally:
168
+ move_directory_contents(out, initial_out)
169
+ os.environ['OUT'] = initial_out
170
+
171
+
172
+ def test_all_outside_out(allowed_broken_targets_percentage):
173
+ """Wrapper around test_all that changes OUT and returns the result."""
174
+ with use_different_out_dir() as out:
175
+ return test_all(out, allowed_broken_targets_percentage)
176
+
177
+
178
+ def centipede_needs_auxiliaries():
179
+ """Checks if auxiliaries are needed for Centipede."""
180
+ # Centipede always requires unsanitized binaries as the main fuzz targets,
181
+ # and separate sanitized binaries as auxiliaries.
182
+ # 1. Building sanitized binaries with helper.py (i.e., local or GitHub CI):
183
+ # Unsanitized ones will be built automatically into the same docker container.
184
+ # Script bad_build_check tests both
185
+ # a) If main fuzz targets can run with the auxiliaries, and
186
+ # b) If the auxiliaries are built with the correct sanitizers.
187
+ # 2. In Trial build and production build:
188
+ # Two kinds of binaries will be in separated buckets / docker containers.
189
+ # Script bad_build_check tests either
190
+ # a) If the unsanitized binaries can run without the sanitized ones, or
191
+ # b) If the sanitized binaries are built with the correct sanitizers.
192
+ return (os.getenv('FUZZING_ENGINE') == 'centipede' and
193
+ os.getenv('SANITIZER') != 'none' and os.getenv('HELPER') == 'True')
194
+
195
+
196
+ def find_centipede_auxiliary(main_fuzz_target_path):
197
+ """Finds the sanitized binary path that corresponds to |main_fuzz_target| for
198
+ bad_build_check."""
199
+ target_dir, target_name = os.path.split(main_fuzz_target_path)
200
+ sanitized_binary_dir = os.path.join(target_dir,
201
+ f'__centipede_{os.getenv("SANITIZER")}')
202
+ sanitized_binary_path = os.path.join(sanitized_binary_dir, target_name)
203
+
204
+ if os.path.isfile(sanitized_binary_path):
205
+ return sanitized_binary_path
206
+
207
+ # Neither of the following two should ever happen, returns None to indicate
208
+ # an error.
209
+ if os.path.isdir(sanitized_binary_dir):
210
+ print('ERROR: Unable to identify Centipede\'s sanitized target'
211
+ f'{sanitized_binary_path} in {os.listdir(sanitized_binary_dir)}')
212
+ else:
213
+ print('ERROR: Unable to identify Centipede\'s sanitized target directory'
214
+ f'{sanitized_binary_dir} in {os.listdir(target_dir)}')
215
+ return None
216
+
217
+
218
+ def test_all(out, allowed_broken_targets_percentage): # pylint: disable=too-many-return-statements
219
+ """Do bad_build_check on all fuzz targets."""
220
+ # TODO(metzman): Refactor so that we can convert test_one to python.
221
+ fuzz_targets = find_fuzz_targets(out)
222
+ if not fuzz_targets:
223
+ print('ERROR: No fuzz targets found.')
224
+ return False
225
+
226
+ if centipede_needs_auxiliaries():
227
+ for fuzz_target in fuzz_targets:
228
+ if not find_centipede_auxiliary(fuzz_target):
229
+ print(f'ERROR: Couldn\'t find auxiliary for {fuzz_target}.')
230
+ return False
231
+
232
+ pool = multiprocessing.Pool()
233
+ bad_build_results = pool.map(do_bad_build_check, fuzz_targets)
234
+ pool.close()
235
+ pool.join()
236
+ broken_targets = get_broken_fuzz_targets(bad_build_results, fuzz_targets)
237
+ broken_targets_count = len(broken_targets)
238
+ if not broken_targets_count:
239
+ return True
240
+
241
+ print('Retrying failed fuzz targets sequentially', broken_targets_count)
242
+ pool = multiprocessing.Pool(1)
243
+ retry_targets = []
244
+ for broken_target, result in broken_targets:
245
+ retry_targets.append(broken_target)
246
+ bad_build_results = pool.map(do_bad_build_check, retry_targets)
247
+ pool.close()
248
+ pool.join()
249
+ broken_targets = get_broken_fuzz_targets(bad_build_results, broken_targets)
250
+ broken_targets_count = len(broken_targets)
251
+ if not broken_targets_count:
252
+ return True
253
+
254
+ print('Broken fuzz targets', broken_targets_count)
255
+ total_targets_count = len(fuzz_targets)
256
+ broken_targets_percentage = 100 * broken_targets_count / total_targets_count
257
+ for broken_target, result in broken_targets:
258
+ print(broken_target)
259
+ # Use write because we can't print binary strings.
260
+ sys.stdout.buffer.write(result.stdout + result.stderr + b'\n')
261
+
262
+ if broken_targets_percentage > allowed_broken_targets_percentage:
263
+ print('ERROR: {broken_targets_percentage}% of fuzz targets seem to be '
264
+ 'broken. See the list above for a detailed information.'.format(
265
+ broken_targets_percentage=broken_targets_percentage))
266
+ if has_ignored_targets(out):
267
+ print('Build check automatically passing because of ignored targets.')
268
+ return True
269
+ return False
270
+ print('{total_targets_count} fuzzers total, {broken_targets_count} '
271
+ 'seem to be broken ({broken_targets_percentage}%).'.format(
272
+ total_targets_count=total_targets_count,
273
+ broken_targets_count=broken_targets_count,
274
+ broken_targets_percentage=broken_targets_percentage))
275
+ return True
276
+
277
+
278
+ def get_allowed_broken_targets_percentage():
279
+ """Returns the value of the environment value
280
+ 'ALLOWED_BROKEN_TARGETS_PERCENTAGE' as an int or returns a reasonable
281
+ default."""
282
+ return int(os.getenv('ALLOWED_BROKEN_TARGETS_PERCENTAGE') or '10')
283
+
284
+
285
+ def main():
286
+ """Does bad_build_check on all fuzz targets in parallel. Returns 0 on success.
287
+ Returns 1 on failure."""
288
+ allowed_broken_targets_percentage = get_allowed_broken_targets_percentage()
289
+ if not test_all_outside_out(allowed_broken_targets_percentage):
290
+ return 1
291
+ return 0
292
+
293
+
294
+ if __name__ == '__main__':
295
+ sys.exit(main())
local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_all_test.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ """Tests test_all.py"""
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import test_all
21
+
22
+
23
+ class TestTestAll(unittest.TestCase):
24
+ """Tests for the test_all_function."""
25
+
26
+ @mock.patch('test_all.find_fuzz_targets', return_value=[])
27
+ @mock.patch('builtins.print')
28
+ def test_test_all_no_fuzz_targets(self, mock_print, _):
29
+ """Tests that test_all returns False when there are no fuzz targets."""
30
+ outdir = '/out'
31
+ allowed_broken_targets_percentage = 0
32
+ self.assertFalse(
33
+ test_all.test_all(outdir, allowed_broken_targets_percentage))
34
+ mock_print.assert_called_with('ERROR: No fuzz targets found.')
35
+
36
+
37
+ if __name__ == '__main__':
38
+ unittest.main()