• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/bin/bash -eu
2#
3# Copyright 2021 Google LLC
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17################################################################################
18
19: "${BAZEL_FUZZ_TEST_TAG:=fuzz-test}"
20: "${BAZEL_FUZZ_TEST_EXCLUDE_TAG:=no-oss-fuzz}"
21: "${BAZEL_PACKAGE_SUFFIX:=_oss_fuzz}"
22: "${BAZEL_TOOL:=bazel}"
23: "${BAZEL_EXTRA_BUILD_FLAGS:=}"
24
25if [[ -z "${BAZEL_FUZZ_TEST_QUERY:-}" ]]; then
26    BAZEL_FUZZ_TEST_QUERY="
27        let all_fuzz_tests = attr(tags, \"${BAZEL_FUZZ_TEST_TAG}\", \"//...\") in
28        \$all_fuzz_tests - attr(tags, \"${BAZEL_FUZZ_TEST_EXCLUDE_TAG}\", \$all_fuzz_tests)
29    "
30fi
31
32echo "Using Bazel query to find fuzz targets: ${BAZEL_FUZZ_TEST_QUERY}"
33
34declare -r OSS_FUZZ_TESTS=(
35    $(bazel query "${BAZEL_FUZZ_TEST_QUERY}" | sed "s/$/${BAZEL_PACKAGE_SUFFIX}/")
36)
37
38echo "Found ${#OSS_FUZZ_TESTS[@]} fuzz test packages:"
39for oss_fuzz_test in "${OSS_FUZZ_TESTS[@]}"; do
40    echo "  ${oss_fuzz_test}"
41done
42
43declare -r BAZEL_BUILD_FLAGS=(
44    "-c" "opt"
45    "--//fuzzing:cc_engine=@rules_fuzzing_oss_fuzz//:oss_fuzz_engine" \
46    "--@rules_fuzzing//fuzzing:cc_engine_instrumentation=oss-fuzz" \
47    "--@rules_fuzzing//fuzzing:cc_engine_sanitizer=none" \
48    "--linkopt=-lc++" \
49    "--action_env=CC=${CC}" "--action_env=CXX=${CXX}" \
50    ${BAZEL_EXTRA_BUILD_FLAGS[*]}
51)
52
53echo "Building the fuzz tests with the following Bazel options:"
54echo "  ${BAZEL_BUILD_FLAGS[@]}"
55
56${BAZEL_TOOL} build "${BAZEL_BUILD_FLAGS[@]}" "${OSS_FUZZ_TESTS[@]}"
57
58echo "Extracting the fuzz test packages in the output directory."
59for oss_fuzz_archive in $(find bazel-bin/ -name "*${BAZEL_PACKAGE_SUFFIX}.tar"); do
60    tar -xvf "${oss_fuzz_archive}" -C "${OUT}"
61done
62
63if [ "$SANITIZER" = "coverage" ]; then
64    echo "Collecting the repository source files for coverage tracking."
65    declare -r COVERAGE_SOURCES="${OUT}/proc/self/cwd"
66    mkdir -p "${COVERAGE_SOURCES}"
67    declare -r RSYNC_FILTER_ARGS=(
68        "--include" "*.h"
69        "--include" "*.cc"
70        "--include" "*.hpp"
71        "--include" "*.cpp"
72        "--include" "*.c"
73        "--include" "*.inc"
74        "--include" "*/"
75        "--exclude" "*"
76    )
77    rsync -avLk "${RSYNC_FILTER_ARGS[@]}" \
78        "$(bazel info execution_root)/" \
79        "${COVERAGE_SOURCES}/"
80fi
81