diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..580cd305b56be53270602277b76a21ea664e84b4 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile @@ -0,0 +1,26 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +# Copy/Run this now to make the cache more resilient. +COPY fuzzbench_install_dependencies /usr/local/bin +RUN fuzzbench_install_dependencies + +ENV OSS_FUZZ_ON_DEMAND=1 + +COPY fuzzbench_build fuzzbench_run_fuzzer fuzzbench_measure /usr/local/bin/ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_build b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_build new file mode 100644 index 0000000000000000000000000000000000000000..7231fe755ff0c02f9ff6dba1e5235505095e7aa6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_build @@ -0,0 +1,28 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# TODO(metzman): Do this in a docket image so we don't need to waste time +# reinstalling. +PYTHONPATH=$FUZZBENCH_PATH python3 -B -u -c "from fuzzers.$FUZZING_ENGINE import fuzzer; fuzzer.build()" + +if [ "$FUZZING_ENGINE" = "coverage" ]; then + cd $OUT + mkdir -p filestore/oss-fuzz-on-demand/coverage-binaries + # We expect an error regarding leading slashes. Just assume this step succeeds. + # TODO(metzman): Fix this when I get a chance. + tar -czvf filestore/oss-fuzz-on-demand/coverage-binaries/coverage-build-$PROJECT.tar.gz * /src /work || exit 0 +fi diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies new file mode 100644 index 0000000000000000000000000000000000000000..94c0b8764805a90e348eed66d70816c723e42297 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies @@ -0,0 +1,22 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +apt-get update && apt-get install -y gcc gfortran python-dev libopenblas-dev liblapack-dev cython libpq-dev +wget -O /tmp/requirements.txt https://raw.githubusercontent.com/google/fuzzbench/master/requirements.txt +pip3 install pip --upgrade +CFLAGS= CXXFLAGS= pip3 install -r /tmp/requirements.txt +rm /tmp/requirements.txt diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure new file mode 100644 index 0000000000000000000000000000000000000000..ba9a413a0b59557a4e8d029aa413967bd700041c --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure @@ -0,0 +1,32 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# TODO(metzman): Make these configurable. +export DB_PATH=$OUT/experiment.db +export SNAPSHOT_PERIOD=30 +export EXPERIMENT_FILESTORE=$OUT/filestore +export MAX_TOTAL_TIME=120 +export EXPERIMENT=oss-fuzz-on-demand + +rm -f $DB_PATH + +# FUZZER=mopt BENCHMARK=skcms + +export SQL_DATABASE_URL=sqlite:///$DB_PATH + +cd $FUZZBENCH_PATH +PYTHONPATH=. python3 -B experiment/measurer/standalone.py $MAX_TOTAL_TIME diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..008fdbb05cc390c3af022c6d2204a3014abcc8b9 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer @@ -0,0 +1,41 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +export RUNNER_NICENESS="-5" +export EXPERIMENT_FILESTORE=$OUT/filestore +export EXPERIMENT=oss-fuzz-on-demand +export OSS_FUZZ_ON_DEMAND=1 +export OUTPUT_CORPUS_DIR=/output-corpus +export SEED_CORPUS_DIR=/input-corpus +mkdir $SEED_CORPUS_DIR +rm -rf $OUTPUT_CORPUS_DIR +mkdir $OUTPUT_CORPUS_DIR +export FUZZER=$FUZZING_ENGINE +# TODO(metzman): Make this configurable. +export MAX_TOTAL_TIME=120 +export SNAPSHOT_PERIOD=30 +export TRIAL_ID=1 +export FORCE_LOCAL=1 + +# BENCHMARK, FUZZ_TARGET +cd $OUT + +# Prevent permissions issues with pyc files and docker. +cp -r $FUZZBENCH_PATH /tmp/fuzzbench + +PYTHONPATH=/tmp/fuzzbench nice -n $RUNNER_NICENESS python3 -B -u /tmp/fuzzbench/experiment/runner.py +cat $EXPERIMENT_FILESTORE/$EXPERIMENT/experiment-folders/$BENCHMARK-$FUZZER/trial-$TRIAL_ID/results/fuzzer-log.txt diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89333395375de51f083062a9c0c9d9985e8296f2 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/Dockerfile @@ -0,0 +1,33 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +# Set up Golang environment variables (copied from /root/.bash_profile). +ENV GOPATH /root/go + +# /root/.go/bin is for the standard Go binaries (i.e. go, gofmt, etc). +# $GOPATH/bin is for the binaries from the dependencies installed via "go get". +ENV PATH $PATH:/root/.go/bin:$GOPATH/bin + +COPY gosigfuzz.c $GOPATH/gosigfuzz/ + +RUN install_go.sh + +# TODO(jonathanmetzman): Install this file using install_go.sh. +COPY ossfuzz_coverage_runner.go \ + $GOPATH/ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c new file mode 100644 index 0000000000000000000000000000000000000000..d613ce64b78fcbce7180f48587ac5f8085ae402f --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c @@ -0,0 +1,47 @@ +/* + * Copyright 2023 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include +#include + +static void fixSignalHandler(int signum) { + struct sigaction new_action; + struct sigaction old_action; + sigemptyset (&new_action.sa_mask); + sigaction (signum, NULL, &old_action); + new_action.sa_flags = old_action.sa_flags | SA_ONSTACK; + new_action.sa_sigaction = old_action.sa_sigaction; + new_action.sa_handler = old_action.sa_handler; + sigaction (signum, &new_action, NULL); +} + +static void FixStackSignalHandler() { + fixSignalHandler(SIGSEGV); + fixSignalHandler(SIGABRT); + fixSignalHandler(SIGALRM); + fixSignalHandler(SIGINT); + fixSignalHandler(SIGTERM); + fixSignalHandler(SIGBUS); + fixSignalHandler(SIGFPE); + fixSignalHandler(SIGXFSZ); + fixSignalHandler(SIGUSR1); + fixSignalHandler(SIGUSR2); +} + +int LLVMFuzzerInitialize(int *argc, char ***argv) { + FixStackSignalHandler(); + return 0; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/ossfuzz_coverage_runner.go b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/ossfuzz_coverage_runner.go new file mode 100644 index 0000000000000000000000000000000000000000..ab2504888105835a80f6c0d1c0192bd724e2d52e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-go/ossfuzz_coverage_runner.go @@ -0,0 +1,80 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mypackagebeingfuzzed + +import ( + "io/fs" + "io/ioutil" + "os" + "path/filepath" + "runtime/pprof" + "testing" +) + +func TestFuzzCorpus(t *testing.T) { + dir := os.Getenv("FUZZ_CORPUS_DIR") + if dir == "" { + t.Logf("No fuzzing corpus directory set") + return + } + filename := "" + defer func() { + if r := recover(); r != nil { + t.Error("Fuzz panicked in "+filename, r) + } + }() + profname := os.Getenv("FUZZ_PROFILE_NAME") + if profname != "" { + f, err := os.Create(profname + ".cpu.prof") + if err != nil { + t.Logf("error creating profile file %s\n", err) + } else { + _ = pprof.StartCPUProfile(f) + } + } + _, err := ioutil.ReadDir(dir) + if err != nil { + t.Logf("Not fuzzing corpus directory %s", err) + return + } + // recurse for regressions subdirectory + err = filepath.Walk(dir, func(fname string, info fs.FileInfo, err error) error { + if info.IsDir() { + return nil + } + data, err := ioutil.ReadFile(fname) + if err != nil { + t.Error("Failed to read corpus file", err) + return err + } + filename = fname + FuzzFunction(data) + return nil + }) + if err != nil { + t.Error("Failed to run corpus", err) + } + if profname != "" { + pprof.StopCPUProfile() + f, err := os.Create(profname + ".heap.prof") + if err != nil { + t.Logf("error creating heap profile file %s\n", err) + } + if err = pprof.WriteHeapProfile(f); err != nil { + t.Logf("error writing heap profile file %s\n", err) + } + f.Close() + } +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e558984c194daff35064cba3c5118c76f3e5c582 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile @@ -0,0 +1,22 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +RUN install_swift.sh + +COPY precompile_swift /usr/local/bin/ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift new file mode 100644 index 0000000000000000000000000000000000000000..ab855a620191656e572d6a68a869e26f020b0dc5 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift @@ -0,0 +1,33 @@ +#!/bin/bash -eu +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +cp /usr/local/bin/llvm-symbolizer-swift $OUT/llvm-symbolizer + +export SWIFTFLAGS="-Xswiftc -parse-as-library -Xswiftc -static-stdlib --static-swift-stdlib" +if [ "$SANITIZER" = "coverage" ] +then + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -profile-generate -Xswiftc -profile-coverage-mapping -Xswiftc -sanitize=fuzzer" +else + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -sanitize=fuzzer,$SANITIZER --sanitize=$SANITIZER" + for f in $CFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcc=$f" + done + + for f in $CXXFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcxx=$f" + done +fi diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile new file mode 100644 index 0000000000000000000000000000000000000000..8aa6580bc3d393ca5b75499c5fc0064bed1ee80f --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile @@ -0,0 +1,420 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "---------------------------------------------------------------" + +sysctl -w vm.mmap_rnd_bits=28 + +OSS_FUZZ_ON_DEMAND="${OSS_FUZZ_ON_DEMAND:-0}" + +# Used for Rust introspector builds +RUST_SANITIZER=$SANITIZER + +if [ "$FUZZING_LANGUAGE" = "jvm" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ] && [ "$FUZZING_ENGINE" != "wycheproof" ]; then + echo "ERROR: JVM projects can be fuzzed with libFuzzer or tested with wycheproof engines only." + exit 1 + fi + if [ "$SANITIZER" != "address" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "none" ] && [ "$SANITIZER" != "introspector" ]; then + echo "ERROR: JVM projects can be fuzzed with AddressSanitizer or UndefinedBehaviorSanitizer or Introspector only." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: JVM projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ "$FUZZING_LANGUAGE" = "rust" ]; then + if [ "$SANITIZER" = "introspector" ]; then + # introspector sanitizer flag will cause cargo build to fail. Rremove it + # temporarily, RUST_SANITIZER will hold the original sanitizer. + export SANITIZER=address + fi +fi + + +if [ "$FUZZING_LANGUAGE" = "javascript" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ]; then + echo "ERROR: JavaScript projects can be fuzzed with libFuzzer engine only." + exit 1 + fi + if [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "none" ]; then + echo "ERROR: JavaScript projects cannot be fuzzed with sanitizers." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: JavaScript projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ "$FUZZING_LANGUAGE" = "python" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ]; then + echo "ERROR: Python projects can be fuzzed with libFuzzer engine only." + exit 1 + fi + if [ "$SANITIZER" != "address" ] && [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "introspector" ]; then + echo "ERROR: Python projects can be fuzzed with AddressSanitizer or UndefinedBehaviorSanitizer or Coverage or Fuzz Introspector only." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: Python projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ -z "${SANITIZER_FLAGS-}" ]; then + FLAGS_VAR="SANITIZER_FLAGS_${SANITIZER}" + export SANITIZER_FLAGS=${!FLAGS_VAR-} +fi + +if [[ $ARCHITECTURE == "i386" ]]; then + export CFLAGS="-m32 $CFLAGS" + cp -R /usr/i386/lib/* /usr/local/lib + cp -R /usr/i386/include/* /usr/local/include +fi + +# Don't use a fuzzing engine with Jazzer which has libFuzzer built-in or with +# FuzzBench which will provide the fuzzing engine. +if [[ $FUZZING_ENGINE != "none" ]] && [[ $FUZZING_LANGUAGE != "jvm" ]] && [[ "${OSS_FUZZ_ON_DEMAND}" == "0" ]] ; then + # compile script might override environment, use . to call it. + . compile_${FUZZING_ENGINE} +fi + +if [[ $SANITIZER_FLAGS = *sanitize=memory* ]] +then + # Take all libraries from lib/msan + # export CXXFLAGS_EXTRA="-L/usr/msan/lib $CXXFLAGS_EXTRA" + cp -R /usr/msan/lib/* /usr/local/lib/x86_64-unknown-linux-gnu/ + cp -R /usr/msan/include/* /usr/local/include + + echo 'Building without MSan instrumented libraries.' +fi + +# Coverage flag overrides. +COVERAGE_FLAGS_VAR="COVERAGE_FLAGS_${SANITIZER}" +if [[ -n ${!COVERAGE_FLAGS_VAR+x} ]] +then + export COVERAGE_FLAGS="${!COVERAGE_FLAGS_VAR}" +fi + +# Only need the default coverage instrumentation for libFuzzer or honggfuzz. +# Other engines bring their own. +if [ $FUZZING_ENGINE = "none" ] || [ $FUZZING_ENGINE = "afl" ] || [ $FUZZING_ENGINE = "centipede" ] || [ "${OSS_FUZZ_ON_DEMAND}" != "0" ]; then + export COVERAGE_FLAGS= +fi + +# Rust does not support sanitizers and coverage flags via CFLAGS/CXXFLAGS, so +# use RUSTFLAGS. +# FIXME: Support code coverage once support is in. +# See https://github.com/rust-lang/rust/issues/34701. +if [ "$RUST_SANITIZER" == "introspector" ]; then + export RUSTFLAGS="-Cdebuginfo=2 -Cforce-frame-pointers" +elif [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "none" ] && [ "$ARCHITECTURE" != 'i386' ]; then + export RUSTFLAGS="--cfg fuzzing -Zsanitizer=${SANITIZER} -Cdebuginfo=1 -Cforce-frame-pointers" +else + export RUSTFLAGS="--cfg fuzzing -Cdebuginfo=1 -Cforce-frame-pointers" +fi +if [ "$SANITIZER" = "coverage" ] +then + # link to C++ from comment in f5098035eb1a14aa966c8651d88ea3d64323823d + export RUSTFLAGS="$RUSTFLAGS -Cinstrument-coverage -C link-arg=-lc++" +fi + +# Add Rust libfuzzer flags. +# See https://github.com/rust-fuzz/libfuzzer/blob/master/build.rs#L12. +export CUSTOM_LIBFUZZER_PATH="$LIB_FUZZING_ENGINE_DEPRECATED" +export CUSTOM_LIBFUZZER_STD_CXX=c++ + +export CFLAGS="$CFLAGS $SANITIZER_FLAGS $COVERAGE_FLAGS" +export CXXFLAGS="$CFLAGS $CXXFLAGS_EXTRA" + +if [ "$SANITIZER" = "undefined" ]; then + # Disable "function" sanitizer for C code for now, because many projects, + # possibly via legacy C code are affected. + # The projects should be fixed and this workaround be removed in the future. + # TODO(#11778): + # https://github.com/google/oss-fuzz/issues/11778 + export CFLAGS="$CFLAGS -fno-sanitize=function" +fi + +if [ "$FUZZING_LANGUAGE" = "go" ]; then + # required by Go 1.20 + export CXX="${CXX} -lresolv" +fi + +if [ "$FUZZING_LANGUAGE" = "python" ]; then + sanitizer_with_fuzzer_lib_dir=`python3 -c "import atheris; import os; print(atheris.path())"` + sanitizer_with_fuzzer_output_lib=$OUT/sanitizer_with_fuzzer.so + if [ "$SANITIZER" = "address" ]; then + cp $sanitizer_with_fuzzer_lib_dir/asan_with_fuzzer.so $sanitizer_with_fuzzer_output_lib + elif [ "$SANITIZER" = "undefined" ]; then + cp $sanitizer_with_fuzzer_lib_dir/ubsan_with_fuzzer.so $sanitizer_with_fuzzer_output_lib + fi + + # Disable leak checking as it is unsupported. + export CFLAGS="$CFLAGS -fno-sanitize=function,leak,vptr," + export CXXFLAGS="$CXXFLAGS -fno-sanitize=function,leak,vptr" +fi + +# Copy latest llvm-symbolizer in $OUT for stack symbolization. +cp $(which llvm-symbolizer) $OUT/ + +# Copy Jazzer to $OUT if needed. +if [ "$FUZZING_LANGUAGE" = "jvm" ]; then + cp $(which jazzer_agent_deploy.jar) $(which jazzer_driver) $(which jazzer_junit.jar) $OUT/ + jazzer_driver_with_sanitizer=$OUT/jazzer_driver_with_sanitizer + if [ "$SANITIZER" = "address" ]; then + cat > $jazzer_driver_with_sanitizer << 'EOF' +#!/bin/bash +this_dir=$(dirname "$0") +"$this_dir/jazzer_driver" --asan "$@" +EOF + elif [ "$SANITIZER" = "undefined" ]; then + cat > $jazzer_driver_with_sanitizer << 'EOF' +#!/bin/bash +this_dir=$(dirname "$0") +"$this_dir/jazzer_driver" --ubsan "$@" +EOF + elif [ "$SANITIZER" = "coverage" ] || [ "$SANITIZER" = "introspector" ]; then + # Coverage & introspector builds require no instrumentation. + cp $(which jazzer_driver) $jazzer_driver_with_sanitizer + fi + chmod +x $jazzer_driver_with_sanitizer + + # Disable leak checking since the JVM triggers too many false positives. + export CFLAGS="$CFLAGS -fno-sanitize=leak" + export CXXFLAGS="$CXXFLAGS -fno-sanitize=leak" +fi + +if [ "$SANITIZER" = "introspector" ] || [ "$RUST_SANITIZER" = "introspector" ]; then + export AR=llvm-ar + export NM=llvm-nm + export RANLIB=llvm-ranlib + + export CFLAGS="$CFLAGS -g" + export CXXFLAGS="$CXXFLAGS -g" + export FI_BRANCH_PROFILE=1 + export FUZZ_INTROSPECTOR=1 + export FUZZ_INTROSPECTOR_AUTO_FUZZ=1 + + # Move ar and ranlib + mv /usr/bin/ar /usr/bin/old-ar + mv /usr/bin/nm /usr/bin/old-nm + mv /usr/bin/ranlib /usr/bin/old-ranlib + + ln -sf /usr/local/bin/llvm-ar /usr/bin/ar + ln -sf /usr/local/bin/llvm-nm /usr/bin/nm + ln -sf /usr/local/bin/llvm-ranlib /usr/bin/ranlib + + apt-get install -y libjpeg-dev zlib1g-dev libyaml-dev + python3 -m pip install --upgrade pip setuptools + python3 -m pip install cxxfilt pyyaml beautifulsoup4 lxml soupsieve rust-demangler + python3 -m pip install --prefer-binary matplotlib + + # Install Fuzz-Introspector + pushd /fuzz-introspector/src + python3 -m pip install -e . + popd + + if [ "$FUZZING_LANGUAGE" = "python" ]; then + python3 /fuzz-introspector/src/main.py light --language=python + cp -rf $SRC/inspector/ /tmp/inspector-saved + elif [ "$FUZZING_LANGUAGE" = "jvm" ]; then + python3 /fuzz-introspector/src/main.py light --language=jvm + cp -rf $SRC/inspector/ /tmp/inspector-saved + elif [ "$FUZZING_LANGUAGE" = "rust" ]; then + python3 /fuzz-introspector/src/main.py light --language=rust + cp -rf $SRC/inspector/ /tmp/inspector-saved + else + python3 /fuzz-introspector/src/main.py light + + # Make a copy of the light. This is needed because we run two versions of + # introspector: one based on pure statis analysis and one based on + # regular LTO. + cp -rf $SRC/inspector/ /tmp/inspector-saved + + + # Move coverage report. + if [ -d "$OUT/textcov_reports" ] + then + find $OUT/textcov_reports/ -name "*.covreport" -exec cp {} $SRC/inspector/ \; + find $OUT/textcov_reports/ -name "*.json" -exec cp {} $SRC/inspector/ \; + fi + + # Make fuzz-introspector HTML report using light approach. + REPORT_ARGS="--name=$PROJECT_NAME" + + # Only pass coverage_url when COVERAGE_URL is set (in cloud builds) + if [[ ! -z "${COVERAGE_URL+x}" ]]; then + REPORT_ARGS="$REPORT_ARGS --coverage-url=${COVERAGE_URL}" + fi + + # Run pure static analysis fuzz introspector + fuzz-introspector full --target-dir=$SRC \ + --language=${FUZZING_LANGUAGE} \ + --out-dir=$SRC/inspector \ + ${REPORT_ARGS} + fi + + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" +fi + +echo "---------------------------------------------------------------" +echo "CC=$CC" +echo "CXX=$CXX" +echo "CFLAGS=$CFLAGS" +echo "CXXFLAGS=$CXXFLAGS" +echo "RUSTFLAGS=$RUSTFLAGS" +echo "---------------------------------------------------------------" + +if [ "${OSS_FUZZ_ON_DEMAND}" != "0" ]; then + fuzzbench_build + cp $(which llvm-symbolizer) $OUT/ + exit 0 +fi + + +if [[ ! -z "${CAPTURE_REPLAY_SCRIPT-}" ]]; then + # Capture a replaying build script which can be used for replaying the build + # after a vanilla build. This script is meant to be used in a cached + # container. + python3 -m pip install bashlex + python3 /usr/local/bin/bash_parser.py $SRC/build.sh +fi + +# Prepare the build command to run the project's build script. +if [[ ! -z "${REPLAY_ENABLED-}" ]]; then + # If this is a replay, then use replay_build.sh. This is expected to be + # running in a cached container where a build has already happened prior. + BUILD_CMD="bash -eux $SRC/replay_build.sh" +else + BUILD_CMD="bash -eux $SRC/build.sh" +fi + +# Set +u temporarily to continue even if GOPATH and OSSFUZZ_RUSTPATH are undefined. +set +u +# We need to preserve source code files for generating a code coverage report. +# We need exact files that were compiled, so copy both $SRC and $WORK dirs. +COPY_SOURCES_CMD="cp -rL --parents $SRC $WORK /usr/include /usr/local/include $GOPATH $OSSFUZZ_RUSTPATH /rustc $OUT" +set -u + +if [ "$FUZZING_LANGUAGE" = "rust" ]; then + # Copy rust std lib to its path with a hash. + export rustch=`rustc --version --verbose | grep commit-hash | cut -d' ' -f2` + mkdir -p /rustc/$rustch/ + export rustdef=`rustup toolchain list | grep default | cut -d' ' -f1` + cp -r /rust/rustup/toolchains/$rustdef/lib/rustlib/src/rust/library/ /rustc/$rustch/ +fi + +if [ "${BUILD_UID-0}" -ne "0" ]; then + adduser -u $BUILD_UID --disabled-password --gecos '' builder + chown -R builder $SRC $OUT $WORK + su -c "$BUILD_CMD" builder + if [ "$SANITIZER" = "coverage" ]; then + # Some directories have broken symlinks (e.g. honggfuzz), ignore the errors. + su -c "$COPY_SOURCES_CMD" builder 2>/dev/null || true + fi +else + $BUILD_CMD + if [ "$SANITIZER" = "coverage" ]; then + # Some directories have broken symlinks (e.g. honggfuzz), ignore the errors. + $COPY_SOURCES_CMD 2>/dev/null || true + fi +fi + +if [ "$SANITIZER" = "introspector" ] || [ "$RUST_SANITIZER" = "introspector" ]; then + unset CXXFLAGS + unset CFLAGS + export G_ANALYTICS_TAG="G-8WTFM1Y62J" + + # If we get to here, it means the e.g. LTO had no problems and succeeded. + # TO this end, we wlil restore the original light analysis and used the + # LTO processing itself. + rm -rf $SRC/inspector + cp -rf /tmp/inspector-saved $SRC/inspector + + cd /fuzz-introspector/src + python3 -m pip install -e . + cd /src/ + + if [ "$FUZZING_LANGUAGE" = "rust" ]; then + # Restore the sanitizer flag for rust + export SANITIZER="introspector" + fi + + mkdir -p $SRC/inspector + find $SRC/ -name "fuzzerLogFile-*.data" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "fuzzerLogFile-*.data.yaml" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "fuzzerLogFile-*.data.debug_*" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "allFunctionsWithMain-*.yaml" -exec cp {} $SRC/inspector/ \; + + # Move coverage report. + if [ -d "$OUT/textcov_reports" ] + then + find $OUT/textcov_reports/ -name "*.covreport" -exec cp {} $SRC/inspector/ \; + find $OUT/textcov_reports/ -name "*.json" -exec cp {} $SRC/inspector/ \; + fi + + cd $SRC/inspector + + # Make fuzz-introspector HTML report. + REPORT_ARGS="--name=$PROJECT_NAME" + # Only pass coverage_url when COVERAGE_URL is set (in cloud builds) + if [[ ! -z "${COVERAGE_URL+x}" ]]; then + REPORT_ARGS="$REPORT_ARGS --coverage-url=${COVERAGE_URL}" + fi + + # Do different things depending on languages + if [ "$FUZZING_LANGUAGE" = "python" ]; then + echo "GOING python route" + set -x + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=python" + fuzz-introspector report $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + elif [ "$FUZZING_LANGUAGE" = "jvm" ]; then + echo "GOING jvm route" + set -x + find $OUT/ -name "jacoco.xml" -exec cp {} $SRC/inspector/ \; + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC --out-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=jvm" + fuzz-introspector full $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + elif [ "$FUZZING_LANGUAGE" = "rust" ]; then + echo "GOING rust route" + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC --out-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=rust" + fuzz-introspector full $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + else + # C/C++ + mkdir -p $SRC/inspector + # Correlate fuzzer binaries to fuzz-introspector's raw data + fuzz-introspector correlate --binaries-dir=$OUT/ + + # Generate fuzz-introspector HTML report, this generates + # the file exe_to_fuzz_introspector_logs.yaml + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC/inspector" + # Use the just-generated correlation file + REPORT_ARGS="$REPORT_ARGS --correlation-file=exe_to_fuzz_introspector_logs.yaml" + fuzz-introspector report $REPORT_ARGS + + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + fi +fi diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_afl b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_afl new file mode 100644 index 0000000000000000000000000000000000000000..484d4668c86648d042081a8a1e254dd6a5c36256 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_afl @@ -0,0 +1,53 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# If LLVM once again does weird changes then enable this: +#export AFL_LLVM_INSTRUMENT=LLVM-NATIVE + +# AFL++ setup +echo "Copying precompiled AFL++" + +# Copy AFL++ tools necessary for fuzzing. +pushd $SRC/aflplusplus > /dev/null + +cp -f libAFLDriver.a $LIB_FUZZING_ENGINE + +# Some important projects include libraries, copy those even when they don't +# start with "afl-". Use "sort -u" to avoid a warning about duplicates. +ls afl-* *.txt *.a *.o *.so | sort -u | xargs cp -t $OUT +export CC="$SRC/aflplusplus/afl-clang-fast" +export CXX="$SRC/aflplusplus/afl-clang-fast++" + +# Set sane AFL++ environment defaults: +# Be quiet, otherwise this can break some builds. +export AFL_QUIET=1 +# No leak errors during builds. +export ASAN_OPTIONS="detect_leaks=0:symbolize=0:detect_odr_violation=0:abort_on_error=1" +# Do not abort on any problems (because this is during build where it is ok) +export AFL_IGNORE_PROBLEMS=1 +# No complain on unknown AFL environment variables +export AFL_IGNORE_UNKNOWN_ENVS=1 + +# Provide a way to document the AFL++ options used in this build: +echo +echo AFL++ target compilation setup: +env | egrep '^AFL_' | tee "$OUT/afl_options.txt" +echo + +popd > /dev/null + +echo " done." diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..df7d3e24d23c1caf7e262040021fa04240efa8bb --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer @@ -0,0 +1,69 @@ +#!/bin/bash -eu +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +path=$1 +function=$2 +fuzzer=$3 +tags="-tags gofuzz" +if [[ $# -eq 4 ]]; then + tags="-tags $4" +fi + +# makes directory change temporary +( +cd $GOPATH/src/$path || true +# in the case we are in the right directory, with go.mod but no go.sum +go mod tidy || true +# project was downloaded with go get if go list fails +go list $tags $path || { cd $GOPATH/pkg/mod/ && cd `echo $path | cut -d/ -f1-3 | awk '{print $1"@*"}'`; } || cd - +# project does not have go.mod if go list fails again +go list $tags $path || { go mod init $path && go mod tidy ;} + +if [[ $SANITIZER = *coverage* ]]; then + fuzzed_package=`go list $tags -f '{{.Name}}' $path` + abspath=`go list $tags -f {{.Dir}} $path` + cd $abspath + cp $GOPATH/ossfuzz_coverage_runner.go ./"${function,,}"_test.go + sed -i -e 's/FuzzFunction/'$function'/' ./"${function,,}"_test.go + sed -i -e 's/mypackagebeingfuzzed/'$fuzzed_package'/' ./"${function,,}"_test.go + sed -i -e 's/TestFuzzCorpus/Test'$function'Corpus/' ./"${function,,}"_test.go + + # The repo is the module path/name, which is already created above in case it doesn't exist, + # but not always the same as the module path. This is necessary to handle SIV properly. + fuzzed_repo=$(go list $tags -f {{.Module}} "$path") + abspath_repo=`go list -m $tags -f {{.Dir}} $fuzzed_repo || go list $tags -f {{.Dir}} $fuzzed_repo` + # give equivalence to absolute paths in another file, as go test -cover uses golangish pkg.Dir + echo "s=$fuzzed_repo"="$abspath_repo"= > $OUT/$fuzzer.gocovpath + # Additional packages for which to get coverage. + pkgaddcov="" + # to prevent bash from failing about unbound variable + GO_COV_ADD_PKG_SET=${GO_COV_ADD_PKG:-} + if [[ -n "${GO_COV_ADD_PKG_SET}" ]]; then + pkgaddcov=","$GO_COV_ADD_PKG + abspath_repo=`go list -m $tags -f {{.Dir}} $GO_COV_ADD_PKG || go list $tags -f {{.Dir}} $GO_COV_ADD_PKG` + echo "s=^$GO_COV_ADD_PKG"="$abspath_repo"= >> $OUT/$fuzzer.gocovpath + fi + go test -run Test${function}Corpus -v $tags -coverpkg $fuzzed_repo/...$pkgaddcov -c -o $OUT/$fuzzer $path +else + # Compile and instrument all Go files relevant to this fuzz target. + echo "Running go-fuzz $tags -func $function -o $fuzzer.a $path" + go-fuzz $tags -func $function -o $fuzzer.a $path + + # Link Go code ($fuzzer.a) with fuzzing engine to produce fuzz target binary. + $CXX $CXXFLAGS $LIB_FUZZING_ENGINE $fuzzer.a -o $OUT/$fuzzer +fi +) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0243b3ac513e942825e445bf4786bc593f48a338 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py @@ -0,0 +1,121 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Test the functionality of the detect_repo module. +This will consist of the following functional test: + 1. Determine if an OSS-Fuzz projects main repo can be detected from example + commits. + 2. Determine if an OSS-Fuzz project main repo can be detected from a + repo name. +""" +import os +import re +import sys +import tempfile +import unittest +from unittest import mock + +import detect_repo + +# Appending to path for access to repo_manager module. +# pylint: disable=wrong-import-position +sys.path.append( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +import repo_manager +import test_repos +# pylint: enable=wrong-import-position + + +class TestCheckForRepoName(unittest.TestCase): + """Tests for check_for_repo_name.""" + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller/', None)) + def test_go_get_style_url(self, _, __): + """Tests that check_for_repo_name works on repos that were downloaded using + go get.""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller', None)) + def test_missing_git_and_slash_url(self, _, __): + """Tests that check_for_repo_name works on repos who's URLs do not end in + ".git" or "/".""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller.git', None)) + def test_normal_style_repo_url(self, _, __): + """Tests that check_for_repo_name works on normally cloned repos.""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class DetectRepoIntegrationTest(unittest.TestCase): + """Class to test the functionality of the detect_repo module.""" + + def test_infer_main_repo_from_commit(self): + """Tests that the main repo can be inferred based on an example commit.""" + + with tempfile.TemporaryDirectory() as tmp_dir: + # Construct example repo's to check for commits. + for test_repo in test_repos.TEST_REPOS: + repo_manager.clone_repo_and_get_manager(test_repo.git_url, tmp_dir) + self.check_with_repo(test_repo.git_url, + test_repo.git_repo_name, + tmp_dir, + commit=test_repo.old_commit) + + def test_infer_main_repo_from_name(self): + """Tests that the main project repo can be inferred from a repo name.""" + with tempfile.TemporaryDirectory() as tmp_dir: + for test_repo in test_repos.TEST_REPOS: + repo_manager.clone_repo_and_get_manager(test_repo.git_url, tmp_dir) + self.check_with_repo(test_repo.git_url, test_repo.git_repo_name, + tmp_dir) + + def check_with_repo(self, repo_origin, repo_name, tmp_dir, commit=None): + """Checks the detect repo's main method for a specific set of inputs. + + Args: + repo_origin: URL of the git repo. + repo_name: The name of the directory it is cloned to. + tmp_dir: The location of the directory of git repos to be searched. + commit: The commit that should be used to look up the repo. + """ + command = ['python3', 'detect_repo.py', '--src_dir', tmp_dir] + + if commit: + command += ['--example_commit', commit] + else: + command += ['--repo_name', repo_name] + + out, _ = detect_repo.execute(command, + location=os.path.dirname( + os.path.realpath(__file__))) + match = re.search(r'\bDetected repo: ([^ ]+) ([^ ]+)', out.rstrip()) + if match and match.group(1) and match.group(2): + self.assertEqual(match.group(1), repo_origin) + self.assertEqual(match.group(2), os.path.join(tmp_dir, repo_name)) + else: + self.assertIsNone(repo_origin) + self.assertIsNone(repo_name) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_go.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_go.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a93bd76702f33c0c3319fcc74ddbfd42852057 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_go.sh @@ -0,0 +1,43 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +cd /tmp + +wget https://go.dev/dl/go1.23.4.linux-amd64.tar.gz +mkdir temp-go +tar -C temp-go/ -xzf go1.23.4.linux-amd64.tar.gz + +mkdir /root/.go/ +mv temp-go/go/* /root/.go/ +rm -rf temp-go + +echo 'Set "GOPATH=/root/go"' +echo 'Set "PATH=$PATH:/root/.go/bin:$GOPATH/bin"' + +go install github.com/mdempsky/go114-fuzz-build@latest +ln -s $GOPATH/bin/go114-fuzz-build $GOPATH/bin/go-fuzz + +# Build signal handler +if [ -f "$GOPATH/gosigfuzz/gosigfuzz.c" ]; then + clang -c $GOPATH/gosigfuzz/gosigfuzz.c -o $GOPATH/gosigfuzz/gosigfuzz.o +fi + +cd /tmp +git clone https://github.com/AdamKorcz/go-118-fuzz-build +cd go-118-fuzz-build +go build +mv go-118-fuzz-build $GOPATH/bin/ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_java.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_java.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7743c6cd37c9c09f6459c3ed1805d7ddd4b56df --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-builder/install_java.sh @@ -0,0 +1,31 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Install OpenJDK 17 and trim its size by removing unused components. This enables using Jazzer's mutation framework. +cd /tmp +curl --silent -L -O https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-x64_bin.tar.gz && \ +mkdir -p $JAVA_HOME +tar -xz --strip-components=1 -f openjdk-17.0.2_linux-x64_bin.tar.gz --directory $JAVA_HOME && \ +rm -f openjdk-17.0.2_linux-x64_bin.tar.gz +rm -rf $JAVA_HOME/jmods $JAVA_HOME/lib/src.zip + +# Install OpenJDK 15 and trim its size by removing unused components. Some projects only run with Java 15. +curl --silent -L -O https://download.java.net/java/GA/jdk15.0.2/0d1cfde4252546c6931946de8db48ee2/7/GPL/openjdk-15.0.2_linux-x64_bin.tar.gz && \ +mkdir -p $JAVA_15_HOME +tar -xz --strip-components=1 -f openjdk-15.0.2_linux-x64_bin.tar.gz --directory $JAVA_15_HOME && \ +rm -f openjdk-15.0.2_linux-x64_bin.tar.gz +rm -rf $JAVA_15_HOME/jmods $JAVA_15_HOME/lib/src.zip diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner-debug/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner-debug/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05d15f03a48a9cbfb8b6b5383984cfef786bd7db --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner-debug/Dockerfile @@ -0,0 +1,26 @@ +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-runner:${IMG_TAG} +RUN apt-get update && apt-get install -y valgrind zip + +# Installing GDB 12, re https://github.com/google/oss-fuzz/issues/7513. +RUN apt-get install -y build-essential libgmp-dev && \ + wget https://ftp.gnu.org/gnu/gdb/gdb-12.1.tar.xz && \ + tar -xf gdb-12.1.tar.xz && cd gdb-12.1 && ./configure && \ + make -j $(expr $(nproc) / 2) && make install && cd .. && \ + rm -rf gdb-12.1* && apt-get remove --purge -y build-essential libgmp-dev diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/README.md b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e1e29e3802fc485f0a4df667baf89cea7fad5dfd --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/README.md @@ -0,0 +1,31 @@ +# base-runner +> Base image for fuzzer runners. + +```bash +docker run -ti ghcr.io/aixcc-finals/base-runner +``` + +## Commands + +| Command | Description | +|---------|-------------| +| `reproduce ` | build all fuzz targets and run specified one with testcase `/testcase` and given options. +| `run_fuzzer ` | runs specified fuzzer combining options with `.options` file | +| `test_all.py` | runs every binary in `/out` as a fuzzer for a while to ensure it works. | +| `coverage ` | generate a coverage report for the given fuzzer. | + +# Examples + +- *Reproduce using latest OSS-Fuzz build:* + +
+docker run --rm -ti -v <testcase_path>:/testcase gcr.io/oss-fuzz/$PROJECT_NAME reproduce <fuzzer_name>
+
+ +- *Reproduce using local source checkout:* + +
+docker run --rm -ti -v <source_path>:/src/$PROJECT_NAME \
+                    -v <testcase_path>:/testcase gcr.io/oss-fuzz/$PROJECT_NAME \
+                    reproduce <fuzzer_name>
+
diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage new file mode 100644 index 0000000000000000000000000000000000000000..585b4d457e753e12025344efd735c571b38fb580 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage @@ -0,0 +1,549 @@ +#!/bin/bash -u +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +cd $OUT + +if (( $# > 0 )); then + FUZZ_TARGETS="$@" +else + FUZZ_TARGETS="$(find . -maxdepth 1 -type f -executable -printf '%P\n' | \ + grep -v -x -F \ + -e 'llvm-symbolizer' \ + -e 'jazzer_agent_deploy.jar' \ + -e 'jazzer_driver' \ + -e 'jazzer_driver_with_sanitizer' \ + -e 'sanitizer_with_fuzzer.so')" +fi + +COVERAGE_OUTPUT_DIR=${COVERAGE_OUTPUT_DIR:-$OUT} + +DUMPS_DIR="$COVERAGE_OUTPUT_DIR/dumps" +FUZZERS_COVERAGE_DUMPS_DIR="$DUMPS_DIR/fuzzers_coverage" +MERGED_COVERAGE_DIR="$COVERAGE_OUTPUT_DIR/merged_coverage" +FUZZER_STATS_DIR="$COVERAGE_OUTPUT_DIR/fuzzer_stats" +TEXTCOV_REPORT_DIR="$COVERAGE_OUTPUT_DIR/textcov_reports" +LOGS_DIR="$COVERAGE_OUTPUT_DIR/logs" +REPORT_ROOT_DIR="$COVERAGE_OUTPUT_DIR/report" +REPORT_BY_TARGET_ROOT_DIR="$COVERAGE_OUTPUT_DIR/report_target" +PLATFORM=linux +REPORT_PLATFORM_DIR="$COVERAGE_OUTPUT_DIR/report/$PLATFORM" + +for directory in $DUMPS_DIR $FUZZER_STATS_DIR $LOGS_DIR $REPORT_ROOT_DIR $TEXTCOV_REPORT_DIR\ + $REPORT_PLATFORM_DIR $REPORT_BY_TARGET_ROOT_DIR $FUZZERS_COVERAGE_DUMPS_DIR $MERGED_COVERAGE_DIR; do + rm -rf $directory + mkdir -p $directory +done + +PROFILE_FILE="$DUMPS_DIR/merged.profdata" +SUMMARY_FILE="$REPORT_PLATFORM_DIR/summary.json" +COVERAGE_TARGET_FILE="$FUZZER_STATS_DIR/coverage_targets.txt" + +# Use path mapping, as $SRC directory from the builder is copied into $OUT/$SRC. +PATH_EQUIVALENCE_ARGS="-path-equivalence=/,$OUT" + +# It's important to use $COVERAGE_EXTRA_ARGS as the last argument, because it +# can contain paths to source files / directories which are positional args. +LLVM_COV_COMMON_ARGS="$PATH_EQUIVALENCE_ARGS \ + -ignore-filename-regex=.*src/libfuzzer/.* $COVERAGE_EXTRA_ARGS" + +# Options to extract branch coverage. +BRANCH_COV_ARGS="--show-branches=count --show-expansions" + +# Timeout for running a single fuzz target. +TIMEOUT=1h + +# This will be used by llvm-cov command to generate the actual report. +objects="" + +# Number of CPUs available, this is needed for running tests in parallel. +# Set the max number of parallel jobs to be the CPU count and a max of 10. +NPROC=$(nproc) +MAX_PARALLEL_COUNT=10 + +CORPUS_DIR=${CORPUS_DIR:-"/corpus"} + +function run_fuzz_target { + local target=$1 + + # '%1m' will produce separate dump files for every object. For example, if a + # fuzz target loads a shared library, we will have dumps for both of them. + local profraw_file="$DUMPS_DIR/$target.%1m.profraw" + local profraw_file_mask="$DUMPS_DIR/$target.*.profraw" + local profdata_file="$DUMPS_DIR/$target.profdata" + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # Use -merge=1 instead of -runs=0 because merge is crash resistant and would + # let to get coverage using all corpus files even if there are crash inputs. + # Merge should not introduce any significant overhead compared to -runs=0, + # because (A) corpuses are already minimized; (B) we do not use sancov, and so + # libFuzzer always finishes merge with an empty output dir. + # Use 100s timeout instead of 25s as code coverage builds can be very slow. + local args="-merge=1 -timeout=100 $corpus_dummy $corpus_real" + + export LLVM_PROFILE_FILE=$profraw_file + timeout $TIMEOUT $OUT/$target $args &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + rm -rf $corpus_dummy + if (( $(du -c $profraw_file_mask | tail -n 1 | cut -f 1) == 0 )); then + # Skip fuzz targets that failed to produce profile dumps. + return 0 + fi + + # If necessary translate to latest profraw version. + if [[ $target == *"@"* ]]; then + # Extract fuzztest binary name from fuzztest wrapper script. + target=(${target//@/ }[0]) + fi + profraw_update.py $OUT/$target -i $profraw_file_mask + llvm-profdata merge -j=1 -sparse $profraw_file_mask -o $profdata_file + + # Delete unnecessary and (potentially) large .profraw files. + rm $profraw_file_mask + + shared_libraries=$(coverage_helper shared_libs -build-dir=$OUT -object=$target) + + llvm-cov export -summary-only -instr-profile=$profdata_file -object=$target \ + $shared_libraries $LLVM_COV_COMMON_ARGS > $FUZZER_STATS_DIR/$target.json + + # For introspector. + llvm-cov show -instr-profile=$profdata_file -object=$target -line-coverage-gt=0 $shared_libraries $BRANCH_COV_ARGS $LLVM_COV_COMMON_ARGS > ${TEXTCOV_REPORT_DIR}/$target.covreport +} + +function run_go_fuzz_target { + local target=$1 + + echo "Running go target $target" + export FUZZ_CORPUS_DIR="$CORPUS_DIR/${target}/" + export FUZZ_PROFILE_NAME="$DUMPS_DIR/$target.perf" + + # setup for native go fuzzers + cd $OUT + mkdir -p "testdata/fuzz/${target}" + cp -r "${FUZZ_CORPUS_DIR}" "testdata/fuzz/" + + # rewrite libFuzzer corpus to Std Go corpus if native fuzzing + grep "TestFuzzCorpus" $target > /dev/null 2>&1 && $SYSGOPATH/bin/convertcorpus $target "testdata/fuzz/${target}" + cd - + + timeout $TIMEOUT $OUT/$target -test.coverprofile $DUMPS_DIR/$target.profdata &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + # cleanup after native go fuzzers + rm -r "${OUT}/testdata/fuzz/${target}" + + # The Go 1.18 fuzzers are renamed to "*_fuzz_.go" during "infra/helper.py build_fuzzers". + # They are are therefore refered to as "*_fuzz_.go" in the profdata files. + # Since the copies named "*_fuzz_.go" do not exist in the file tree during + # the coverage build, we change the references in the .profdata files + # to the original file names. + #sed -i "s/_test.go_fuzz_.go/_test.go/g" $DUMPS_DIR/$target.profdata + # translate from golangish paths to current absolute paths + cat $OUT/$target.gocovpath | while read i; do sed -i $i $DUMPS_DIR/$target.profdata; done + # cf PATH_EQUIVALENCE_ARGS + sed -i 's=/='$OUT'/=' $DUMPS_DIR/$target.profdata + $SYSGOPATH/bin/gocovsum $DUMPS_DIR/$target.profdata > $FUZZER_STATS_DIR/$target.json +} + +function run_python_fuzz_target { + local target=$1 + local zipped_sources="$DUMPS_DIR/$target.deps.zip" + local corpus_real="$CORPUS_DIR/${target}" + # Write dummy stats file + echo "{}" > "$FUZZER_STATS_DIR/$target.json" + + # Run fuzzer + $OUT/$target $corpus_real -atheris_runs=$(ls -la $corpus_real | wc -l) > $LOGS_DIR/$target.log 2>&1 + if (( $? != 0 )); then + echo "Error happened getting coverage of $target" + echo "This is likely because Atheris did not exit gracefully" + cat $LOGS_DIR/$target.log + return 0 + fi + mv .coverage $OUT/.coverage_$target +} + +function run_java_fuzz_target { + local target=$1 + + local exec_file="$DUMPS_DIR/$target.exec" + local class_dump_dir="$DUMPS_DIR/${target}_classes/" + mkdir "$class_dump_dir" + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # Use 100s timeout instead of 25s as code coverage builds can be very slow. + local jacoco_args="destfile=$exec_file,classdumpdir=$class_dump_dir,excludes=com.code_intelligence.jazzer.*\\:com.sun.tools.attach.VirtualMachine" + local args="-merge=1 -timeout=100 --nohooks \ + --additional_jvm_args=-javaagent\\:/opt/jacoco-agent.jar=$jacoco_args \ + $corpus_dummy $corpus_real" + + timeout $TIMEOUT $OUT/$target $args &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + if (( $(du -c $exec_file | tail -n 1 | cut -f 1) == 0 )); then + # Skip fuzz targets that failed to produce .exec files. + echo "$target failed to produce .exec file." + return 0 + fi + + # Generate XML report only as input to jacoco_report_converter. + # Source files are not needed for the summary. + local xml_report="$DUMPS_DIR/${target}.xml" + local summary_file="$FUZZER_STATS_DIR/$target.json" + java -jar /opt/jacoco-cli.jar report $exec_file \ + --xml $xml_report \ + --classfiles $class_dump_dir + + # Write llvm-cov summary file. + jacoco_report_converter.py $xml_report $summary_file +} + +function run_javascript_fuzz_target { + local target=$1 + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # IstanbulJS currently does not work when the tested program creates + # subprocesses. For this reason, we first minimize the corpus removing + # any crashing inputs so that we can report source-based code coverage + # with a single sweep over the minimized corpus + local merge_args="-merge=1 -timeout=100 $corpus_dummy $corpus_real" + timeout $TIMEOUT $OUT/$target $merge_args &> $LOGS_DIR/$target.log + + # nyc saves the coverage reports in a directory with the default name "coverage" + local coverage_dir="$DUMPS_DIR/coverage_dir_for_${target}" + rm -rf $coverage_dir && mkdir -p $coverage_dir + + local nyc_json_coverage_file="$coverage_dir/coverage-final.json" + local nyc_json_summary_file="$coverage_dir/coverage-summary.json" + + local args="-runs=0 $corpus_dummy" + local jazzerjs_args="--coverage --coverageDirectory $coverage_dir --coverageReporters json --coverageReporters json-summary" + + JAZZERJS_EXTRA_ARGS=$jazzerjs_args $OUT/$target $args &> $LOGS_DIR/$target.log + + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + if [ ! -s $nyc_json_coverage_file ]; then + # Skip fuzz targets that failed to produce coverage-final.json file. + echo "$target failed to produce coverage-final.json file." + return 0 + fi + + cp $nyc_json_coverage_file $FUZZERS_COVERAGE_DUMPS_DIR/$target.json + + local summary_file="$FUZZER_STATS_DIR/$target.json" + + nyc_report_converter.py $nyc_json_summary_file $summary_file +} + +function generate_html { + local profdata=$1 + local shared_libraries=$2 + local objects=$3 + local output_dir=$4 + + rm -rf "$output_dir" + mkdir -p "$output_dir/$PLATFORM" + + local llvm_cov_args="-instr-profile=$profdata $objects $LLVM_COV_COMMON_ARGS" + llvm-cov show -format=html -output-dir=$output_dir -Xdemangler rcfilt $llvm_cov_args + + # Export coverage summary in JSON format. + local summary_file=$output_dir/$PLATFORM/summary.json + + llvm-cov export -summary-only $llvm_cov_args > $summary_file + + coverage_helper -v post_process -src-root-dir=/ -summary-file=$summary_file \ + -output-dir=$output_dir $PATH_EQUIVALENCE_ARGS +} + +export SYSGOPATH=$GOPATH +export GOPATH=$OUT/$GOPATH +# Run each fuzz target, generate raw coverage dumps. +for fuzz_target in $FUZZ_TARGETS; do + # Test if fuzz target is a golang one. + if [[ $FUZZING_LANGUAGE == "go" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "FUZZ_CORPUS_DIR" $fuzz_target > /dev/null 2>&1 || grep "testing\.T" $fuzz_target > /dev/null 2>&1 || continue + fi + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_go_fuzz_target $fuzz_target & + elif [[ $FUZZING_LANGUAGE == "python" ]]; then + echo "Entering python fuzzing" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_python_fuzz_target $fuzz_target + elif [[ $FUZZING_LANGUAGE == "jvm" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_java_fuzz_target $fuzz_target & + elif [[ $FUZZING_LANGUAGE == "javascript" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_javascript_fuzz_target $fuzz_target & + else + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_fuzz_target $fuzz_target & + + # Rewrite object if its a FUZZTEST target + if [[ $fuzz_target == *"@"* ]]; then + # Extract fuzztest binary name from fuzztest wrapper script. + fuzz_target=(${fuzz_target//@/ }[0]) + fi + if [[ -z $objects ]]; then + # The first object needs to be passed without -object= flag. + objects="$fuzz_target" + else + objects="$objects -object=$fuzz_target" + fi + fi + + + # Limit the number of processes to be spawned. + n_child_proc=$(jobs -rp | wc -l) + while [[ "$n_child_proc" -eq "$NPROC" || "$n_child_proc" -gt "$MAX_PARALLEL_COUNT" ]]; do + sleep 4 + n_child_proc=$(jobs -rp | wc -l) + done +done + +# Wait for background processes to finish. +wait + +if [[ $FUZZING_LANGUAGE == "go" ]]; then + echo $DUMPS_DIR + $SYSGOPATH/bin/gocovmerge $DUMPS_DIR/*.profdata > fuzz.cov + gotoolcover -html=fuzz.cov -o $REPORT_ROOT_DIR/index.html + $SYSGOPATH/bin/gocovsum fuzz.cov > $SUMMARY_FILE + cp $REPORT_ROOT_DIR/index.html $REPORT_PLATFORM_DIR/index.html + $SYSGOPATH/bin/pprof-merge $DUMPS_DIR/*.perf.cpu.prof + mv merged.data $REPORT_ROOT_DIR/cpu.prof + $SYSGOPATH/bin/pprof-merge $DUMPS_DIR/*.perf.heap.prof + mv merged.data $REPORT_ROOT_DIR/heap.prof + #TODO some proxy for go tool pprof -http=127.0.0.1:8001 $DUMPS_DIR/cpu.prof + echo "Finished generating code coverage report for Go fuzz targets." +elif [[ $FUZZING_LANGUAGE == "python" ]]; then + # Extract source files from all dependency zip folders + mkdir -p /pythoncovmergedfiles/medio + PYCOVDIR=/pycovdir/ + mkdir $PYCOVDIR + for fuzzer in $FUZZ_TARGETS; do + fuzzer_deps=${fuzzer}.pkg.deps.zip + unzip $OUT/${fuzzer_deps} + rsync -r ./medio /pythoncovmergedfiles/medio + rm -rf ./medio + + # Translate paths in unzipped folders to paths that we can use + mv $OUT/.coverage_$fuzzer .coverage + python3 /usr/local/bin/python_coverage_runner_help.py translate /pythoncovmergedfiles/medio + cp .new_coverage $PYCOVDIR/.coverage_$fuzzer + cp .new_coverage $OUT/coverage_d_$fuzzer + done + + # Combine coverage + cd $PYCOVDIR + python3 /usr/local/bin/python_coverage_runner_help.py combine .coverage_* + python3 /usr/local/bin/python_coverage_runner_help.py html + # Produce all_cov file used by fuzz introspector. + python3 /usr/local/bin/python_coverage_runner_help.py json -o ${TEXTCOV_REPORT_DIR}/all_cov.json + + # Generate .json with similar format to llvm-cov output. + python3 /usr/local/bin/python_coverage_runner_help.py \ + convert-to-summary-json ${TEXTCOV_REPORT_DIR}/all_cov.json $SUMMARY_FILE + + # Copy coverage date out + cp htmlcov/status.json ${TEXTCOV_REPORT_DIR}/html_status.json + + mv htmlcov/* $REPORT_PLATFORM_DIR/ + mv .coverage_* $REPORT_PLATFORM_DIR/ +elif [[ $FUZZING_LANGUAGE == "jvm" ]]; then + + # From this point on the script does not tolerate any errors. + set -e + + # Merge .exec files from the individual targets. + jacoco_merged_exec=$DUMPS_DIR/jacoco.merged.exec + java -jar /opt/jacoco-cli.jar merge $DUMPS_DIR/*.exec \ + --destfile $jacoco_merged_exec + + # Prepare classes directory for jacoco process + classes_dir=$DUMPS_DIR/classes + mkdir $classes_dir + + # Only copy class files found in $OUT/$SRC to ensure they are + # lively compiled from the project, avoiding inclusion of + # dependency classes. This also includes the fuzzer classes. + find "$OUT/$SRC" -type f -name "*.class" | while read -r class_file; do + # Skip module-info.class + if [[ "$(basename "$class_file")" == "module-info.class" ]]; then + continue + fi + + # Use javap to extract the fully qualified name of the class and copy it to $classes_dir + fqn=$(javap -verbose "$class_file" 2>/dev/null | grep "this_class:" | grep -oP '(?<=// ).*') + if [ -n "$fqn" ]; then + mkdir -p $classes_dir/$(dirname $fqn) + cp $class_file $classes_dir/$fqn.class + fi + done + + # Heuristically determine source directories based on Maven structure. + # Always include the $SRC root as it likely contains the fuzzer sources. + sourcefiles_args=(--sourcefiles $OUT/$SRC) + source_dirs=$(find $OUT/$SRC -type d -name 'java') + for source_dir in $source_dirs; do + sourcefiles_args+=(--sourcefiles "$source_dir") + done + + # Generate HTML and XML reports. + xml_report=$REPORT_PLATFORM_DIR/index.xml + java -jar /opt/jacoco-cli.jar report $jacoco_merged_exec \ + --html $REPORT_PLATFORM_DIR \ + --xml $xml_report \ + --classfiles $classes_dir \ + "${sourcefiles_args[@]}" + + # Also serve the raw exec file and XML report, which can be useful for + # automated analysis. + cp $jacoco_merged_exec $REPORT_PLATFORM_DIR/jacoco.exec + cp $xml_report $REPORT_PLATFORM_DIR/jacoco.xml + cp $xml_report $TEXTCOV_REPORT_DIR/jacoco.xml + + # Write llvm-cov summary file. + jacoco_report_converter.py $xml_report $SUMMARY_FILE + + set +e +elif [[ $FUZZING_LANGUAGE == "javascript" ]]; then + + # From this point on the script does not tolerate any errors. + set -e + + json_report=$MERGED_COVERAGE_DIR/coverage.json + nyc merge $FUZZERS_COVERAGE_DUMPS_DIR $json_report + + nyc report -t $MERGED_COVERAGE_DIR --report-dir $REPORT_PLATFORM_DIR --reporter=html --reporter=json-summary + + nyc_json_summary_file=$REPORT_PLATFORM_DIR/coverage-summary.json + + # Write llvm-cov summary file. + nyc_report_converter.py $nyc_json_summary_file $SUMMARY_FILE + + set +e +else + + # From this point on the script does not tolerate any errors. + set -e + + # Merge all dumps from the individual targets. + rm -f $PROFILE_FILE + llvm-profdata merge -sparse $DUMPS_DIR/*.profdata -o $PROFILE_FILE + + # TODO(mmoroz): add script from Chromium for rendering directory view reports. + # The first path in $objects does not have -object= prefix (llvm-cov format). + shared_libraries=$(coverage_helper shared_libs -build-dir=$OUT -object=$objects) + objects="$objects $shared_libraries" + + generate_html $PROFILE_FILE "$shared_libraries" "$objects" "$REPORT_ROOT_DIR" + + # Per target reports. + for fuzz_target in $FUZZ_TARGETS; do + if [[ $fuzz_target == *"@"* ]]; then + profdata_path=$DUMPS_DIR/$fuzz_target.profdata + report_dir=$REPORT_BY_TARGET_ROOT_DIR/$fuzz_target + # Extract fuzztest binary name from fuzztest wrapper script. + fuzz_target=(${fuzz_target//@/ }[0]) + else + profdata_path=$DUMPS_DIR/$fuzz_target.profdata + report_dir=$REPORT_BY_TARGET_ROOT_DIR/$fuzz_target + fi + if [[ ! -f "$profdata_path" ]]; then + echo "WARNING: $fuzz_target has no profdata generated." + continue + fi + + generate_html $profdata_path "$shared_libraries" "$fuzz_target" "$report_dir" + done + + set +e +fi + +# Make sure report is readable. +chmod -R +r $REPORT_ROOT_DIR $REPORT_BY_TARGET_ROOT_DIR +find $REPORT_ROOT_DIR $REPORT_BY_TARGET_ROOT_DIR -type d -exec chmod +x {} + + +# HTTP_PORT is optional. +set +u +if [[ -n $HTTP_PORT ]]; then + # Serve the report locally. + echo "Serving the report on http://127.0.0.1:$HTTP_PORT/linux/index.html" + cd $REPORT_ROOT_DIR + python3 -m http.server $HTTP_PORT +fi diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage_helper b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage_helper new file mode 100644 index 0000000000000000000000000000000000000000..4d29ceac8f5d048a43a7ec6cc0524d7a23936781 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/coverage_helper @@ -0,0 +1,17 @@ +#!/bin/bash -u +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +python3 $CODE_COVERAGE_SRC/coverage_utils.py $@ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/download_corpus b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/download_corpus new file mode 100644 index 0000000000000000000000000000000000000000..1b7ebe8a263b5c3410dcbbd5b8e861c5cf134d4a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/download_corpus @@ -0,0 +1,30 @@ +#!/bin/bash -u +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +if (( $# < 1 )); then + echo "Usage: $0 \"path_download_to url_download_from\" (can be repeated)" >&2 + exit 1 +fi + +for pair in "$@"; do + read path url <<< "$pair" + wget -q -O $path $url +done + +# Always exit with 0 as we do not track wget return codes and should not rely +# on the latest command execution. +exit 0 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9fc22230c71a5c7f01068a871d44942489aad0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +# +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Script for generating differential coverage reports. +generate_differential_cov_report.py \ + +""" +import os +import shutil +import subprocess +import sys + + +class ProfData: + """Class representing a profdata file.""" + + def __init__(self, text): + self.function_profs = [] + for function_prof in text.split('\n\n'): + if not function_prof: + continue + self.function_profs.append(FunctionProf(function_prof)) + + def to_string(self): + """Convert back to a string.""" + return '\n'.join( + [function_prof.to_string() for function_prof in self.function_profs]) + + def find_function(self, function, idx=None): + """Find the same function in this profdata.""" + if idx is not None: + try: + possibility = self.function_profs[idx] + if function.func_hash == possibility.func_hash: + return possibility + except IndexError: + pass + for function_prof in self.function_profs: + if function_prof.func_hash == function.func_hash: + return function_prof + return None + + def subtract(self, subtrahend): + """Subtract subtrahend from this profdata.""" + for idx, function_prof in enumerate(self.function_profs): + subtrahend_function_prof = subtrahend.find_function(function_prof, idx) + function_prof.subtract(subtrahend_function_prof) + + +class FunctionProf: + """Profile of a function.""" + FUNC_HASH_COMMENT_LINE = '# Func Hash:' + NUM_COUNTERS_COMMENT_LINE = '# Num Counters:' + COUNTER_VALUES_COMMENT_LINE = '# Counter Values:' + + def __init__(self, text): + print(text) + lines = text.splitlines() + self.function = lines[0] + assert self.FUNC_HASH_COMMENT_LINE == lines[1] + self.func_hash = lines[2] + assert self.NUM_COUNTERS_COMMENT_LINE == lines[3] + self.num_counters = int(lines[4]) + assert self.COUNTER_VALUES_COMMENT_LINE == lines[5] + self.counter_values = [1 if int(line) else 0 for line in lines[6:]] + + def to_string(self): + """Convert back to text.""" + lines = [ + self.function, + self.FUNC_HASH_COMMENT_LINE, + self.func_hash, + self.NUM_COUNTERS_COMMENT_LINE, + str(self.num_counters), + self.COUNTER_VALUES_COMMENT_LINE, + ] + [str(num) for num in self.counter_values] + return '\n'.join(lines) + + def subtract(self, subtrahend_prof): + """Subtract this other function from this function.""" + if not subtrahend_prof: + print(self.function, 'has no subtrahend') + # Nothing to subtract. + return + self.counter_values = [ + max(counter1 - counter2, 0) for counter1, counter2 in zip( + self.counter_values, subtrahend_prof.counter_values) + ] + + +def get_profdata_files(directory): + """Returns profdata files in |directory|.""" + profdatas = [] + for filename in os.listdir(directory): + filename = os.path.join(directory, filename) + if filename.endswith('.profdata'): + profdatas.append(filename) + return profdatas + + +def convert_profdata_to_text(profdata): + """Convert a profdata binary file to a profdata text file.""" + profdata_text = f'{profdata}.txt' + if os.path.exists(profdata_text): + os.remove(profdata_text) + command = [ + 'llvm-profdata', 'merge', '-j=1', '-sparse', profdata, '--text', '-o', + profdata_text + ] + print(command) + subprocess.run(command, check=True) + return profdata_text + + +def convert_text_profdata_to_bin(profdata_text): + """Convert a profdata text file to a profdata binary file.""" + profdata = profdata_text.replace('.txt', '').replace('.profdata', + '') + '.profdata' + print('bin profdata', profdata) + if os.path.exists(profdata): + os.remove(profdata) + command = [ + 'llvm-profdata', 'merge', '-j=1', '-sparse', profdata_text, '-o', profdata + ] + print(command) + subprocess.run(command, check=True) + return profdata + + +def get_difference(minuend_filename, subtrahend_filename): + """Subtract subtrahend_filename from minuend_filename.""" + with open(minuend_filename, 'r', encoding='utf-8') as minuend_file: + print('minuend', minuend_filename) + minuend = ProfData(minuend_file.read()) + with open(subtrahend_filename, 'r', encoding='utf-8') as subtrahend_file: + print('subtrahend', subtrahend_filename) + subtrahend = ProfData(subtrahend_file.read()) + + minuend.subtract(subtrahend) + return minuend + + +def profdatas_to_objects(profdatas): + """Get the corresponding objects for each profdata.""" + return [ + os.path.splitext(os.path.basename(profdata))[0] for profdata in profdatas + ] + + +def generate_differential_cov_reports(minuend_profdatas, subtrahend_profdatas, + difference_dir): + """Calculate the differences between all profdatas and generate differential + coverage reports.""" + profdata_objects = profdatas_to_objects(minuend_profdatas) + real_profdata_objects = [ + binobject for binobject in profdata_objects if binobject != 'merged' + ] + for minuend, subtrahend, binobject in zip(minuend_profdatas, + subtrahend_profdatas, + profdata_objects): + minuend_text = convert_profdata_to_text(minuend) + subtrahend_text = convert_profdata_to_text(subtrahend) + difference = get_difference(minuend_text, subtrahend_text) + basename = os.path.basename(minuend_text) + difference_text = os.path.join(difference_dir, basename) + with open(difference_text, 'w', encoding='utf-8') as file_handle: + file_handle.write(difference.to_string()) + difference_profdata = convert_text_profdata_to_bin(difference_text) + if not difference_profdata.endswith('merged.profdata'): + generate_html_report(difference_profdata, [binobject], + os.path.join(difference_dir, binobject)) + else: + generate_html_report(difference_profdata, real_profdata_objects, + os.path.join(difference_dir, 'merged')) + + +def generate_html_report(profdata, objects, directory): + """Generate an HTML coverage report.""" + # TODO(metzman): Deal with shared libs. + html_dir = os.path.join(directory, 'reports') + if os.path.exists(html_dir): + os.remove(html_dir) + os.makedirs(html_dir) + out_dir = os.getenv('OUT', '/out') + command = [ + 'llvm-cov', 'show', f'-path-equivalence=/,{out_dir}', '-format=html', + '-Xdemangler', 'rcfilt', f'-instr-profile={profdata}' + ] + + objects = [os.path.join(out_dir, binobject) for binobject in objects] + command += objects + ['-o', html_dir] + print(' '.join(command)) + subprocess.run(command, check=True) + + +def main(): + """Generate differential coverage reports.""" + if len(sys.argv) != 4: + print( + f'Usage: {sys.argv[0]} ') + minuend_dir = sys.argv[1] + subtrahend_dir = sys.argv[2] + difference_dir = sys.argv[3] + if os.path.exists(difference_dir): + shutil.rmtree(difference_dir) + os.makedirs(difference_dir, exist_ok=True) + minuend_profdatas = get_profdata_files(minuend_dir) + subtrahend_profdatas = get_profdata_files(subtrahend_dir) + generate_differential_cov_reports(minuend_profdatas, subtrahend_profdatas, + difference_dir) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_deps.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_deps.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc0569b339add75ce09c0772fbaa938a4aca0db1 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_deps.sh @@ -0,0 +1,37 @@ +#!/bin/bash -eux +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Install dependencies in a platform-aware way. + +apt-get update && apt-get install -y \ + binutils \ + file \ + ca-certificates \ + fonts-dejavu \ + git \ + libcap2 \ + rsync \ + unzip \ + wget \ + zip --no-install-recommends + +case $(uname -m) in + x86_64) + # We only need to worry about i386 if we are on x86_64. + apt-get install -y lib32gcc1 libc6-i386 + ;; +esac diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_go.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_go.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d6066b0f0a8c868d34099204b18c9ce140f09e1 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_go.sh @@ -0,0 +1,41 @@ +#!/bin/bash -eux +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Install go on x86_64, don't do anything on ARM. + +case $(uname -m) in + x86_64) + # Download and install Go 1.19. + wget -q https://storage.googleapis.com/golang/getgo/installer_linux -O $SRC/installer_linux + chmod +x $SRC/installer_linux + SHELL="bash" $SRC/installer_linux -version 1.19 + rm $SRC/installer_linux + # Set up Golang coverage modules. + printf $(find . -name gocoverage) + cd $GOPATH/gocoverage && /root/.go/bin/go install ./... + cd convertcorpus && /root/.go/bin/go install . + cd /root/.go/src/cmd/cover && /root/.go/bin/go build && mv cover $GOPATH/bin/gotoolcover + ;; + aarch64) + # Don't install go because installer is not provided. + echo "Not installing go: aarch64." + ;; + *) + echo "Error: unsupported architecture: $(uname -m)" + exit 1 + ;; +esac diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_java.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_java.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cf3855265031837b0d64058de3e7742d9383934 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/install_java.sh @@ -0,0 +1,46 @@ +#!/bin/bash -eux +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Install java in a platform-aware way. + +ARCHITECTURE= +case $(uname -m) in + x86_64) + ARCHITECTURE=x64 + ;; + aarch64) + ARCHITECTURE=aarch64 + ;; + *) + echo "Error: unsupported architecture: $(uname -m)" + exit 1 + ;; +esac + +wget -q https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz -O /tmp/openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +wget -q https://download.java.net/java/GA/jdk15.0.2/0d1cfde4252546c6931946de8db48ee2/7/GPL/openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz -O /tmp/openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +cd /tmp +mkdir -p $JAVA_HOME +tar -xz --strip-components=1 -f openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz --directory $JAVA_HOME +rm -f openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +rm -rf $JAVA_HOME/jmods $JAVA_HOME/lib/src.zip + +# Install OpenJDK 15 and trim its size by removing unused components. Some projects only run with Java 15. +mkdir -p $JAVA_15_HOME +tar -xz --strip-components=1 -f openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz --directory $JAVA_15_HOME +rm -f openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +rm -rf $JAVA_15_HOME/jmods $JAVA_15_HOME/lib/src.zip diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..bf9d89faf3a10fb1e7c3e4f7eb49538567bb8a00 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Helper script for creating an llvm-cov style JSON summary from a JaCoCo XML +report.""" +import json +import os +import sys +import xml.etree.ElementTree as ET + + +def convert(xml): + """Turns a JaCoCo XML report into an llvm-cov JSON summary.""" + summary = { + 'type': 'oss-fuzz.java.coverage.json.export', + 'version': '1.0.0', + 'data': [{ + 'totals': {}, + 'files': [], + }], + } + + report = ET.fromstring(xml) + totals = make_element_summary(report) + summary['data'][0]['totals'] = totals + + # Since Java compilation does not track source file location, we match + # coverage info to source files via the full class name, e.g. we search for + # a path in /out/src ending in foo/bar/Baz.java for the class foo.bar.Baz. + # Under the assumptions that a given project only ever contains a single + # version of a class and that no class name appears as a suffix of another + # class name, we can assign coverage info to every source file matched in that + # way. + src_files = list_src_files() + + for class_element in report.findall('./package/class'): + # Skip fuzzer classes + if is_fuzzer_class(class_element): + continue + + # Skip non class elements + if 'sourcefilename' not in class_element.attrib: + continue + + class_name = class_element.attrib['name'] + package_name = os.path.dirname(class_name) + basename = class_element.attrib['sourcefilename'] + # This path is 'foo/Bar.java' for the class element + # . + canonical_path = os.path.join(package_name, basename) + + class_summary = make_element_summary(class_element) + for src_file in relative_to_src_path(src_files, canonical_path): + summary['data'][0]['files'].append({ + 'filename': src_file, + 'summary': class_summary, + }) + + return json.dumps(summary) + + +def list_src_files(): + """Returns a map from basename to full path for all files in $OUT/$SRC.""" + filename_to_paths = {} + out_path = os.environ['OUT'] + '/' + src_path = os.environ['SRC'] + src_in_out = out_path + src_path + for dirpath, _, filenames in os.walk(src_in_out): + for filename in filenames: + full_path = dirpath + '/' + filename + # Map /out//src/... to /src/... + file_path = full_path[len(out_path):] + filename_to_paths.setdefault(filename, []).append(file_path) + return filename_to_paths + + +def is_fuzzer_class(class_element): + """Check if the class is fuzzer class.""" + method_elements = class_element.find('./method[@name=\"fuzzerTestOneInput\"]') + if method_elements: + return True + + return False + + +def relative_to_src_path(src_files, canonical_path): + """Returns all paths in src_files ending in canonical_path.""" + basename = os.path.basename(canonical_path) + if basename not in src_files: + return [] + candidate_paths = src_files[basename] + return [ + path for path in candidate_paths if path.endswith("/" + canonical_path) + ] + + +def make_element_summary(element): + """Returns a coverage summary for an element in the XML report.""" + summary = {} + + function_counter = element.find('./counter[@type=\'METHOD\']') + summary['functions'] = make_counter_summary(function_counter) + + line_counter = element.find('./counter[@type=\'LINE\']') + summary['lines'] = make_counter_summary(line_counter) + + # JaCoCo tracks branch coverage, which counts the covered control-flow edges + # between llvm-cov's regions instead of the covered regions themselves. For + # non-trivial code parts, the difference is usually negligible. However, if + # all methods of a class consist of a single region only (no branches), + # JaCoCo does not report any branch coverage even if there is instruction + # coverage. Since this would give incorrect results for CI Fuzz purposes, we + # increase the regions counter by 1 if there is any amount of instruction + # coverage. + instruction_counter = element.find('./counter[@type=\'INSTRUCTION\']') + has_some_coverage = instruction_counter is not None and int( + instruction_counter.attrib["covered"]) > 0 + branch_covered_adjustment = 1 if has_some_coverage else 0 + region_counter = element.find('./counter[@type=\'BRANCH\']') + summary['regions'] = make_counter_summary( + region_counter, covered_adjustment=branch_covered_adjustment) + + return summary + + +def make_counter_summary(counter_element, covered_adjustment=0): + """Turns a JaCoCo element into an llvm-cov totals entry.""" + summary = {} + covered = covered_adjustment + missed = 0 + if counter_element is not None: + covered += int(counter_element.attrib['covered']) + missed += int(counter_element.attrib['missed']) + summary['covered'] = covered + summary['notcovered'] = missed + summary['count'] = summary['covered'] + summary['notcovered'] + if summary['count'] != 0: + summary['percent'] = (100.0 * summary['covered']) / summary['count'] + else: + summary['percent'] = 0 + return summary + + +def main(): + """Produces an llvm-cov style JSON summary from a JaCoCo XML report.""" + if len(sys.argv) != 3: + sys.stderr.write('Usage: %s \n' % + sys.argv[0]) + return 1 + + with open(sys.argv[1], 'r') as xml_file: + xml_report = xml_file.read() + json_summary = convert(xml_report) + with open(sys.argv[2], 'w') as json_file: + json_file.write(json_summary) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..53044754c26b2a74a6b7afa7f5f22b52881767d1 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Helper script for creating a llvm-cov style JSON summary from a nyc +JSON summary.""" +import json +import sys + + +def convert(nyc_json_summary): + """Turns a nyc JSON report into a llvm-cov JSON summary.""" + summary = { + 'type': + 'oss-fuzz.javascript.coverage.json.export', + 'version': + '1.0.0', + 'data': [{ + 'totals': + file_summary(nyc_json_summary['total']), + 'files': [{ + 'filename': src_file, + 'summary': file_summary(nyc_json_summary[src_file]) + } for src_file in nyc_json_summary if src_file != 'total'], + }], + } + + return json.dumps(summary) + + +def file_summary(nyc_file_summary): + """Returns a summary for a given file in the nyc JSON summary report.""" + return { + 'functions': element_summary(nyc_file_summary['functions']), + 'lines': element_summary(nyc_file_summary['lines']), + 'regions': element_summary(nyc_file_summary['branches']) + } + + +def element_summary(element): + """Returns a summary of a coverage element in the nyc JSON summary + of the file""" + return { + 'count': element['total'], + 'covered': element['covered'], + 'notcovered': element['total'] - element['covered'] - element['skipped'], + 'percent': element['pct'] if element['pct'] != 'Unknown' else 0 + } + + +def main(): + """Produces a llvm-cov style JSON summary from a nyc JSON summary.""" + if len(sys.argv) != 3: + sys.stderr.write('Usage: %s \n' % + sys.argv[0]) + return 1 + + with open(sys.argv[1], 'r') as nyc_json_summary_file: + nyc_json_summary = json.load(nyc_json_summary_file) + json_summary = convert(nyc_json_summary) + with open(sys.argv[2], 'w') as json_output_file: + json_output_file.write(json_summary) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/profraw_update.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/profraw_update.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ce1fd86396ed02a03fbeb6a54de1d595c2855b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/profraw_update.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Helper script for upgrading a profraw file to latest version.""" + +from collections import namedtuple +import struct +import subprocess +import sys + +HeaderGeneric = namedtuple('HeaderGeneric', 'magic version') +HeaderVersion9 = namedtuple( + 'HeaderVersion9', + 'BinaryIdsSize DataSize PaddingBytesBeforeCounters CountersSize \ + PaddingBytesAfterCounters NumBitmapBytes PaddingBytesAfterBitmapBytes NamesSize CountersDelta BitmapDelta NamesDelta ValueKindLast' +) + +PROFRAW_MAGIC = 0xff6c70726f667281 + + +def relativize_address(data, offset, databegin, sect_prf_cnts, sect_prf_data): + """Turns an absolute offset into a relative one.""" + value = struct.unpack('Q', data[offset:offset + 8])[0] + if sect_prf_cnts <= value < sect_prf_data: + # If the value is an address in the right section, make it relative. + value = (value - databegin) & 0xffffffffffffffff + value = struct.pack('Q', value) + for i in range(8): + data[offset + i] = value[i] + # address was made relative + return True + # no changes done + return False + + +def upgrade(data, sect_prf_cnts, sect_prf_data): + """Upgrades profraw data, knowing the sections addresses.""" + generic_header = HeaderGeneric._make(struct.unpack('QQ', data[:16])) + if generic_header.magic != PROFRAW_MAGIC: + raise Exception('Bad magic.') + base_version = generic_header.version + + if base_version >= 9: + # Nothing to do. + return data + if base_version < 5 or base_version == 6: + raise Exception('Unhandled version.') + + if generic_header.version == 5: + generic_header = generic_header._replace(version=7) + # Upgrade from version 5 to 7 by adding binaryids field. + data = data[:8] + struct.pack('Q', generic_header.version) + struct.pack( + 'Q', 0) + data[16:] + if generic_header.version == 7: + # cf https://reviews.llvm.org/D111123 + generic_header = generic_header._replace(version=8) + data = data[:8] + struct.pack('Q', generic_header.version) + data[16:] + if generic_header.version == 8: + # see https://reviews.llvm.org/D138846 + generic_header = generic_header._replace(version=9) + # Upgrade from version 8 to 9 by adding NumBitmapBytes, PaddingBytesAfterBitmapBytes and BitmapDelta fields. + data = data[:8] + struct.pack( + 'Q', generic_header.version) + data[16:56] + struct.pack( + 'QQ', 0, 0) + data[56:72] + struct.pack('Q', 0) + data[72:] + + v9_header = HeaderVersion9._make(struct.unpack('QQQQQQQQQQQQ', data[16:112])) + + if base_version <= 8 and v9_header.BinaryIdsSize % 8 != 0: + # Adds padding for binary ids. + # cf commit b9f547e8e51182d32f1912f97a3e53f4899ea6be + # cf https://reviews.llvm.org/D110365 + padlen = 8 - (v9_header.BinaryIdsSize % 8) + v7_header = v9_header._replace(BinaryIdsSize=v9_header.BinaryIdsSize + + padlen) + data = data[:16] + struct.pack('Q', v9_header.BinaryIdsSize) + data[24:] + data = data[:112 + v9_header.BinaryIdsSize] + bytes( + padlen) + data[112 + v9_header.BinaryIdsSize:] + + if base_version <= 8: + offset = 112 + v9_header.BinaryIdsSize + for d in range(v9_header.DataSize): + # Add BitmapPtr and aligned u32(NumBitmapBytes) + data = data[:offset + 3 * 8] + struct.pack( + 'Q', 0) + data[offset + 3 * 8:offset + 6 * 8] + struct.pack( + 'Q', 0) + data[offset + 6 * 8:] + value = struct.unpack('Q', + data[offset + 2 * 8:offset + 3 * 8])[0] - 16 * d + data = data[:offset + 2 * 8] + struct.pack('Q', + value) + data[offset + 3 * 8:] + offset += 8 * 8 + + if base_version >= 8: + # Nothing more to do. + return data + + # Last changes are relaed to bump from 7 to version 8 making CountersPtr relative. + dataref = sect_prf_data + # 80 is offset of CountersDelta. + if not relativize_address(data, 80, dataref, sect_prf_cnts, sect_prf_data): + return data + + offset = 112 + v9_header.BinaryIdsSize + # This also works for C+Rust binaries compiled with + # clang-14/rust-nightly-clang-13. + for _ in range(v9_header.DataSize): + # 16 is the offset of CounterPtr in ProfrawData structure. + relativize_address(data, offset + 16, dataref, sect_prf_cnts, sect_prf_data) + # We need this because of CountersDelta -= sizeof(*SrcData); + # seen in __llvm_profile_merge_from_buffer. + dataref += 44 + 2 * (v9_header.ValueKindLast + 1) + if was8: + #profraw9 added RelativeBitmapPtr and NumBitmapBytes (8+4 rounded up to 16) + dataref -= 16 + # This is the size of one ProfrawData structure. + offset += 44 + 2 * (v9_header.ValueKindLast + 1) + + return data + + +def main(): + """Helper script for upgrading a profraw file to latest version.""" + if len(sys.argv) < 3: + sys.stderr.write('Usage: %s options? ...\n' % sys.argv[0]) + return 1 + + # First find llvm profile sections addresses in the elf, quick and dirty. + process = subprocess.Popen(['readelf', '-S', sys.argv[1]], + stdout=subprocess.PIPE) + output, err = process.communicate() + if err: + print('readelf failed') + return 2 + for line in iter(output.split(b'\n')): + if b'__llvm_prf_cnts' in line: + sect_prf_cnts = int(line.split()[3], 16) + elif b'__llvm_prf_data' in line: + sect_prf_data = int(line.split()[3], 16) + + out_name = "default.profup" + in_place = False + start = 2 + if sys.argv[2] == "-i": + in_place = True + start = start + 1 + elif sys.argv[2] == "-o": + out_name = sys.argv[3] + start = 4 + + if len(sys.argv) < start: + sys.stderr.write('Usage: %s options ...\n' % sys.argv[0]) + return 1 + + for i in range(start, len(sys.argv)): + # Then open and read the input profraw file. + with open(sys.argv[i], 'rb') as input_file: + profraw_base = bytearray(input_file.read()) + # Do the upgrade, returning a bytes object. + profraw_latest = upgrade(profraw_base, sect_prf_cnts, sect_prf_data) + # Write the output to the file given to the command line. + if in_place: + out_name = sys.argv[i] + with open(out_name, 'wb') as output_file: + output_file.write(profraw_latest) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5f627128455ed4d5d70c166ef8c7fe218ace99 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py @@ -0,0 +1,181 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Helper to manage coverage.py related operations. Does two main +things: (1) pass commands into the coverage.py library and (2) +translate .coverage created from a pyinstaller executable into +paths that match local files. This is needed for html report creation. +""" +import os +import re +import json +import sys +from coverage.cmdline import main as coverage_main +from coverage.data import CoverageData + + +def should_exclude_file(filepath): + """Returns whether the path should be excluded from the coverage report.""" + # Skip all atheris code + if "atheris" in filepath: + return True + + # Filter out all standard python libraries + if ('/usr/local/lib/python' in filepath and + 'site-packages' not in filepath and 'dist-packages' not in filepath): + return True + + # Avoid all PyInstaller modules. + if 'PyInstaller' in filepath: + return True + + return False + + +def translate_lines(cov_data, new_cov_data, all_file_paths): + """ + Translate lines in a .coverage file created by coverage.py such that + the file paths points to local files instead. This is needed when collecting + coverage from executables created by pyinstaller. + """ + for pyinstaller_file_path in cov_data.measured_files(): + stripped_py_file_path = pyinstaller_file_path + if stripped_py_file_path.startswith('/tmp/_MEI'): + stripped_py_file_path = '/'.join(stripped_py_file_path.split('/')[3:]) + if stripped_py_file_path.startswith('/out/'): + stripped_py_file_path = stripped_py_file_path.replace('/out/', '') + + # Check if this file exists in our file paths: + for local_file_path in all_file_paths: + if should_exclude_file(local_file_path): + continue + if local_file_path.endswith(stripped_py_file_path): + print('Found matching: %s' % (local_file_path)) + new_cov_data.add_lines( + {local_file_path: cov_data.lines(pyinstaller_file_path)}) + + +def translate_coverage(all_file_paths): + """ + Translate pyinstaller-generated file paths in .coverage (produced by + coverage.py) into local file paths. Place result in .new_coverage. + """ + covdata_pre_translation = CoverageData('.coverage') + covdata_post_translation = CoverageData('.new_coverage') + + covdata_pre_translation.read() + translate_lines(covdata_pre_translation, covdata_post_translation, + all_file_paths) + covdata_post_translation.write() + + +def convert_coveragepy_cov_to_summary_json(src, dst): + """ + Converts a json file produced by coveragepy into a summary.json file + similary to llvm-cov output. `src` is the source coveragepy json file, + `dst` is the destination json file, which will be overwritten. + """ + dst_dict = {'data': [{'files': {}}]} + lines_covered = 0 + lines_count = 0 + with open(src, "r") as src_f: + src_json = json.loads(src_f.read()) + if 'files' in src_json: + for elem in src_json.get('files'): + if 'summary' not in src_json['files'][elem]: + continue + src_dict = src_json['files'][elem]['summary'] + count = src_dict['covered_lines'] + src_dict['missing_lines'] + covered = src_dict['covered_lines'] + notcovered = src_dict['missing_lines'] + percent = src_dict['percent_covered'] + + # Accumulate line coverage + lines_covered += covered + lines_count += count + + dst_dict['data'][0]['files'][elem] = { + 'summary': { + 'lines': { + 'count': count, + 'covered': covered, + 'notcovered': notcovered, + 'percent': percent + } + } + } + if lines_count > 0: + lines_covered_percent = lines_covered / lines_count + else: + lines_covered_percent = 0.0 + dst_dict['data'][0]['totals'] = { + 'branches': { + 'count': 0, + 'covered': 0, + 'notcovered': 0, + 'percent': 0.0 + }, + 'functions': { + 'count': 0, + 'covered': 0, + 'percent': 0.0 + }, + 'instantiations': { + 'count': 0, + 'covered': 0, + 'percent': 0.0 + }, + 'lines': { + 'count': lines_count, + 'covered': lines_covered, + 'percent': lines_covered_percent + }, + 'regions': { + 'count': 0, + 'covered': 0, + 'notcovered': 0, + 'percent': 0.0 + } + } + + with open(dst, 'w') as dst_f: + dst_f.write(json.dumps(dst_dict)) + + +def main(): + """ + Main handler. + """ + if sys.argv[1] == 'translate': + print('Translating the coverage') + files_path = sys.argv[2] + all_file_paths = list() + for root, _, files in os.walk(files_path): + for relative_file_path in files: + abs_file_path = os.path.abspath(os.path.join(root, relative_file_path)) + all_file_paths.append(abs_file_path) + print('Done with path walk') + translate_coverage(all_file_paths) + elif sys.argv[1] == 'convert-to-summary-json': + src = sys.argv[2] + dst = sys.argv[3] + convert_coveragepy_cov_to_summary_json(src, dst) + else: + # Pass commands into coverage package + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(coverage_main()) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/rcfilt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/rcfilt new file mode 100644 index 0000000000000000000000000000000000000000..1c621100c3be0ae4f50d0e4cf817120b8f169b5a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/rcfilt @@ -0,0 +1,21 @@ +#!/bin/bash -u +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Symbol demangling for both C++ and Rust +# +################################################################################ + +# simply pipe +rustfilt | c++filt -n diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/reproduce b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/reproduce new file mode 100644 index 0000000000000000000000000000000000000000..2c074d05e51bd0068f5ed4795159cc69eda0426f --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/reproduce @@ -0,0 +1,34 @@ +#!/bin/bash -eux +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +FUZZER=$1 +shift + +if [ ! -v TESTCASE ]; then + TESTCASE="/testcase" +fi + +if [ ! -f $TESTCASE ]; then + echo "Error: $TESTCASE not found, use: docker run -v :$TESTCASE ..." + exit 1 +fi + +export RUN_FUZZER_MODE="interactive" +export FUZZING_ENGINE="libfuzzer" +export SKIP_SEED_CORPUS="1" + +run_fuzzer $FUZZER $@ $TESTCASE diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/run_fuzzer b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/run_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..6e55917cb62bf43b524eed257f585f54154c3362 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/run_fuzzer @@ -0,0 +1,228 @@ +#!/bin/bash -eu +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Fuzzer runner. Appends .options arguments and seed corpus to users args. +# Usage: $0 + +sysctl -w vm.mmap_rnd_bits=28 + +export PATH=$OUT:$PATH +cd $OUT + +DEBUGGER=${DEBUGGER:-} + +FUZZER=$1 +shift + +# This env var is set by CIFuzz. CIFuzz fills this directory with the corpus +# from ClusterFuzz. +CORPUS_DIR=${CORPUS_DIR:-} +if [ -z "$CORPUS_DIR" ] +then + CORPUS_DIR="/tmp/${FUZZER}_corpus" + rm -rf $CORPUS_DIR && mkdir -p $CORPUS_DIR +fi + +SANITIZER=${SANITIZER:-} +if [ -z $SANITIZER ]; then + # If $SANITIZER is not specified (e.g. calling from `reproduce` command), it + # is not important and can be set to any value. + SANITIZER="default" +fi + +if [[ "$RUN_FUZZER_MODE" = interactive ]]; then + FUZZER_OUT="$OUT/${FUZZER}_${FUZZING_ENGINE}_${SANITIZER}_out" +else + FUZZER_OUT="/tmp/${FUZZER}_${FUZZING_ENGINE}_${SANITIZER}_out" +fi + +function get_dictionary() { + local options_file="$FUZZER.options" + local dict_file="$FUZZER.dict" + local dict="" + if [[ -f "$options_file" ]]; then + dict=$(sed -n 's/^\s*dict\s*=\s*\(.*\)/\1/p' "$options_file" | tail -1) + fi + if [[ -z "$dict" && -f "$dict_file" ]]; then + dict="$dict_file" + fi + [[ -z "$dict" ]] && return + if [[ "$FUZZING_ENGINE" = "libfuzzer" ]]; then + printf -- "-dict=%s" "$dict" + elif [[ "$FUZZING_ENGINE" = "afl" ]]; then + printf -- "-x %s" "$dict" + elif [[ "$FUZZING_ENGINE" = "honggfuzz" ]]; then + printf -- "--dict %s" "$dict" + elif [[ "$FUZZING_ENGINE" = "centipede" ]]; then + printf -- "--dictionary %s" "$dict" + else + printf "Unexpected FUZZING_ENGINE: $FUZZING_ENGINE, ignoring\n" >&2 + fi +} + +function get_extra_binaries() { + [[ "$FUZZING_ENGINE" != "centipede" ]] && return + + extra_binaries="$OUT/__centipede_${SANITIZER}/${FUZZER}" + if compgen -G "$extra_binaries" >> /dev/null; then + printf -- "--extra_binaries %s" \""$extra_binaries\"" + fi + +} + +rm -rf $FUZZER_OUT && mkdir -p $FUZZER_OUT + +SEED_CORPUS="${FUZZER}_seed_corpus.zip" + +# TODO: Investigate why this code block is skipped +# by all default fuzzers in bad_build_check. +# They all set SKIP_SEED_CORPUS=1. +if [ -f $SEED_CORPUS ] && [ -z ${SKIP_SEED_CORPUS:-} ]; then + echo "Using seed corpus: $SEED_CORPUS" + unzip -o -d ${CORPUS_DIR}/ $SEED_CORPUS > /dev/null +fi + +OPTIONS_FILE="${FUZZER}.options" +CUSTOM_LIBFUZZER_OPTIONS="" + +if [ -f $OPTIONS_FILE ]; then + custom_asan_options=$(parse_options.py $OPTIONS_FILE asan) + if [ ! -z $custom_asan_options ]; then + export ASAN_OPTIONS="$ASAN_OPTIONS:$custom_asan_options" + fi + + custom_msan_options=$(parse_options.py $OPTIONS_FILE msan) + if [ ! -z $custom_msan_options ]; then + export MSAN_OPTIONS="$MSAN_OPTIONS:$custom_msan_options" + fi + + custom_ubsan_options=$(parse_options.py $OPTIONS_FILE ubsan) + if [ ! -z $custom_ubsan_options ]; then + export UBSAN_OPTIONS="$UBSAN_OPTIONS:$custom_ubsan_options" + fi + + CUSTOM_LIBFUZZER_OPTIONS=$(parse_options.py $OPTIONS_FILE libfuzzer) +fi + +if [[ "$FUZZING_ENGINE" = afl ]]; then + + # Set afl++ environment options. + export ASAN_OPTIONS="$ASAN_OPTIONS:abort_on_error=1:symbolize=0:detect_odr_violation=0:" + export MSAN_OPTIONS="$MSAN_OPTIONS:exit_code=86:symbolize=0" + export UBSAN_OPTIONS="$UBSAN_OPTIONS:symbolize=0" + export AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 + export AFL_SKIP_CPUFREQ=1 + export AFL_TRY_AFFINITY=1 + export AFL_FAST_CAL=1 + export AFL_CMPLOG_ONLY_NEW=1 + export AFL_FORKSRV_INIT_TMOUT=30000 + export AFL_IGNORE_PROBLEMS=1 + export AFL_IGNORE_UNKNOWN_ENVS=1 + + # If $OUT/afl_cmplog.txt is present this means the target was compiled for + # CMPLOG. So we have to add the proper parameters to afl-fuzz. + test -e "$OUT/afl_cmplog.txt" && AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -c $OUT/$FUZZER" + + # If $OUT/afl++.dict we load it as a dictionary for afl-fuzz. + test -e "$OUT/afl++.dict" && AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -x $OUT/afl++.dict" + + # Ensure timeout is a bit larger than 1sec as some of the OSS-Fuzz fuzzers + # are slower than this. + AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -t 5000+" + + # AFL expects at least 1 file in the input dir. + echo input > ${CORPUS_DIR}/input + + CMD_LINE="$OUT/afl-fuzz $AFL_FUZZER_ARGS -i $CORPUS_DIR -o $FUZZER_OUT $(get_dictionary) $* -- $OUT/$FUZZER" + + echo afl++ setup: + env|grep AFL_ + cat "$OUT/afl_options.txt" + +elif [[ "$FUZZING_ENGINE" = honggfuzz ]]; then + + # Honggfuzz expects at least 1 file in the input dir. + echo input > $CORPUS_DIR/input + # --exit_upon_crash: exit whith a first crash seen + # -V: verify crashes + # -R (report): save report file to this location + # -W (working dir): where the crashes go + # -v (verbose): don't use VTE UI, just stderr + # -z: use software-instrumentation of clang (trace-pc-guard....) + # -P: use persistent mode of fuzzing (i.e. LLVMFuzzerTestOneInput) + # -f: location of the initial (and destination) file corpus + # -n: number of fuzzing threads (and processes) + CMD_LINE="$OUT/honggfuzz -n 1 --exit_upon_crash -V -R /tmp/${FUZZER}_honggfuzz.report -W $FUZZER_OUT -v -z -P -f \"$CORPUS_DIR\" $(get_dictionary) $* -- \"$OUT/$FUZZER\"" + + if [[ $(LC_ALL=C grep -P "\x01_LIBHFUZZ_NETDRIVER_BINARY_SIGNATURE_\x02\xFF" "$FUZZER" ) ]]; then + # Honggfuzz Netdriver port. This must match the port in Clusterfuzz. + export HFND_TCP_PORT=8666 + fi +elif [[ "$FUZZING_ENGINE" = centipede ]]; then + + # Create the work and corpus directory for Centipede. + CENTIPEDE_WORKDIR="${CENTIPEDE_WORKDIR:-$OUT}" + + # Centipede only saves crashes to crashes/ in workdir. + rm -rf $FUZZER_OUT + + # --workdir: Dir that stores corpus&features in Centipede's own format. + # --corpus_dir: Location of the initial (and destination) file corpus. + # --fork_server: Execute the target(s) via the fork server. + # Run in fork mode to continue fuzzing indefinitely in case of + # OOMs, timeouts, and crashes. + # --exit_on_crash=0: Do not exit on crash. + # --timeout=1200: The process that executes target binary will abort + # if an input runs >= 1200s. + # --rss_limit_mb=0: Disable RSS limit. + # --address_space_limit_mb=0: No address space limit. + # --binary: The target binary under test without sanitizer. + # --extra_binary: The target binaries under test with sanitizers. + CMD_LINE="$OUT/centipede --workdir=$CENTIPEDE_WORKDIR --corpus_dir=\"$CORPUS_DIR\" --fork_server=1 --exit_on_crash=1 --timeout=1200 --rss_limit_mb=4096 --address_space_limit_mb=5120 $(get_dictionary) --binary=\"$OUT/${FUZZER}\" $(get_extra_binaries) $*" +else + + CMD_LINE="$OUT/$FUZZER $FUZZER_ARGS $*" + + if [ -z ${SKIP_SEED_CORPUS:-} ]; then + CMD_LINE="$CMD_LINE $CORPUS_DIR" + fi + + if [[ ! -z ${CUSTOM_LIBFUZZER_OPTIONS} ]]; then + CMD_LINE="$CMD_LINE $CUSTOM_LIBFUZZER_OPTIONS" + fi + + if [[ ! "$CMD_LINE" =~ "-dict=" ]]; then + if [ -f "$FUZZER.dict" ]; then + CMD_LINE="$CMD_LINE -dict=$FUZZER.dict" + fi + fi + + CMD_LINE="$CMD_LINE < /dev/null" + +fi + +echo $CMD_LINE + +# Unset OUT so the fuzz target can't rely on it. +unset OUT + +if [ ! -z "$DEBUGGER" ]; then + CMD_LINE="$DEBUGGER $CMD_LINE" +fi + +bash -c "$CMD_LINE" + diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/ruzzy b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/ruzzy new file mode 100644 index 0000000000000000000000000000000000000000..663e8f5b9c4288cde4e1c422343ca595e4afaab6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/ruzzy @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +ASAN_OPTIONS="allocator_may_return_null=1:detect_leaks=0:use_sigaltstack=0" LD_PRELOAD=$(ruby -e 'require "ruzzy"; print Ruzzy::ASAN_PATH') \ + ruby $@ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/targets_list b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/targets_list new file mode 100644 index 0000000000000000000000000000000000000000..95615c81118c7991cea1c3e800ea9b5c304040ed --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/targets_list @@ -0,0 +1,10 @@ +#!/bin/bash + +for binary in $(find $OUT/ -executable -type f); do + [[ "$binary" != *.so ]] || continue + [[ $(basename "$binary") != jazzer_driver* ]] || continue + file "$binary" | grep -e ELF -e "shell script" > /dev/null 2>&1 || continue + grep "LLVMFuzzerTestOneInput" "$binary" > /dev/null 2>&1 || continue + + basename "$binary" +done diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_one.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_one.py new file mode 100644 index 0000000000000000000000000000000000000000..e391ec96dcc3b9b74fd2049f88806c2578df5ff8 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/base-runner/test_one.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Does bad_build_check on a fuzz target in $OUT.""" +import os +import sys + +import test_all + + +def test_one(fuzz_target): + """Does bad_build_check on one fuzz target. Returns True on success.""" + with test_all.use_different_out_dir(): + fuzz_target_path = os.path.join(os.environ['OUT'], fuzz_target) + result = test_all.do_bad_build_check(fuzz_target_path) + if result.returncode != 0: + sys.stdout.buffer.write(result.stdout + result.stderr + b'\n') + return False + return True + + +def main(): + """Does bad_build_check on one fuzz target. Returns 1 on failure, 0 on + success.""" + if len(sys.argv) != 2: + print('Usage: %d ', sys.argv[0]) + return 1 + + fuzz_target_binary = sys.argv[1] + return 0 if test_one(fuzz_target_binary) else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..164c890e91849dc1374c71f0320896f098c5ad97 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml @@ -0,0 +1,55 @@ +# action.yml +name: 'build-fuzzers' +description: "Builds an OSS-Fuzz project's fuzzers." +inputs: + oss-fuzz-project-name: + description: 'Name of the corresponding OSS-Fuzz project.' + required: true + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + allowed-broken-targets-percentage: + description: 'The percentage of broken targets allowed in bad_build_check.' + required: false + sanitizer: + description: 'The sanitizer to build the fuzzers with.' + default: 'address' + architecture: + description: 'The architecture used to build the fuzzers.' + default: 'x86_64' + project-src-path: + description: "The path to the project's source code checkout." + required: false + bad-build-check: + description: "Whether or not OSS-Fuzz's check for bad builds should be done." + required: false + default: true + keep-unaffected-fuzz-targets: + description: "Whether to keep unaffected fuzzers or delete them." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false +runs: + using: 'docker' + image: '../../../build_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + DRY_RUN: ${{ inputs.dry-run}} + ALLOWED_BROKEN_TARGETS_PERCENTAGE: ${{ inputs.allowed-broken-targets-percentage}} + SANITIZER: ${{ inputs.sanitizer }} + ARCHITECTURE: ${{ inputs.architecture }} + PROJECT_SRC_PATH: ${{ inputs.project-src-path }} + LOW_DISK_SPACE: 'True' + BAD_BUILD_CHECK: ${{ inputs.bad-build-check }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + KEEP_UNAFFECTED_FUZZ_TARGETS: ${{ inputs.keep-unaffected-fuzz-targets }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..197aed2b02e4af2b3725040a5ce46f258337af82 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml @@ -0,0 +1,82 @@ +# action.yml +name: 'run-fuzzers' +description: 'Runs fuzz target binaries for a specified length of time.' +inputs: + oss-fuzz-project-name: + description: 'The OSS-Fuzz project name.' + required: true + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + fuzz-seconds: + description: 'The total time allotted for fuzzing in seconds.' + required: true + default: 600 + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + sanitizer: + description: 'The sanitizer to run the fuzzers with.' + default: 'address' + mode: + description: | + The mode to run the fuzzers with ("code-change", "batch", "coverage", or "prune"). + "code-change" is for fuzzing a pull request or commit. + "batch" is for non-interactive fuzzing of an entire project. + "coverage" is for coverage generation. + "prune" is for corpus pruning. + required: false + default: 'code-change' + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + report-unreproducible-crashes: + description: 'If True, then unreproducible crashes will be reported.' + required: false + default: False + minimize-crashes: + description: 'If True, reportable crashes will be minimized.' + required: false + default: False + parallel-fuzzing: + description: "Whether to use all available cores for fuzzing." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false + report-timeouts: + description: "Whether to report fails due to timeout." + required: false + default: true + report-ooms: + description: "Whether to report fails due to OOM." + required: false + default: true +runs: + using: 'docker' + image: '../../../run_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + FUZZ_SECONDS: ${{ inputs.fuzz-seconds }} + DRY_RUN: ${{ inputs.dry-run}} + SANITIZER: ${{ inputs.sanitizer }} + MODE: ${{ inputs.mode }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + REPORT_UNREPRODUCIBLE_CRASHES: ${{ inputs.report-unreproducible-crashes }} + MINIMIZE_CRASHES: ${{ inputs.minimize-crashes }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + PARALLEL_FUZZING: ${{ inputs.parallel-fuzzing }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} + REPORT_TIMEOUTS: ${{ inputs.report-timeouts }} + REPORT_OOMS: ${{ inputs.report-ooms}} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f3ada4f2762c6e6ddf058b6be9a67b31c154594 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile @@ -0,0 +1,44 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +FROM ghcr.io/aixcc-finals/base-runner + +RUN apt-get update && \ + apt-get install -y systemd && \ + wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_20.10.8~3-0~ubuntu-focal_amd64.deb -O /tmp/docker-ce.deb && \ + dpkg -i /tmp/docker-ce.deb && \ + rm /tmp/docker-ce.deb + +ENV PATH=/opt/gcloud/google-cloud-sdk/bin/:$PATH +ENV OSS_FUZZ_ROOT=/opt/oss-fuzz + +# Do this step before copying to make rebuilding faster when developing. +COPY ./infra/cifuzz/requirements.txt /tmp/requirements.txt +RUN python3 -m pip install -r /tmp/requirements.txt && rm /tmp/requirements.txt + +ADD . ${OSS_FUZZ_ROOT} +# Don't use the default npm location since jazzer.js can break us. +# This means javascript needed by cifuzz/clusterfuzzlite must be executed in +# OSS_FUZZ_ROOT. +RUN cd ${OSS_FUZZ_ROOT} && npm install ${OSS_FUZZ_ROOT}/infra/cifuzz + + +ENV PYTHONUNBUFFERED=1 + +# Python file to execute when the docker container starts up. +# We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var, +# just expand to '/opt/oss-fuzz'. +ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py"] diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5b782e46d4d3116b628143666db8f3f6406ace0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml @@ -0,0 +1,75 @@ +# action.yml +name: 'build-fuzzers' +description: "Builds an OSS-Fuzz project's fuzzers." +inputs: + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + allowed-broken-targets-percentage: + description: 'The percentage of broken targets allowed in bad_build_check.' + required: false + sanitizer: + description: 'The sanitizer to build the fuzzers with.' + default: 'address' + project-src-path: + description: "The path to the project's source code checkout." + required: false + bad-build-check: + description: "Whether or not OSS-Fuzz's check for bad builds should be done." + required: false + default: true + keep-unaffected-fuzz-targets: + description: "Whether to keep unaffected fuzzers or delete them." + required: false + default: false + storage-repo: + description: | + The git repo to use for storing certain artifacts from fuzzing. + required: false + storage-repo-branch: + description: | + The branch of the git repo to use for storing certain artifacts from + fuzzing. + required: false + storage-repo-branch-coverage: + description: | + The branch of the git repo to use for storing coverage reports. + required: false + upload-build: + description: | + If set, will upload the build. + default: false + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false +runs: + using: 'docker' + image: '../../../build_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + DRY_RUN: ${{ inputs.dry-run}} + ALLOWED_BROKEN_TARGETS_PERCENTAGE: ${{ inputs.allowed-broken-targets-percentage}} + SANITIZER: ${{ inputs.sanitizer }} + PROJECT_SRC_PATH: ${{ inputs.project-src-path }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + BAD_BUILD_CHECK: ${{ inputs.bad-build-check }} + UPLOAD_BUILD: ${{ inputs.upload-build }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + KEEP_UNAFFECTED_FUZZ_TARGETS: ${{ inputs.keep-unaffected-fuzz-targets }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ca11e448a0d86d74112eac5133783b57dbe55c0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml @@ -0,0 +1,97 @@ +# action.yml +name: 'run-fuzzers' +description: 'Runs fuzz target binaries for a specified length of time.' +inputs: + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + fuzz-seconds: + description: 'The total time allotted for fuzzing in seconds.' + required: true + default: 600 + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + sanitizer: + description: 'The sanitizer to run the fuzzers with.' + default: 'address' + mode: + description: | + The mode to run the fuzzers with ("code-change", "batch", "coverage", or "prune"). + "code-change" is for fuzzing a pull request or commit. + "batch" is for non-interactive fuzzing of an entire project. + "coverage" is for coverage generation. + "prune" is for corpus pruning. + required: false + default: 'code-change' + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: true + storage-repo: + description: | + The git repo to use for storing certain artifacts from fuzzing. + required: false + storage-repo-branch: + description: | + The branch of the git repo to use for storing certain artifacts from + fuzzing. + default: main + required: false + storage-repo-branch-coverage: + description: | + The branch of the git repo to use for storing coverage reports. + default: gh-pages + required: false + report-unreproducible-crashes: + description: 'If True, then unreproducible crashes will be reported.' + required: false + default: false + minimize-crashes: + description: 'If True, reportable crashes will be minimized.' + required: false + default: False + parallel-fuzzing: + description: "Whether to use all available cores for fuzzing." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false + report-timeouts: + description: "Whether to report fails due to timeout." + required: false + default: true + report-ooms: + description: "Whether to report fails due to OOM." + required: false + default: true +runs: + using: 'docker' + image: '../../../run_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + FUZZ_SECONDS: ${{ inputs.fuzz-seconds }} + DRY_RUN: ${{ inputs.dry-run}} + SANITIZER: ${{ inputs.sanitizer }} + MODE: ${{ inputs.mode }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + GIT_STORE_REPO: ${{ inputs.storage-repo }} + GIT_STORE_BRANCH: ${{ inputs.storage-repo-branch }} + GIT_STORE_BRANCH_COVERAGE: ${{ inputs.storage-repo-branch-coverage }} + REPORT_UNREPRODUCIBLE_CRASHES: ${{ inputs.report-unreproducible-crashes }} + MINIMIZE_CRASHES: ${{ inputs.minimize-crashes }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + PARALLEL_FUZZING: ${{ inputs.parallel-fuzzing }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} + REPORT_TIMEOUTS: ${{ inputs.report-timeouts }} + REPORT_OOMS: ${{ inputs.report-ooms}} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bce4271ce61303b8567beee2cc6343646be2aeda --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/__init__.py @@ -0,0 +1,54 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for a generic filestore.""" + + +class FilestoreError(Exception): + """Error using the filestore.""" + + +# pylint: disable=unused-argument,no-self-use +class BaseFilestore: + """Base class for a filestore.""" + + def __init__(self, config): + self.config = config + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + raise NotImplementedError('Child class must implement method.') + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + raise NotImplementedError('Child class must implement method.') + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + raise NotImplementedError('Child class must implement method.') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddea132661e3acae27eb5abff61f1432eb65ba5 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py @@ -0,0 +1,107 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Filestore implementation using a filesystem directory.""" +import logging +import os +import shutil +import subprocess +import sys + +from distutils import dir_util + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore + + +def recursive_list_dir(directory): + """Returns list of all files in |directory|, including those in + subdirectories.""" + files = [] + for root, _, filenames in os.walk(directory): + for filename in filenames: + files.append(os.path.join(root, filename)) + return files + + +class FilesystemFilestore(filestore.BaseFilestore): + """Filesystem implementation using a filesystem directory.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._filestore_root_dir = self.config.platform_conf.filestore_root_dir + + def _get_filestore_path(self, name, prefix_dir): + """Returns the filesystem path in the filestore for |name| and + |prefix_dir|.""" + return os.path.join(self._filestore_root_dir, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + filestore_path = self._get_filestore_path(name, prefix) + if os.path.exists(filestore_path): + initial_files = set(recursive_list_dir(filestore_path)) + else: + initial_files = set() + + # Make directory and any parents. + os.makedirs(filestore_path, exist_ok=True) + copied_files = set(dir_util.copy_tree(directory, filestore_path)) + if not delete: + return True + + files_to_delete = initial_files - copied_files + for file_path in files_to_delete: + os.remove(file_path) + return True + + def _download_directory(self, name, dst_directory, prefix): + filestore_path = self._get_filestore_path(name, prefix) + return dir_util.copy_tree(filestore_path, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, directory, self.CRASHES_DIR) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..636ed693f4357f160ad14e3ccadd6ea07eddb38b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py @@ -0,0 +1,158 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for a git based filestore.""" + +import logging +import os +import shutil +import subprocess +import sys +import tempfile + +import filestore + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +sys.path.append(INFRA_DIR) + +import retry + +_PUSH_RETRIES = 3 +_PUSH_BACKOFF = 1 +_GIT_EMAIL = 'cifuzz@clusterfuzz.com' +_GIT_NAME = 'CIFuzz' +_CORPUS_DIR = 'corpus' +_COVERAGE_DIR = 'coverage' + + +def git_runner(repo_path): + """Returns a gits runner for the repo_path.""" + + def func(*args): + return subprocess.check_call(('git', '-C', repo_path) + args) + + return func + + +# pylint: disable=unused-argument,no-self-use +class GitFilestore(filestore.BaseFilestore): + """Generic git filestore. This still relies on another filestore provided by + the CI for larger artifacts or artifacts which make sense to be included as + the result of a workflow run.""" + + def __init__(self, config, ci_filestore): + super().__init__(config) + self.repo_path = tempfile.mkdtemp() + self._git = git_runner(self.repo_path) + self._clone(self.config.git_store_repo) + + self._ci_filestore = ci_filestore + + def __del__(self): + shutil.rmtree(self.repo_path) + + def _clone(self, repo_url): + """Clones repo URL.""" + self._git('clone', repo_url, '.') + self._git('config', '--local', 'user.email', _GIT_EMAIL) + self._git('config', '--local', 'user.name', _GIT_NAME) + + def _reset_git(self, branch): + """Resets the git repo.""" + self._git('fetch', 'origin') + try: + self._git('checkout', '-B', branch, 'origin/' + branch) + self._git('reset', '--hard', 'HEAD') + except subprocess.CalledProcessError: + self._git('checkout', '--orphan', branch) + + self._git('clean', '-fxd') + + # pylint: disable=too-many-arguments + @retry.wrap(_PUSH_RETRIES, _PUSH_BACKOFF) + def _upload_to_git(self, + message, + branch, + upload_path, + local_path, + replace=False): + """Uploads a directory to git. If `replace` is True, then existing contents + in the upload_path is deleted.""" + self._reset_git(branch) + + full_repo_path = os.path.join(self.repo_path, upload_path) + if replace and os.path.exists(full_repo_path): + shutil.rmtree(full_repo_path) + + shutil.copytree(local_path, full_repo_path, dirs_exist_ok=True) + self._git('add', '.') + try: + self._git('commit', '-m', message) + except subprocess.CalledProcessError: + logging.debug('No changes, skipping git push.') + return + + self._git('push', 'origin', branch) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return self._ci_filestore.upload_crashes(name, directory) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + self._upload_to_git('Corpus upload', + self.config.git_store_branch, + os.path.join(_CORPUS_DIR, name), + directory, + replace=replace) + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + return self._ci_filestore.upload_build(name, directory) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + self._upload_to_git('Coverage upload', + self.config.git_store_branch_coverage, + os.path.join(_COVERAGE_DIR, name), + directory, + replace=True) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + self._reset_git(self.config.git_store_branch) + path = os.path.join(self.repo_path, _CORPUS_DIR, name) + if not os.path.exists(path): + logging.debug('Corpus does not exist at %s.', path) + return False + + shutil.copytree(path, dst_directory, dirs_exist_ok=True) + return True + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._ci_filestore.download_build(name, dst_directory) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + self._reset_git(self.config.git_store_branch_coverage) + path = os.path.join(self.repo_path, _COVERAGE_DIR, name) + if not os.path.exists(path): + logging.debug('Coverage does not exist at %s.', path) + return False + + shutil.copytree(path, dst_directory, dirs_exist_ok=True) + return True diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py new file mode 100644 index 0000000000000000000000000000000000000000..56be23bacd0fdf75c5f9bf7fb0fe475a2d48b6b6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py @@ -0,0 +1,122 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for git.""" +import filecmp +import os +import tempfile +import subprocess +import sys +import unittest +from unittest import mock + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +sys.path.append(INFRA_DIR) + +from filestore import git +import test_helpers + +# pylint: disable=protected-access,no-self-use + + +class GitFilestoreTest(unittest.TestCase): + """Tests for GitFilestore.""" + + def setUp(self): + self.git_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.git_dir.cleanup) + + self.local_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.local_dir.cleanup) + + self.download_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.download_dir.cleanup) + + with open(os.path.join(self.local_dir.name, 'a'), 'w') as handle: + handle.write('') + + os.makedirs(os.path.join(self.local_dir.name, 'b')) + + with open(os.path.join(self.local_dir.name, 'b', 'c'), 'w') as handle: + handle.write('') + + self.git_repo = git.git_runner(self.git_dir.name) + self.git_repo('init', '--bare') + + self.config = test_helpers.create_run_config( + git_store_repo='file://' + self.git_dir.name, + git_store_branch='main', + git_store_branch_coverage='cov-branch') + + self.mock_ci_filestore = mock.MagicMock() + self.git_store = git.GitFilestore(self.config, self.mock_ci_filestore) + + def assert_dirs_same(self, first, second): + """Asserts two dirs are the same.""" + dcmp = filecmp.dircmp(first, second) + if dcmp.diff_files or dcmp.left_only or dcmp.right_only: + return False + + return all( + self.assert_dirs_same(os.path.join(first, subdir), + os.path.join(second, subdir)) + for subdir in dcmp.common_dirs) + + def get_repo_filelist(self, branch): + """Get files in repo.""" + return subprocess.check_output([ + 'git', '-C', self.git_dir.name, 'ls-tree', '-r', '--name-only', branch + ]).decode().splitlines() + + def test_upload_download_corpus(self): + """Tests uploading and downloading corpus.""" + self.git_store.upload_corpus('target', self.local_dir.name) + self.git_store.download_corpus('target', self.download_dir.name) + self.assert_dirs_same(self.local_dir.name, self.download_dir.name) + + self.assertCountEqual([ + 'corpus/target/a', + 'corpus/target/b/c', + ], self.get_repo_filelist('main')) + + def test_upload_download_coverage(self): + """Tests uploading and downloading corpus.""" + self.git_store.upload_coverage('latest', self.local_dir.name) + self.git_store.download_coverage('latest', self.download_dir.name) + self.assert_dirs_same(self.local_dir.name, self.download_dir.name) + + self.assertCountEqual([ + 'coverage/latest/a', + 'coverage/latest/b/c', + ], self.get_repo_filelist('cov-branch')) + + def test_upload_crashes(self): + """Tests uploading crashes.""" + self.git_store.upload_crashes('current', self.local_dir.name) + self.mock_ci_filestore.upload_crashes.assert_called_with( + 'current', self.local_dir.name) + + def test_upload_build(self): + """Tests uploading build.""" + self.git_store.upload_build('sanitizer', self.local_dir.name) + self.mock_ci_filestore.upload_build.assert_called_with( + 'sanitizer', self.local_dir.name) + + def test_download_build(self): + """Tests downloading build.""" + self.git_store.download_build('sanitizer', self.download_dir.name) + self.mock_ci_filestore.download_build.assert_called_with( + 'sanitizer', self.download_dir.name) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4750a39b9709d49b9f207321480147b1e1d75476 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py @@ -0,0 +1,179 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Implementation of a filestore using Github actions artifacts.""" +import logging +import os +import shutil +import sys +import tarfile +import tempfile + +# pylint: disable=wrong-import-position,import-error +INFRA_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, + os.path.pardir)) +sys.path.append(INFRA_DIR) +OSS_FUZZ_ROOT_DIR = os.path.dirname(INFRA_DIR) + +import utils +import http_utils +import filestore +from filestore.github_actions import github_api + +UPLOAD_JS = os.path.join(os.path.dirname(__file__), 'upload.js') + + +def tar_directory(directory, archive_path): + """Tars a |directory| and stores archive at |archive_path|. |archive_path| + must end in .tar""" + assert archive_path.endswith('.tar') + # Do this because make_archive will append the extension to archive_path. + archive_path = os.path.splitext(archive_path)[0] + + root_directory = os.path.abspath(directory) + shutil.make_archive(archive_path, + 'tar', + root_dir=root_directory, + base_dir='./') + + +class GithubActionsFilestore(filestore.BaseFilestore): + """Implementation of BaseFilestore using Github actions artifacts. Relies on + github_actions_toolkit for using the GitHub actions API and the github_api + module for using GitHub's standard API. We need to use both because the GitHub + actions API is the only way to upload an artifact but it does not support + downloading artifacts from other runs. The standard GitHub API does support + this however.""" + + ARTIFACT_PREFIX = 'cifuzz-' + BUILD_PREFIX = 'build-' + CRASHES_PREFIX = 'crashes-' + CORPUS_PREFIX = 'corpus-' + COVERAGE_PREFIX = 'coverage-' + + def __init__(self, config): + super().__init__(config) + self.github_api_http_headers = github_api.get_http_auth_headers(config) + + def _get_artifact_name(self, name): + """Returns |name| prefixed with |self.ARITFACT_PREFIX| if it isn't already + prefixed. Otherwise returns |name|.""" + if name.startswith(self.ARTIFACT_PREFIX): + return name + return f'{self.ARTIFACT_PREFIX}{name}' + + def _upload_directory(self, name, directory): # pylint: disable=no-self-use + """Uploads |directory| as artifact with |name|.""" + name = self._get_artifact_name(name) + with tempfile.TemporaryDirectory() as temp_dir: + archive_path = os.path.join(temp_dir, name + '.tar') + tar_directory(directory, archive_path) + _raw_upload_directory(name, temp_dir) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return _raw_upload_directory(self.CRASHES_PREFIX + name, directory) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + # Not applicable as the the entire corpus is uploaded under a single + # artifact name. + del replace + return self._upload_directory(self.CORPUS_PREFIX + name, directory) + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + return self._upload_directory(self.BUILD_PREFIX + name, directory) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(self.COVERAGE_PREFIX + name, directory) + + def download_corpus(self, name, dst_directory): # pylint: disable=unused-argument,no-self-use + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_artifact(self.CORPUS_PREFIX + name, dst_directory) + + def _find_artifact(self, name): + """Finds an artifact using the GitHub API and returns it.""" + logging.debug('Listing artifacts.') + artifacts = self._list_artifacts() + artifact = github_api.find_artifact(name, artifacts) + logging.debug('Artifact: %s.', artifact) + return artifact + + def _download_artifact(self, name, dst_directory): + """Downloads artifact with |name| to |dst_directory|. Returns True on + success.""" + name = self._get_artifact_name(name) + + with tempfile.TemporaryDirectory() as temp_dir: + if not self._raw_download_artifact(name, temp_dir): + logging.warning('Could not download artifact: %s.', name) + return False + + artifact_tarfile_path = os.path.join(temp_dir, name + '.tar') + if not os.path.exists(artifact_tarfile_path): + logging.error('Artifact zip did not contain a tarfile.') + return False + + # TODO(jonathanmetzman): Replace this with archive.unpack from + # libClusterFuzz so we can avoid path traversal issues. + with tarfile.TarFile(artifact_tarfile_path) as artifact_tarfile: + artifact_tarfile.extractall(dst_directory) + return True + + def _raw_download_artifact(self, name, dst_directory): + """Downloads the artifact with |name| to |dst_directory|. Returns True on + success. Does not do any untarring or adding prefix to |name|.""" + artifact = self._find_artifact(name) + if not artifact: + logging.warning('Could not find artifact: %s.', name) + return False + download_url = artifact['archive_download_url'] + return http_utils.download_and_unpack_zip( + download_url, dst_directory, headers=self.github_api_http_headers) + + def _list_artifacts(self): + """Returns a list of artifacts.""" + return github_api.list_artifacts(self.config.project_repo_owner, + self.config.project_repo_name, + self.github_api_http_headers) + + def download_build(self, name, dst_directory): + """Downloads the build with name |name| to |dst_directory|.""" + return self._download_artifact(self.BUILD_PREFIX + name, dst_directory) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_artifact(self.COVERAGE_PREFIX + name, dst_directory) + + +def _upload_artifact_with_upload_js(name, artifact_paths, directory): + """Uploads the artifacts in |artifact_paths| that are located in |directory| + to |name|, using the upload.js script.""" + command = [UPLOAD_JS, name, directory] + artifact_paths + _, _, retcode = utils.execute(command, location=OSS_FUZZ_ROOT_DIR) + return retcode == 0 + + +def _raw_upload_directory(name, directory): + """Uploads the artifacts located in |directory| to |name|. Does not do any + tarring or adding prefixes to |name|.""" + # Get file paths. + artifact_paths = [] + for root, _, curr_file_paths in os.walk(directory): + for file_path in curr_file_paths: + artifact_paths.append(os.path.join(root, file_path)) + logging.debug('Artifact paths: %s.', artifact_paths) + return _upload_artifact_with_upload_js(name, artifact_paths, directory) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_actions_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_actions_test.py new file mode 100644 index 0000000000000000000000000000000000000000..90a0b070db61df690ad0781c2fdd63009d1af6a8 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_actions_test.py @@ -0,0 +1,283 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for github_actions.""" +import os +import shutil +import sys +import tarfile +import tempfile +import unittest +from unittest import mock + +from pyfakefs import fake_filesystem_unittest + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.append(INFRA_DIR) + +from filestore import github_actions +import test_helpers + +# pylint: disable=protected-access,no-self-use + + +class GithubActionsFilestoreTest(fake_filesystem_unittest.TestCase): + """Tests for GithubActionsFilestore.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): # pylint: disable=arguments-differ + test_helpers.patch_environ(self) + self.token = 'example githubtoken' + self.owner = 'exampleowner' + self.repo = 'examplerepo' + os.environ['GITHUB_REPOSITORY'] = f'{self.owner}/{self.repo}' + os.environ['GITHUB_EVENT_PATH'] = '/fake' + os.environ['CFL_PLATFORM'] = 'github' + os.environ['GITHUB_WORKSPACE'] = '/workspace' + self.config = test_helpers.create_run_config(token=self.token) + self.local_dir = '/local-dir' + self.testcase = os.path.join(self.local_dir, 'testcase') + + def _get_expected_http_headers(self): + return { + 'Authorization': f'token {self.token}', + 'Accept': 'application/vnd.github.v3+json', + } + + @mock.patch('filestore.github_actions.github_api.list_artifacts') + def test_list_artifacts(self, mock_list_artifacts): + """Tests that _list_artifacts works as intended.""" + filestore = github_actions.GithubActionsFilestore(self.config) + filestore._list_artifacts() + mock_list_artifacts.assert_called_with(self.owner, self.repo, + self._get_expected_http_headers()) + + @mock.patch('logging.warning') + @mock.patch('filestore.github_actions.GithubActionsFilestore._list_artifacts', + return_value=None) + @mock.patch('filestore.github_actions.github_api.find_artifact', + return_value=None) + def test_download_build_no_artifact(self, _, __, mock_warning): + """Tests that download_build returns None and doesn't exception when + find_artifact can't find an artifact.""" + filestore = github_actions.GithubActionsFilestore(self.config) + name = 'name' + build_dir = 'build-dir' + self.assertFalse(filestore.download_build(name, build_dir)) + mock_warning.assert_called_with('Could not download artifact: %s.', + 'cifuzz-build-' + name) + + @mock.patch('logging.warning') + @mock.patch('filestore.github_actions.GithubActionsFilestore._list_artifacts', + return_value=None) + @mock.patch('filestore.github_actions.github_api.find_artifact', + return_value=None) + def test_download_corpus_no_artifact(self, _, __, mock_warning): + """Tests that download_corpus_build returns None and doesn't exception when + find_artifact can't find an artifact.""" + filestore = github_actions.GithubActionsFilestore(self.config) + name = 'name' + dst_dir = 'local-dir' + self.assertFalse(filestore.download_corpus(name, dst_dir)) + mock_warning.assert_called_with('Could not download artifact: %s.', + 'cifuzz-corpus-' + name) + + @mock.patch('filestore.github_actions.tar_directory') + @mock.patch('filestore.github_actions._upload_artifact_with_upload_js') + def test_upload_corpus(self, mock_upload_artifact, mock_tar_directory): + """Test uploading corpus.""" + self._create_local_dir() + + def mock_tar_directory_impl(_, archive_path): + self.fs.create_file(archive_path) + + mock_tar_directory.side_effect = mock_tar_directory_impl + + filestore = github_actions.GithubActionsFilestore(self.config) + filestore.upload_corpus('target', self.local_dir) + self.assert_upload(mock_upload_artifact, mock_tar_directory, + 'corpus-target') + + @mock.patch('filestore.github_actions._upload_artifact_with_upload_js') + def test_upload_crashes(self, mock_upload_artifact): + """Test uploading crashes.""" + self._create_local_dir() + + filestore = github_actions.GithubActionsFilestore(self.config) + filestore.upload_crashes('current', self.local_dir) + mock_upload_artifact.assert_has_calls( + [mock.call('crashes-current', ['/local-dir/testcase'], '/local-dir')]) + + @mock.patch('filestore.github_actions.tar_directory') + @mock.patch('filestore.github_actions._upload_artifact_with_upload_js') + def test_upload_build(self, mock_upload_artifact, mock_tar_directory): + """Test uploading build.""" + self._create_local_dir() + + def mock_tar_directory_impl(_, archive_path): + self.fs.create_file(archive_path) + + mock_tar_directory.side_effect = mock_tar_directory_impl + + filestore = github_actions.GithubActionsFilestore(self.config) + filestore.upload_build('sanitizer', self.local_dir) + self.assert_upload(mock_upload_artifact, mock_tar_directory, + 'build-sanitizer') + + @mock.patch('filestore.github_actions.tar_directory') + @mock.patch('filestore.github_actions._upload_artifact_with_upload_js') + def test_upload_coverage(self, mock_upload_artifact, mock_tar_directory): + """Test uploading coverage.""" + self._create_local_dir() + + def mock_tar_directory_impl(_, archive_path): + self.fs.create_file(archive_path) + + mock_tar_directory.side_effect = mock_tar_directory_impl + + filestore = github_actions.GithubActionsFilestore(self.config) + filestore.upload_coverage('latest', self.local_dir) + self.assert_upload(mock_upload_artifact, mock_tar_directory, + 'coverage-latest') + + def assert_upload(self, mock_upload_artifact, mock_tar_directory, + expected_artifact_name): + """Tests that upload_directory invokes tar_directory and + artifact_client.upload_artifact properly.""" + # Don't assert what second argument will be since it's a temporary + # directory. + self.assertEqual(mock_tar_directory.call_args_list[0][0][0], self.local_dir) + + # Don't assert what second and third arguments will be since they are + # temporary directories. + expected_artifact_name = 'cifuzz-' + expected_artifact_name + self.assertEqual(mock_upload_artifact.call_args_list[0][0][0], + expected_artifact_name) + + # Assert artifacts list contains one tarfile. + artifacts_list = mock_upload_artifact.call_args_list[0][0][1] + self.assertEqual(len(artifacts_list), 1) + self.assertEqual(os.path.basename(artifacts_list[0]), + expected_artifact_name + '.tar') + + def _create_local_dir(self): + """Sets up pyfakefs and creates a corpus directory containing + self.testcase.""" + self.setUpPyfakefs() + self.fs.create_file(self.testcase, contents='hi') + + @mock.patch('filestore.github_actions.GithubActionsFilestore._find_artifact') + @mock.patch('http_utils.download_and_unpack_zip') + def test_download_artifact(self, mock_download_and_unpack_zip, + mock_find_artifact): + """Tests that _download_artifact works as intended.""" + artifact_download_url = 'http://example.com/download' + artifact_listing = { + 'expired': False, + 'name': 'corpus', + 'archive_download_url': artifact_download_url + } + mock_find_artifact.return_value = artifact_listing + + self._create_local_dir() + with tempfile.TemporaryDirectory() as temp_dir: + # Create a tarball. + archive_path = os.path.join(temp_dir, 'cifuzz-corpus.tar') + github_actions.tar_directory(self.local_dir, archive_path) + + artifact_download_dst_dir = os.path.join(temp_dir, 'dst') + os.mkdir(artifact_download_dst_dir) + + def mock_download_and_unpack_zip_impl(url, download_artifact_temp_dir, + headers): + self.assertEqual(url, artifact_download_url) + self.assertEqual(headers, self._get_expected_http_headers()) + shutil.copy( + archive_path, + os.path.join(download_artifact_temp_dir, + os.path.basename(archive_path))) + return True + + mock_download_and_unpack_zip.side_effect = ( + mock_download_and_unpack_zip_impl) + filestore = github_actions.GithubActionsFilestore(self.config) + self.assertTrue( + filestore._download_artifact('corpus', artifact_download_dst_dir)) + mock_find_artifact.assert_called_with('cifuzz-corpus') + self.assertTrue( + os.path.exists( + os.path.join(artifact_download_dst_dir, + os.path.basename(self.testcase)))) + + @mock.patch('filestore.github_actions.github_api.list_artifacts') + def test_find_artifact(self, mock_list_artifacts): + """Tests that _find_artifact works as intended.""" + artifact_listing_1 = { + 'expired': False, + 'name': 'other', + 'archive_download_url': 'http://download1' + } + artifact_listing_2 = { + 'expired': False, + 'name': 'artifact', + 'archive_download_url': 'http://download2' + } + artifact_listing_3 = { + 'expired': True, + 'name': 'artifact', + 'archive_download_url': 'http://download3' + } + artifact_listing_4 = { + 'expired': False, + 'name': 'artifact', + 'archive_download_url': 'http://download4' + } + artifacts = [ + artifact_listing_1, artifact_listing_2, artifact_listing_3, + artifact_listing_4 + ] + mock_list_artifacts.return_value = artifacts + filestore = github_actions.GithubActionsFilestore(self.config) + # Test that find_artifact will return the most recent unexpired artifact + # with the correct name. + self.assertEqual(filestore._find_artifact('artifact'), artifact_listing_2) + mock_list_artifacts.assert_called_with(self.owner, self.repo, + self._get_expected_http_headers()) + + +class TarDirectoryTest(unittest.TestCase): + """Tests for tar_directory.""" + + def test_tar_directory(self): + """Tests that tar_directory writes the archive to the correct location and + archives properly.""" + with tempfile.TemporaryDirectory() as temp_dir: + archive_path = os.path.join(temp_dir, 'myarchive.tar') + archived_dir = os.path.join(temp_dir, 'toarchive') + os.mkdir(archived_dir) + archived_filename = 'file1' + archived_file_path = os.path.join(archived_dir, archived_filename) + with open(archived_file_path, 'w') as file_handle: + file_handle.write('hi') + github_actions.tar_directory(archived_dir, archive_path) + self.assertTrue(os.path.exists(archive_path)) + + # Now check it archives correctly. + unpacked_directory = os.path.join(temp_dir, 'unpacked') + with tarfile.TarFile(archive_path) as artifact_tarfile: + artifact_tarfile.extractall(unpacked_directory) + unpacked_archived_file_path = os.path.join(unpacked_directory, + archived_filename) + self.assertTrue(os.path.exists(unpacked_archived_file_path)) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py new file mode 100644 index 0000000000000000000000000000000000000000..35e92eafb2cf64159c372721598e2a084a573ad4 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py @@ -0,0 +1,109 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for dealing with the GitHub API. This is different from +github_actions_toolkit which only deals with the actions API. We need to use +both.""" +import logging +import os +import sys + +import requests + +import filestore + +# pylint: disable=wrong-import-position,import-error + +sys.path.append( + os.path.join(__file__, os.path.pardir, os.path.pardir, os.path.pardir, + os.path.pardir)) +import retry + +_MAX_ITEMS_PER_PAGE = 100 + +_GET_ATTEMPTS = 3 +_GET_BACKOFF = 1 + + +def get_http_auth_headers(config): + """Returns HTTP headers for authentication to the API.""" + authorization = f'token {config.token}' + return { + 'Authorization': authorization, + 'Accept': 'application/vnd.github.v3+json' + } + + +def _get_artifacts_list_api_url(repo_owner, repo_name): + """Returns the artifacts_api_url for |repo_name| owned by |repo_owner|.""" + github_api_url = os.getenv('GITHUB_API_URL', 'https://api.github.com') + return (f'{github_api_url}/repos/{repo_owner}/' + f'{repo_name}/actions/artifacts') + + +@retry.wrap(_GET_ATTEMPTS, _GET_BACKOFF) +def _do_get_request(*args, **kwargs): + """Wrapped version of requests.get that does retries.""" + return requests.get(*args, **kwargs) + + +def _get_items(url, headers): + """Generator that gets and yields items from a GitHub API endpoint (specified + by |URL|) sending |headers| with the get request.""" + # Github API response pages are 1-indexed. + page_counter = 1 + + # Set to infinity so we run loop at least once. + total_num_items = float('inf') + + item_num = 0 + while item_num < total_num_items: + params = {'per_page': _MAX_ITEMS_PER_PAGE, 'page': str(page_counter)} + response = _do_get_request(url, params=params, headers=headers) + response_json = response.json() + if not response.status_code == 200: + # Check that request was successful. + logging.error('Request to %s failed. Code: %d. Response: %s', + response.request.url, response.status_code, response_json) + raise filestore.FilestoreError('Github API request failed.') + + if total_num_items == float('inf'): + # Set proper total_num_items + total_num_items = response_json['total_count'] + + # Get the key for the items we are after. + keys = [key for key in response_json.keys() if key != 'total_count'] + assert len(keys) == 1, keys + items_key = keys[0] + + for item in response_json[items_key]: + yield item + item_num += 1 + + page_counter += 1 + + +def find_artifact(artifact_name, artifacts): + """Find the artifact with the name |artifact_name| in |artifacts|.""" + for artifact in artifacts: + # TODO(metzman): Handle multiple by making sure we download the latest. + if artifact['name'] == artifact_name and not artifact['expired']: + return artifact + return None + + +def list_artifacts(owner, repo, headers): + """Returns a generator of all the artifacts for |owner|/|repo|.""" + url = _get_artifacts_list_api_url(owner, repo) + logging.debug('Getting artifacts from: %s', url) + return _get_items(url, headers) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6f54e41c8dad942072dc859e42d9c1f8fd82ad --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py @@ -0,0 +1,41 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for github_api.""" +import os +import sys +import unittest + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.abspath( + os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, + os.path.pardir))) + +from filestore.github_actions import github_api +import test_helpers + + +class GetHttpAuthHeaders(unittest.TestCase): + """Tests for get_http_auth_headers.""" + + def test_get_http_auth_headers(self): + """Tests that get_http_auth_headers returns the correct result.""" + token = 'example githubtoken' + run_config = test_helpers.create_run_config(token=token) + expected_headers = { + 'Authorization': f'token {token}', + 'Accept': 'application/vnd.github.v3+json', + } + self.assertEqual(expected_headers, + github_api.get_http_auth_headers(run_config)) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/upload.js b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/upload.js new file mode 100644 index 0000000000000000000000000000000000000000..13a805891bf5565ce88e30120a12c0b078c65af5 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/github_actions/upload.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// Script for uploading an artifact. Returns 0 on success. +// Usage: upload.js ... + +const fs = require('fs'); +const { DefaultArtifactClient } = require('@actions/artifact'); + +const artifactClient = new DefaultArtifactClient(); +const artifactName = process.argv[2]; +const rootDirectory = process.argv[3] +const files = process.argv.slice(4); +const options = { + continueOnError: true +}; + +async function uploadArtifact() { + try { + const uploadResult = await artifactClient.uploadArtifact(artifactName, files, rootDirectory, options); + console.log(uploadResult); + if (uploadResult.failedItems.length > 0) { + return 1; + } + return 0; + } catch (error) { + console.error('Error uploading artifact:', error); + return 1; + } +} + +uploadArtifact().then(exitCode => { + process.exit(exitCode); +}); diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43ee0ce8f17a4231bb46f41377d1277cb87a854b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py @@ -0,0 +1,133 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""GitLab filestore implementation.""" +import logging + +import json +import os +import shutil +import tempfile + +import filestore +import http_utils + +# pylint: disable=no-self-use,unused-argument + + +class GitlabFilestore(filestore.BaseFilestore): + """Implementation of BaseFilestore using GitLab. + Needs a cache to upload and download builds. + Needs a git repository for corpus and coverage. + """ + + BUILD_PREFIX = 'build-' + CORPUS_PREFIX = 'corpus-' + COVERAGE_PREFIX = 'coverage-' + CRASHES_PREFIX = 'crashes-' + + def __init__(self, config): + super().__init__(config) + self.artifacts_dir = self.config.platform_conf.artifacts_dir + self.cache_dir = self.config.platform_conf.cache_dir + if self.config.git_store_repo: + self.git_filestore = filestore.git.GitFilestore(config, None) + else: + self.git_filestore = None + + def upload_crashes(self, name, directory): + """GitLab artifacts implementation of upload_crashes.""" + # Upload crashes as job artifacts. + if os.listdir(directory): + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.CRASHES_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def upload_corpus(self, name, directory, replace=False): + """GitLab artifacts implementation of upload_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.upload_corpus(name, directory, replace) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + # Remove previous corpus from cache if any. + shutil.rmtree(dest_dir_cache, ignore_errors=True) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_build(self, name, directory): + """GitLab artifacts implementation of upload_build.""" + # Puts build into the cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_coverage(self, name, directory): + """GitLab artifacts implementation of upload_coverage.""" + # Use the git filestore. + if self.git_filestore: + self.git_filestore.upload_coverage(name, directory) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + # And also updates coverage reports as artifacts + # as it should not be too big. + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.COVERAGE_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def _copy_from_cache(self, src_dir_cache, dst_directory): + if not os.path.exists(src_dir_cache): + logging.info('Cache %s does not exist.', src_dir_cache) + return False + logging.info('Copying %s from cache to %s.', src_dir_cache, dst_directory) + shutil.copytree(src_dir_cache, dst_directory, dirs_exist_ok=True) + return True + + def download_corpus(self, name, dst_directory): + """GitLab artifacts implementation of download_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.download_corpus(name, dst_directory) + return + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + self._copy_from_cache(src_dir_cache, dst_directory) + + def download_build(self, name, dst_directory): + """GitLab artifacts implementation of download_build.""" + # Gets build from the cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) + + def download_coverage(self, name, dst_directory): + """GitLab artifacts implementation of download_coverage.""" + # Use the git filestore if any. + if self.git_filestore: + return self.git_filestore.download_coverage(name, dst_directory) + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85f85508d78e8a01d11dcbed7c3f463d830d322b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py @@ -0,0 +1,109 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Filestore implementation using gsutil.""" +import logging +import os +import posixpath +import subprocess +import sys + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore +import utils + + +def _gsutil_execute(*args, parallel=True): + """Executes a gsutil command, passing |*args| to gsutil and returns the + stdout, stderr and returncode. Exceptions on failure.""" + command = ['gsutil'] + if parallel: + command.append('-m') + command += list(args) + logging.info('Executing gsutil command: %s', command) + return utils.execute(command, check_result=True) + + +def _rsync(src, dst, recursive=True, delete=False): + """Executes gsutil rsync on |src| and |dst|""" + args = ['rsync'] + if recursive: + args.append('-r') + if delete: + args.append('-d') + args += [src, dst] + return _gsutil_execute(*args) + + +class GSUtilFilestore(filestore.BaseFilestore): + """Filestore implementation using gsutil.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._cloud_bucket = self.config.cloud_bucket + + def _get_gsutil_url(self, name, prefix_dir): + """Returns the gsutil URL for |name| and |prefix_dir|.""" + if not prefix_dir: + return posixpath.join(self._cloud_bucket, name) + return posixpath.join(self._cloud_bucket, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(directory, gsutil_url, delete=delete) + + def _download_directory(self, name, dst_directory, prefix): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(gsutil_url, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + # Name is going to be "current". I don't know if this makes sense outside of + # GitHub Actions. + gsutil_url = self._get_gsutil_url(name, self.CRASHES_DIR) + logging.info('Uploading crashes to %s.', gsutil_url) + return _rsync(directory, gsutil_url) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d063116ebcffcf2552225a58a824e4e4409be49 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py @@ -0,0 +1,51 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Empty filestore implementation for platforms that haven't implemented it.""" +import logging + +import filestore + +# pylint:disable=no-self-use,unused-argument + + +class NoFilestore(filestore.BaseFilestore): + """Empty Filestore implementation.""" + + def upload_crashes(self, name, directory): + """Noop implementation of upload_crashes.""" + logging.info('Not uploading crashes because no Filestore.') + + def upload_corpus(self, name, directory, replace=False): + """Noop implementation of upload_corpus.""" + logging.info('Not uploading corpus because no Filestore.') + + def upload_build(self, name, directory): + """Noop implementation of upload_build.""" + logging.info('Not uploading build because no Filestore.') + + def upload_coverage(self, name, directory): + """Noop implementation of upload_coverage.""" + logging.info('Not uploading coverage because no Filestore.') + + def download_corpus(self, name, dst_directory): + """Noop implementation of download_corpus.""" + logging.info('Not downloading corpus because no Filestore.') + + def download_build(self, name, dst_directory): + """Noop implementation of download_build.""" + logging.info('Not downloading build because no Filestore.') + + def download_coverage(self, name, dst_directory): + """Noop implementation of download_coverage.""" + logging.info('Not downloading coverage because no Filestore.') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/__init__.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..219edbe457260f6bb9c3310665d853f2720ffc1d --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/__init__.py @@ -0,0 +1,124 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run.""" +import logging +import os + +import environment + + +class BasePlatformConfig: + """Base class for PlatformConfig subclasses.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or None.""" + path = os.getenv('PROJECT_SRC_PATH') + if not path: + logging.debug('No PROJECT_SRC_PATH.') + return path + + logging.debug('PROJECT_SRC_PATH: %s.', path) + return path + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('WORKSPACE') + + # Optional config variables. + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz. This is used only by GitHub + projects when commit fuzzing. It is not used when PR fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return None + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + # TODO(metzman) Rename base_commit to git_base_commit. + return os.getenv('GIT_BASE_COMMIT') + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + # TODO(metzman) Rename base_ref to git_base_ref. + return os.getenv('GIT_BASE_REF') + + @property + def pr_ref(self): + """Returns the pull request to checkout and fuzz. This is used only by + GitHub projects when PR fuzzing. It is not used when commit fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return None + + @property + def project_repo_owner(self): + """Returns the project repo owner (githubism).""" + return None + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return os.environ.get('REPOSITORY') + + @property + def actor(self): + """Name of the actor for the CI.""" + return None + + @property + def token(self): + """Returns the CI API token.""" + return None + + @property + def docker_in_docker(self): + """Returns whether or not CFL is running using Docker in Docker.""" + return environment.get_bool('DOCKER_IN_DOCKER', False) + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE') + + @property + def git_url(self): + """Returns the repo URL. This is only used by GitHub users. Right now it is + needed by external on GitHub because we need to clone a new repo because the + copy they give us doesn't work for diffing. It isn't used by OSS-Fuzz on + github users since the Git URL is determined using repo detection. + + TODO(metzman): Try to eliminate the need for this by making the clone + from external github projects usable. + TODO(metzman): As an easier goal, maybe make OSS-Fuzz GitHub use this too + for: 1. Consistency 2. Maybe it will allow use on forks.""" + return None diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gcb.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gcb.py new file mode 100644 index 0000000000000000000000000000000000000000..59b7e2fab641cc9709cba880b475a9395ae36d98 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gcb.py @@ -0,0 +1,40 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on Github.""" +import logging +import os + +import platform_config + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Google Cloud Build.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or the default.""" + project_src_path = os.getenv('PROJECT_SRC_PATH', '/workspace') + logging.debug('PROJECT_SRC_PATH: %s.', project_src_path) + return project_src_path + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('WORKSPACE', '/builder/home') + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gsutil') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github.py new file mode 100644 index 0000000000000000000000000000000000000000..dc66e495acd02bb3ede6b92e289a02e2216a219c --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github.py @@ -0,0 +1,146 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on Github.""" +import json +import logging +import os + +import platform_config + + +def _get_github_event_path(): + return os.getenv('GITHUB_EVENT_PATH') + + +def _get_event_data(): + """Returns the GitHub event data.""" + github_event_path = _get_github_event_path() + with open(github_event_path, encoding='utf-8') as file_handle: + return json.load(file_handle) + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitHub.""" + + def __init__(self): + self._event_data = _get_event_data() + self._event = os.getenv('GITHUB_EVENT_NAME') + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('GITHUB_WORKSPACE') + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz. This is used only by GitHub + projects when commit fuzzing. It is not used when PR fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return os.getenv('GITHUB_SHA') + + @property + def actor(self): + """Name of the actor for the CI.""" + return os.getenv('GITHUB_ACTOR') + + @property + def token(self): + """Returns the CI API token.""" + return os.getenv('GITHUB_TOKEN') + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or None. The path returned is relative to |self.workspace| since + on github the checkout will be relative to there.""" + project_src_path = super().project_src_path + if project_src_path is None: + # Not set for internal GitHub users. + return project_src_path + # On GitHub (external users), this path is relative to |workspace|. + return os.path.join(self.workspace, project_src_path) + + @property + def _project_repo_owner_and_name(self): + """Returns a tuple containing the project repo owner and the name of the + repo.""" + # On GitHub this includes owner and repo name. + repository = os.getenv('GITHUB_REPOSITORY') + # Use os.path.split to split owner from repo. + return os.path.split(repository) + + @property + def project_repo_owner(self): + """Returns the project repo owner (githubism).""" + return self._project_repo_owner_and_name[0] + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return self._project_repo_owner_and_name[1] + + @property + def git_url(self): + """Returns the repo URL. This is only used by GitHub users. Right now it is + needed by external on GitHub because we need to clone a new repo because the + copy they give us doesn't work for diffing. It isn't used by OSS-Fuzz on + github users since the Git URL is determined using repo detection. + + TODO(metzman): Try to eliminate the need for this by making the clone + from external github projects usable. + TODO(metzman): As an easier goal, maybe make OSS-Fuzz GitHub use this too + for: 1. Consistency 2. Maybe it will allow use on forks.""" + repository = os.getenv('GITHUB_REPOSITORY') + github_server_url = os.getenv('GITHUB_SERVER_URL', 'https://github.com') + # TODO(metzman): Probably need to change this to github.server_url. + return os.path.join(github_server_url, repository) + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + base_commit = None + if self._event == 'push': + base_commit = self._event_data['before'] + logging.debug('base_commit: %s', base_commit) + return base_commit + + @property + def pr_ref(self): + """Returns the pull request to checkout and fuzz. This is used only by + GitHub projects when PR fuzzing. It is not used when commit fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + if self._event == 'pull_request': + pr_ref = f'refs/pull/{self._event_data["pull_request"]["number"]}/merge' + logging.debug('pr_ref: %s', pr_ref) + return pr_ref + return None + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + return os.getenv('GITHUB_BASE_REF') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github_test.py new file mode 100644 index 0000000000000000000000000000000000000000..11cc6866cdffd122bd0a1dbba91c1b87e676cc39 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/github_test.py @@ -0,0 +1,87 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for platform_config.github.""" +import os +import unittest +from unittest import mock + +import platform_config.github +import test_helpers + +# pylint: disable=arguments-differ + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.platform_conf = platform_config.github.PlatformConfig() + + def test_github_repository_owner(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + self.assertEqual(self.platform_conf.project_repo_owner, self.repo_owner) + + def test_github_repository_name(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.assertEqual(self.platform_conf.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.workspace = '/workspace' + os.environ['GITHUB_WORKSPACE'] = self.workspace + self.project_src_dir_name = 'project-src' + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github_unset(self, _): + """Tests that project_src_path returns None when no PROJECT_SRC_PATH is + set.""" + github_env = platform_config.github.PlatformConfig() + self.assertIsNone(github_env.project_src_path) + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github(self, _): + """Tests that project_src_path returns the correct result on GitHub.""" + os.environ['PROJECT_SRC_PATH'] = self.project_src_dir_name + expected_project_src_path = os.path.join(self.workspace, + self.project_src_dir_name) + github_env = platform_config.github.PlatformConfig() + self.assertEqual(github_env.project_src_path, expected_project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for GenericPlatformConfig.git_url.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.platform_conf = platform_config.github.PlatformConfig() + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertEqual('https://github.com/repo/owner', + self.platform_conf.git_url) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py new file mode 100644 index 0000000000000000000000000000000000000000..186cbefc4db9d2dc3693e36a20ed4ec40227d748 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py @@ -0,0 +1,78 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on GitLab.""" +import logging +import os + +import environment +import platform_config + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitLab.""" + + @property + def workspace(self): + """Returns the workspace.""" + return os.path.join(os.getenv('CI_BUILDS_DIR'), os.getenv('CI_JOB_ID')) + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz.""" + return os.getenv('CI_COMMIT_SHA') + + @property + def project_src_path(self): + """Returns the directory with the source of the project""" + return os.getenv('CI_PROJECT_DIR') + + @property + def token(self): + """Returns the job token""" + return os.getenv('CI_JOB_TOKEN') + + @property + def project_repo_name(self): + """Returns the project's name""" + return os.getenv('CI_PROJECT_NAME') + + @property + def base_commit(self): + """Returns the previous commit sha for commit-fuzzing""" + base_commit = None + if os.getenv('CI_PIPELINE_SOURCE') == 'push': + base_commit = os.getenv('CI_COMMIT_BEFORE_SHA') + logging.debug('base_commit: %s.', base_commit) + return base_commit + + @property + def base_ref(self): + """Returns the base commit sha for a merge request""" + # Could also be CI_MERGE_REQUEST_TARGET_BRANCH_NAME. + return os.getenv('CI_MERGE_REQUEST_DIFF_BASE_SHA') + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gitlab') + + @property + def artifacts_dir(self): + """Gitlab: returns the directory to put artifacts""" + return environment.get('CFL_ARTIFACTS_DIR', 'artifacts') + + @property + def cache_dir(self): + """Gitlab: returns the directory to use as cache""" + return environment.get('CFL_CACHE_DIR', 'cache') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py new file mode 100644 index 0000000000000000000000000000000000000000..75b26f526a4f887383afa122e668d2a6010ff606 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py @@ -0,0 +1,82 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for platform_config.""" +import os +import unittest + +import platform_config +import test_helpers + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertIsNone(self.env.project_repo_name) + + def test_owner(self): + """Tests that the correct result is returned for owner.""" + self.assertIsNone(self.env.project_repo_owner) + + def test_empty_repository(self): + """Tests that the correct result is returned when repository is an empty + string.""" + os.environ['REPOSITORY'] = '' + self.assertEqual(self.env.project_repo_name, '') + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + just the repo name (as it does outside of GitHub).""" + os.environ['REPOSITORY'] = self.repo_name + self.assertEqual(self.env.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def test_not_github(self): + """Tests that project_src_path returns the correct result not on + GitHub.""" + project_src_path = 'project-src' + os.environ['PROJECT_SRC_PATH'] = project_src_path + generic_ci_env = platform_config.BasePlatformConfig() + self.assertEqual(generic_ci_env.project_src_path, project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for BasePlatformConfig.git_url.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertEqual(self.env.git_url, None) + + def test_repository(self): + """Tests that the correct result is returned when GITHUB_REPOSITORY is + set.""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertIsNone(self.env.git_url) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/prow.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/prow.py new file mode 100644 index 0000000000000000000000000000000000000000..69c035ae80194e86b3fff7759db0f0f0aca4a64b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/prow.py @@ -0,0 +1,64 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on prow.""" +import logging +import os + +import platform_config + +# pylint: disable=too-few-public-methods + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Prow.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or the current directory if not. Prow will run ClusterfuzzLite + at the directory head for the repo.""" + project_src_path = os.getenv('PROJECT_SRC_PATH', os.getcwd()) + logging.debug('PROJECT_SRC_PATH: %s.', project_src_path) + return project_src_path + + @property + def workspace(self): + """Returns the workspace.""" + # Let Prow user override workspace, but default to using artifacts dir + return os.getenv('WORKSPACE', os.getenv('ARTIFACTS')) + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + return os.getenv('PULL_BASE_REF') + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return os.getenv('REPO_NAME') + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + return os.getenv('PULL_BASE_SHA') + + @property + def docker_in_docker(self): + """Returns True if using Docker in Docker.""" + return True + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gsutil') diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/standalone.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..1975dfb1b842a28b9f2ceea809ef2f0d4d7a4a49 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/platform_config/standalone.py @@ -0,0 +1,33 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run standalone.""" +import os + +import platform_config + +# pylint: disable=too-few-public-methods + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Standalone.""" + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'filesystem') + + @property + def filestore_root_dir(self): + """Returns the filestore used to store persistent data.""" + return os.environ['FILESTORE_ROOT_DIR'] diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3034d300ed52a6487df3f42a3e83325bae403ad9 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp @@ -0,0 +1,36 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Example of a standalone runner for "fuzz targets". +// It reads all files passed as parameters and feeds their contents +// one by one into the fuzz target (LLVMFuzzerTestOneInput). +// This runner does not do any fuzzing, but allows us to run the fuzz target +// on the test corpus (e.g. "do_stuff_test_data") or on a single file, +// e.g. the one that comes from a bug report. + +// This is a fuzz target that times out on every input by infinite looping. +// This is used for testing. +// Build instructions: +// 1. clang++ -fsanitize=fuzzer TimeoutFuzzer.cpp -o timeout_fuzzer +// 2. strip timeout_fuzzer +// The binary is stripped to save space in the git repo. + +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { + while (true) + ; + return 0; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt new file mode 100644 index 0000000000000000000000000000000000000000..8caebad0cbf1d7778b7d7ea0346410ba012f8acd --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt @@ -0,0 +1,68 @@ +AddressSanitizer: heap-buffer-overflow on address 0x62500001b530 at pc 0x00000052138a bp 0x7ffe62db2c10 sp 0x7ffe62db23d8 +READ of size 52 at 0x62500001b530 thread T0 +SCARINESS: 26 (multi-byte-read-heap-buffer-overflow) + #0 0x521389 in __asan_memcpy /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 + #1 0x567590 in yr_object_set_string /src/yara/libyara/object.c:1122:5 + #2 0x5afced in dex_parse /src/yara/libyara/modules/dex/dex.c:781:5 + #3 0x5b4a8b in dex__load /src/yara/libyara/modules/dex/dex.c:1218:7 + #4 0x56537c in yr_modules_load /src/yara/libyara/modules.c:179:16 + #5 0x5d6583 in yr_execute_code /src/yara/libyara/exec.c:1276:18 + #6 0x56f5c0 in yr_scanner_scan_mem_blocks /src/yara/libyara/scanner.c:444:3 + #7 0x56bf23 in yr_rules_scan_mem_blocks /src/yara/libyara/rules.c:235:12 + #8 0x56c182 in yr_rules_scan_mem /src/yara/libyara/rules.c:285:10 + #9 0x5548d2 in LLVMFuzzerTestOneInput /src/yara/tests/oss-fuzz/dex_fuzzer.cc:40:3 + #10 0x45a3b1 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:556:15 + #11 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #12 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #13 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #14 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #15 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #16 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + #17 0x41e348 in _start (out/dex_fuzzer+0x41e348) + +0x62500001b530 is located 0 bytes to the right of 9264-byte region [0x625000019100,0x62500001b530) +allocated by thread T0 here: + #0 0x521f4d in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:145:3 + #1 0x4331b7 in operator new(unsigned long) (out/dex_fuzzer+0x4331b7) + #2 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #3 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #4 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #5 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #6 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #7 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 in __asan_memcpy +Shadow bytes around the buggy address: + 0x0c4a7fffb650: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb660: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb670: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb680: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb690: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +=>0x0c4a7fffb6a0: 00 00 00 00 00 00[fa]fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb + Shadow gap: cc +==12==ABORTING \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..64cb0af8ceda12d9b7fbbb11a4463cd7b10c476a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt @@ -0,0 +1,202 @@ +/github/workspace/build-out/do_stuff_fuzzer -timeout=25 -rss_limit_mb=2560 -dict=/github/workspace/build-out/do_stuff_fuzzer.dict -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmp9p1w4p8r/ -max_total_time=600 -print_final_stats=1 /github/workspace/cifuzz-corpus/do_stuff_fuzzer >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 77 ============ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (86 inline 8-bit counters): 86 [0x6150e0, 0x615136), +INFO: Loaded 1 PC tables (86 PCs): 86 [0x5c8b08,0x5c9068), +INFO: 5 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: seed corpus: files: 5 min: 3b max: 44b total: 64b rss: 31Mb +#6 INITED cov: 64 ft: 70 corp: 5/64b exec/s: 0 rss: 32Mb +#9 NEW cov: 64 ft: 72 corp: 6/74b lim: 4096 exec/s: 0 rss: 32Mb L: 10/44 MS: 3 ChangeBit-InsertByte-ManualDict- DE: "foo"- +#17 NEW cov: 64 ft: 74 corp: 7/86b lim: 4096 exec/s: 0 rss: 32Mb L: 12/44 MS: 3 ChangeBit-ManualDict-PersAutoDict- DE: "ouch"-"foo"- +#18 NEW cov: 64 ft: 76 corp: 8/100b lim: 4096 exec/s: 0 rss: 32Mb L: 14/44 MS: 1 CrossOver- +#22 NEW cov: 64 ft: 78 corp: 9/141b lim: 4096 exec/s: 0 rss: 32Mb L: 41/44 MS: 4 InsertRepeatedBytes-CopyPart-ChangeBinInt-ChangeBit- +#24 NEW cov: 64 ft: 80 corp: 10/151b lim: 4096 exec/s: 0 rss: 32Mb L: 10/44 MS: 2 CrossOver-CopyPart- +#28 NEW cov: 64 ft: 81 corp: 11/171b lim: 4096 exec/s: 0 rss: 32Mb L: 20/44 MS: 4 InsertByte-PersAutoDict-ShuffleBytes-ManualDict- DE: "foo"-"ouch"- +#43 NEW cov: 65 ft: 83 corp: 12/175b lim: 4096 exec/s: 0 rss: 32Mb L: 4/44 MS: 5 InsertByte-ChangeBit-ManualDict-ManualDict-EraseBytes- DE: "bar"-"bar"- +#54 NEW cov: 65 ft: 84 corp: 13/191b lim: 4096 exec/s: 0 rss: 32Mb L: 16/44 MS: 1 CrossOver- +#64 NEW cov: 65 ft: 86 corp: 14/209b lim: 4096 exec/s: 0 rss: 32Mb L: 18/44 MS: 5 InsertByte-ChangeBinInt-CMP-PersAutoDict-CopyPart- DE: "\000\000"-"foo"- +#75 REDUCE cov: 65 ft: 86 corp: 14/203b lim: 4096 exec/s: 0 rss: 32Mb L: 35/44 MS: 1 EraseBytes- +#76 REDUCE cov: 65 ft: 86 corp: 14/195b lim: 4096 exec/s: 0 rss: 32Mb L: 36/36 MS: 1 EraseBytes- +================================================================= +==26==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000003114 at pc 0x00000056d1db bp 0x7fffd6a72bf0 sp 0x7fffd6a72be8 +READ of size 4 at 0x603000003114 thread T0 +SCARINESS: 17 (4-byte-read-heap-buffer-overflow) + #0 0x56d1da in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:26:10 + #1 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #2 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #5 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #6 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7fcfaa2aa082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #9 0x41f74d in _start (build-out/do_stuff_fuzzer+0x41f74d) + +DEDUP_TOKEN: DoStuff(std::__1::basic_string, std::__1::allocator > const&)--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +0x603000003114 is located 0 bytes to the right of 20-byte region [0x603000003100,0x603000003114) +allocated by thread T0 here: + #0 0x569dfd in operator new(unsigned long) /src/llvm-project/compiler-rt/lib/asan/asan_new_delete.cpp:95:3 + #1 0x56c9d4 in __libcpp_operator_new /usr/local/bin/../include/c++/v1/new:245:10 + #2 0x56c9d4 in __libcpp_allocate /usr/local/bin/../include/c++/v1/new:271:10 + #3 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator.h:105:38 + #4 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator_traits.h:262:20 + #5 0x56c9d4 in __vallocate /usr/local/bin/../include/c++/v1/vector:931:37 + #6 0x56c9d4 in vector /usr/local/bin/../include/c++/v1/vector:1236:9 + #7 0x56c9d4 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:14:20 + #8 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #9 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #10 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #11 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #12 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #13 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #14 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #15 0x7fcfaa2aa082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: operator new(unsigned long)--__libcpp_operator_new--__libcpp_allocate +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/cifuzz-example/my_api.cpp:26:10 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) +Shadow bytes around the buggy address: + 0x0c067fff85d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff85e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff85f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8600: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8610: fd fa fa fa fd fd fd fa fa fa 00 00 00 00 fa fa +=>0x0c067fff8620: 00 00[04]fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8630: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8640: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8650: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8660: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8670: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==26==ABORTING +MS: 4 PersAutoDict-ManualDict-CrossOver-PersAutoDict- DE: "foo"-"ouch"-"bar"-; base unit: 1a25c32303e03f997166aee1c665b5ae9f66ec7d +0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x66,0x6f,0x6f,0xff,0x1,0x62,0x61,0x72,0x63,0x68,0x6f,0x75,0x63,0x68,0x66,0x6f,0x66,0x6e,0x6f,0x6d,0x67,0x6d, +\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377foo\377\001barchouchfofnomgm +artifact_prefix='/tmp/tmp9p1w4p8r/'; Test unit written to /tmp/tmp9p1w4p8r/crash-1c750df432fe458b738987ba69cd20a598708775 +Base64: //////////////////////9mb2//AWJhcmNob3VjaGZvZm5vbWdt +stat::number_of_executed_units: 90 +stat::average_exec_per_sec: 0 +stat::new_units_added: 11 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 33 +/github/workspace/build-out/do_stuff_fuzzer -timeout=25 -rss_limit_mb=2560 -dict=/github/workspace/build-out/do_stuff_fuzzer.dict -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmp9p1w4p8r/ -max_total_time=600 -print_final_stats=1 /github/workspace/cifuzz-corpus/do_stuff_fuzzer >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (86 inline 8-bit counters): 86 [0x6150e0, 0x615136), +INFO: Loaded 1 PC tables (86 PCs): 86 [0x5c8b08,0x5c9068), +INFO: 15 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: seed corpus: files: 15 min: 3b max: 44b total: 239b rss: 31Mb +#16 INITED cov: 65 ft: 86 corp: 13/159b exec/s: 0 rss: 32Mb +#38 NEW cov: 65 ft: 88 corp: 14/188b lim: 4096 exec/s: 0 rss: 32Mb L: 29/35 MS: 2 InsertByte-CopyPart- +#43 REDUCE cov: 65 ft: 88 corp: 14/187b lim: 4096 exec/s: 0 rss: 32Mb L: 2/35 MS: 5 InsertByte-ChangeByte-ChangeBinInt-EraseBytes-EraseBytes- +#64 NEW cov: 66 ft: 89 corp: 15/191b lim: 4096 exec/s: 0 rss: 32Mb L: 4/35 MS: 1 ChangeByte- +#78 REDUCE cov: 66 ft: 89 corp: 15/190b lim: 4096 exec/s: 0 rss: 32Mb L: 15/35 MS: 4 ChangeBinInt-CopyPart-EraseBytes-EraseBytes- +#95 REDUCE cov: 66 ft: 89 corp: 15/188b lim: 4096 exec/s: 0 rss: 32Mb L: 16/35 MS: 2 ChangeBinInt-EraseBytes- +#110 REDUCE cov: 66 ft: 89 corp: 15/184b lim: 4096 exec/s: 0 rss: 32Mb L: 31/31 MS: 5 CrossOver-ChangeByte-ShuffleBytes-InsertByte-EraseBytes- +#146 REDUCE cov: 66 ft: 89 corp: 15/183b lim: 4096 exec/s: 0 rss: 32Mb L: 1/31 MS: 1 EraseBytes- +#157 NEW cov: 66 ft: 90 corp: 16/210b lim: 4096 exec/s: 0 rss: 32Mb L: 27/31 MS: 1 CrossOver- +#230 REDUCE cov: 66 ft: 92 corp: 17/318b lim: 4096 exec/s: 0 rss: 32Mb L: 108/108 MS: 3 CopyPart-InsertRepeatedBytes-CrossOver- +#277 NEW cov: 66 ft: 94 corp: 18/429b lim: 4096 exec/s: 0 rss: 32Mb L: 111/111 MS: 2 ManualDict-CMP- DE: "bar"-"\000\000\000\000"- +#337 NEW cov: 67 ft: 95 corp: 19/439b lim: 4096 exec/s: 0 rss: 32Mb L: 10/111 MS: 5 ChangeByte-ChangeBit-ManualDict-CopyPart-EraseBytes- DE: "bar"- +================================================================= +==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000007d94 at pc 0x00000056d1db bp 0x7ffdb9da4b50 sp 0x7ffdb9da4b48 +READ of size 4 at 0x603000007d94 thread T0 +SCARINESS: 17 (4-byte-read-heap-buffer-overflow) + #0 0x56d1da in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:26:10 + #1 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #2 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #5 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #6 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7fc2c6bd3082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #9 0x41f74d in _start (build-out/do_stuff_fuzzer+0x41f74d) + +DEDUP_TOKEN: DoStuff(std::__1::basic_string, std::__1::allocator > const&)--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +0x603000007d94 is located 0 bytes to the right of 20-byte region [0x603000007d80,0x603000007d94) +allocated by thread T0 here: + #0 0x569dfd in operator new(unsigned long) /src/llvm-project/compiler-rt/lib/asan/asan_new_delete.cpp:95:3 + #1 0x56c9d4 in __libcpp_operator_new /usr/local/bin/../include/c++/v1/new:245:10 + #2 0x56c9d4 in __libcpp_allocate /usr/local/bin/../include/c++/v1/new:271:10 + #3 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator.h:105:38 + #4 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator_traits.h:262:20 + #5 0x56c9d4 in __vallocate /usr/local/bin/../include/c++/v1/vector:931:37 + #6 0x56c9d4 in vector /usr/local/bin/../include/c++/v1/vector:1236:9 + #7 0x56c9d4 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:14:20 + #8 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #9 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #10 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #11 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #12 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #13 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #14 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #15 0x7fc2c6bd3082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: operator new(unsigned long)--__libcpp_operator_new--__libcpp_allocate +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/cifuzz-example/my_api.cpp:26:10 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) +Shadow bytes around the buggy address: + 0x0c067fff8f60: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8f70: fd fa fa fa fd fd fd fa fa fa fd fd fd fa fa fa + 0x0c067fff8f80: fd fd fd fa fa fa fd fd fd fa fa fa fd fd fd fa + 0x0c067fff8f90: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8fa0: fd fa fa fa fd fd fd fa fa fa fd fd fd fa fa fa +=>0x0c067fff8fb0: 00 00[04]fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fe0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8ff0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff9000: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==30==ABORTING +MS: 4 ShuffleBytes-ManualDict-CrossOver-PersAutoDict- DE: "foo"-"bar"-; base unit: 8fc7da8d952ed1aa5c7415e21b3d52b42402973d +0x66,0x6f,0x6f,0x63,0x6f,0x75,0x6f,0x75,0x63,0x68,0x63,0x68,0x66,0x62,0x61,0x72,0x6f,0x6f,0x6d,0x67,0x66,0x6f,0x6f,0x2f,0x99,0x6f,0x6f,0x90,0x6f,0x6f,0x6d,0x0,0x0,0x67,0x2f, +foocououchchfbaroomgfoo/\231oo\220oom\000\000g/ +artifact_prefix='/tmp/tmp9p1w4p8r/'; Test unit written to /tmp/tmp9p1w4p8r/crash-f8a2a1e84f58a2d676e5ad8078119a39b78df901 +Base64: Zm9vY291b3VjaGNoZmJhcm9vbWdmb28vmW9vkG9vbQAAZy8= +stat::number_of_executed_units: 366 +stat::average_exec_per_sec: 0 +stat::new_units_added: 11 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 33 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..30add4d3a8d3cd9d8efc9d8b97983e161a62205b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/Dockerfile @@ -0,0 +1,22 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +FROM ghcr.io/aixcc-finals/base-builder +RUN apt-get update && apt-get install -y make + +COPY . $SRC/external-project +WORKDIR $SRC/external-project +COPY .clusterfuzzlite/build.sh $SRC/ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c52ef90f4cf6ea50746586d7f5c0ffdc5291435 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh @@ -0,0 +1,24 @@ +#!/bin/bash -eu +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +make clean # Not strictly necessary, since we are building in a fresh dir. +make -j$(nproc) all # Build the fuzz targets. + +# Copy the fuzzer executables, zip-ed corpora, option and dictionary files to $OUT +find . -name '*_fuzzer' -exec cp -v '{}' $OUT ';' +find . -name '*_fuzzer.dict' -exec cp -v '{}' $OUT ';' # If you have dictionaries. +find . -name '*_fuzzer.options' -exec cp -v '{}' $OUT ';' # If you have custom options. diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2c177377627adacda8eda47a1f13830cb1f3998b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile @@ -0,0 +1,44 @@ +# Copyright 2017 Google Inc. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); + +# Simple example of a build file that nicely integrates a fuzz target +# with the rest of the project. +# +# We use 'make' as the build system, but these ideas are applicable +# to any other build system + +# By default, use our own standalone_fuzz_target_runner. +# This runner does no fuzzing, but simply executes the inputs +# provided via parameters. +# Run e.g. "make all LIB_FUZZING_ENGINE=/path/to/libFuzzer.a" +# to link the fuzzer(s) against a real fuzzing engine. +# +# OSS-Fuzz will define its own value for LIB_FUZZING_ENGINE. +LIB_FUZZING_ENGINE ?= standalone_fuzz_target_runner.o + +# Values for CC, CFLAGS, CXX, CXXFLAGS are provided by OSS-Fuzz. +# Outside of OSS-Fuzz use the ones you prefer or rely on the default values. +# Do not use the -fsanitize=* flags by default. +# OSS-Fuzz will use different -fsanitize=* flags for different builds (asan, ubsan, msan, ...) + +# You may add extra compiler flags like this: +CXXFLAGS += -std=c++11 + +all: do_stuff_fuzzer + +clean: + rm -fv *.a *.o *_fuzzer crash-* *.zip + +# Fuzz target, links against $LIB_FUZZING_ENGINE, so that +# you may choose which fuzzing engine to use. +do_stuff_fuzzer: do_stuff_fuzzer.cpp my_api.a standalone_fuzz_target_runner.o + ${CXX} ${CXXFLAGS} $< my_api.a ${LIB_FUZZING_ENGINE} -o $@ + + +# The library itself. +my_api.a: my_api.cpp my_api.h + ${CXX} ${CXXFLAGS} $< -c + ar ruv my_api.a my_api.o + +# The standalone fuzz target runner. +standalone_fuzz_target_runner.o: standalone_fuzz_target_runner.cpp diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaf70137c3b8aa58a6c09f89eecdba7f5ebbd010 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.cpp @@ -0,0 +1,24 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include "my_api.h" + +#include + +// Simple fuzz target for DoStuff(). +// See https://llvm.org/docs/LibFuzzer.html for details. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + std::string str(reinterpret_cast(data), size); + DoStuff(str); // Disregard the output. + return 0; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict new file mode 100644 index 0000000000000000000000000000000000000000..6a82ac4b3aa09ea8bbe6fc127e1bad4ed1c28ebb --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict @@ -0,0 +1,6 @@ +# A dictionary for more efficient fuzzing of DoStuff(). +# If the inputs contain multi-byte tokens, list them here. +# See https://llvm.org/docs/LibFuzzer.html#dictionaries +"foo" +"bar" +"ouch" diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a2c1bc1c0d8a7d1a2473e0563b1a385b11ed621 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp @@ -0,0 +1,36 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Implementation of "my_api". +#include "my_api.h" + +#include + +// Do some computations with 'str', return the result. +// This function contains a bug. Can you spot it? +size_t DoStuff(const std::string &str) { + std::vector Vec({0, 1, 2, 3, 4}); + size_t Idx = 0; + if (str.size() > 5) + Idx++; + if (str.find("foo") != std::string::npos) + Idx++; + if (str.find("bar") != std::string::npos) + Idx++; + if (str.find("ouch") != std::string::npos) + Idx++; + if (str.find("omg") != std::string::npos) + Idx++; + return Vec[Idx]; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h new file mode 100644 index 0000000000000000000000000000000000000000..325aa15ccc7f6fbed196437aeb75c94a88a630a6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h @@ -0,0 +1,19 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A library that does ... stuff. +// Serves as an example of good fuzz testing and OSS-Fuzz integration. +#include + +size_t DoStuff(const std::string &str); diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38a0454f0ac98e74052670c5eac9e5a86df9dfc7 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp @@ -0,0 +1,47 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Example of a standalone runner for "fuzz targets". +// It reads all files passed as parameters and feeds their contents +// one by one into the fuzz target (LLVMFuzzerTestOneInput). +// This runner does not do any fuzzing, but allows us to run the fuzz target +// on the test corpus (e.g. "do_stuff_test_data") or on a single file, +// e.g. the one that comes from a bug report. + +#include +#include +#include +#include + +// Forward declare the "fuzz target" interface. +// We deliberately keep this inteface simple and header-free. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); + +int main(int argc, char **argv) { + for (int i = 1; i < argc; i++) { + std::ifstream in(argv[i]); + in.seekg(0, in.end); + size_t length = in.tellg(); + in.seekg (0, in.beg); + std::cout << "Reading " << length << " bytes from " << argv[i] << std::endl; + // Allocate exactly length bytes so that we reliably catch buffer overflows. + std::vector bytes(length); + in.read(bytes.data(), bytes.size()); + assert(in); + LLVMFuzzerTestOneInput(reinterpret_cast(bytes.data()), + bytes.size()); + std::cout << "Execution successful" << std::endl; + } + return 0; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt new file mode 100644 index 0000000000000000000000000000000000000000..b55e9c6b73b5d645ca7fba6a196f2485bd423b24 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt @@ -0,0 +1,22 @@ +MemorySanitizer: use-of-uninitialized-value +#0 0x52675f in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 +#1 0x45a431 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:599:15 +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +#7 0x41eab8 in _start (out/do_stuff_fuzzer+0x41eab8) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) +Uninitialized value was created by a heap allocation +#0 0x4d57ad in malloc /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:901:3 +#1 0x437c07 in operator new(unsigned long) (out/do_stuff_fuzzer+0x437c07) +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +DEDUP_TOKEN: malloc--operator new(unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) + +SUMMARY: \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..c803bfb1c928e7613baa0f7dfd39238e59ecc9b4 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt @@ -0,0 +1,39 @@ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (184 inline 8-bit counters): 184 [0x829300, 0x8293b8), +INFO: Loaded 1 PC tables (184 PCs): 184 [0x5dc910,0x5dd490), +INFO: 5 files found in /tmp/do_stuff_fuzzer_corpus +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +==13==WARNING: MemorySanitizer: use-of-uninitialized-value +#0 0x52675f in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 +#1 0x45a431 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:599:15 +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +#7 0x41eab8 in _start (out/do_stuff_fuzzer+0x41eab8) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) +Uninitialized value was created by a heap allocation +#0 0x4d57ad in malloc /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:901:3 +#1 0x437c07 in operator new(unsigned long) (out/do_stuff_fuzzer+0x437c07) +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +DEDUP_TOKEN: malloc--operator new(unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) + +SUMMARY: MemorySanitizer: use-of-uninitialized-value /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 in LLVMFuzzerTestOneInput +Unique heap origins: 65 +Stack depot allocated bytes: 4424 +Unique origin histories: 29 +History depot allocated bytes: 696 +Exiting +MS: 0 ; base unit: 0000000000000000000000000000000000000000 + + +artifact_prefix='./'; Test unit written to ./crash-da39a3ee5e6b4b0d3255bfef95601890afd80709 +Base64: diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..9214d8f81f9c77c12b77b6da46db80473941f9fd --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt @@ -0,0 +1,62 @@ +Dictionary: 3 entries +2024-05-07 18:49:02,343 - root - INFO - Fuzzer: do_stuff_fuzzer. Detected bug. +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (83 inline 8-bit counters): 83 [0x563ff0e03e98, 0x563ff0e03eeb), +INFO: Loaded 1 PC tables (83 PCs): 83 [0x563ff0e03ef0,0x563ff0e04420), +INFO: 0 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: A corpus is not provided, starting from an empty corpus +#2 INITED cov: 2 ft: 2 corp: 1/1b exec/s: 0 rss: 69Mb +#4 NEW cov: 3 ft: 3 corp: 2/3b lim: 4096 exec/s: 0 rss: 69Mb L: 2/2 MS: 2 ChangeBit-InsertByte- +==23==WARNING: MemorySanitizer: use-of-uninitialized-value + #0 0x563ff0d278f0 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp:24:1 + #1 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #2 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #3 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #4 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #5 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #6 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + #8 0x563ff0c055ad in _start (build-out/do_stuff_fuzzer+0x4a5ad) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) + Uninitialized value was stored to memory at + #0 0x563ff0d278e9 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp + #1 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #2 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #3 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #4 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #5 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #6 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) + Uninitialized value was created by a heap deallocation + #0 0x563ff0cc7480 in free /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:218:3 + #1 0x563ff0d27800 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp:21:5 + #2 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #3 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #4 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #5 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #6 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #7 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: MemorySanitizer: use-of-uninitialized-value /src/cifuzz-external-example/do_stuff_fuzzer.cpp:24:1 in LLVMFuzzerTestOneInput +Unique heap origins: 201 +Stack depot allocated bytes: 9764880 +Unique origin histories: 181 +History depot allocated bytes: 196608 +Exiting +MS: 5 ShuffleBytes-CopyPart-InsertByte-CopyPart-ManualDict- DE: "bar"-; base unit: adc83b19e793491b1c6ea0fd8b46cd9f32e592fc +0xa,0x62,0x61,0x72,0xa, +\012bar\012 +artifact_prefix='/tmp/tmp1tc5b3m2/'; Test unit written to /tmp/tmp1tc5b3m2/crash-c935b6724d7e27401ac9af3773700ca86ac38dea +Base64: CmJhcgo= +stat::number_of_executed_units: 159 +stat::average_exec_per_sec: 0 +stat::new_units_added: 1 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 69 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..71f6e29ad3bf104ca54293b7395f3c0057c205a0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt @@ -0,0 +1,302 @@ +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82577 inline 8-bit counters): 82573 [0x7fc55e6bedf0, 0x7fc55e6d307d), 4 [0x5e9c28, 0x5e9c2c), +2023-05-04 01:02:55,065 - root - INFO - Not reporting crash in fuzz-bus-label because process timed out. +2023-05-04 01:02:55,069 - root - INFO - Deleting corpus and seed corpus of fuzz-bus-label to save disk. +INFO: Loaded 2 PC tables (82577 PCs): 82573 [0x7fc55e6d3080,0x7fc55e815950), 4 [0x5a6c78,0x5a6cb8), +INFO: 256 files found in /github/workspace/cifuzz-corpus/fuzz-bus-label +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 256 min: 1b max: 5242880b total: 30968483b rss: 48Mb +#257 INITED cov: 41 ft: 230 corp: 111/4360b exec/s: 0 rss: 73Mb +#131072 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#262144 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#524288 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 77Mb +#609082 DONE cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43505 rss: 77Mb +Done 609082 runs in 14 second(s) +stat::number_of_executed_units: 609082 +stat::average_exec_per_sec: 43505 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 77 +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-1.log 2>&1 +2023-05-04 01:02:55,082 - root - INFO - Deleting fuzz target: fuzz-bus-label. +2023-05-04 01:02:55,083 - root - INFO - Done deleting. +2023-05-04 01:02:55,084 - root - INFO - Fuzzer fuzz-bus-label finished running without reportable crashes. +2023-05-04 01:02:55,084 - root - INFO - Running fuzzer: fuzz-dhcp-server. +2023-05-04 01:02:55,085 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip +2023-05-04 01:02:55,088 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:02:55,145 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip HTTP/1.1" 200 806749 +2023-05-04 01:02:55,350 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83640 inline 8-bit counters): 82573 [0x7fe86ff70df0, 0x7fe86ff8507d), 1067 [0x60c638, 0x60ca63), +INFO: Loaded 2 PC tables (83640 PCs): 82573 [0x7fe86ff85080,0x7fe8700c7950), 1067 [0x60ca68,0x610d18), +INFO: 1153 files found in /github/workspace/cifuzz-corpus/fuzz-dhcp-server +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 1153 min: 1b max: 5242879b total: 17056071b rss: 50Mb +#1155 INITED cov: 577 ft: 1116 corp: 203/54Kb exec/s: 0 rss: 86Mb +#1167 NEW cov: 577 ft: 1117 corp: 204/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeASCIIInt-CrossOver- +#1509 NEW cov: 577 ft: 1118 corp: 205/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeBit-CopyPart- +#63018 NEW cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21006 rss: 86Mb L: 245/1071 MS: 4 InsertByte-ChangeByte-CMP-InsertByte- DE: "2\000\000\000\000\000\000\000"- +#65536 pulse cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21845 rss: 86Mb +Loaded 1024/1155 files from /github/workspace/cifuzz-corpus/fuzz-dhcp-server +#99784 NEW cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19956 rss: 105Mb L: 243/1071 MS: 2 ChangeASCIIInt-ChangeBinInt- +#131072 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 21845 rss: 105Mb +#262144 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 20164 rss: 105Mb +#275639 DONE cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19688 rss: 105Mb +###### Recommended dictionary. ###### +"2\000\000\000\000\000\000\000" # Uses: 17879 +###### End of recommended dictionary. ###### +Done 275639 runs in 14 second(s) +stat::number_of_executed_units: 275639 +stat::average_exec_per_sec: 19688 +stat::new_units_added: 4 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 105 +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-1.log 2>&1 +2023-05-04 01:03:18,374 - root - INFO - Not reporting crash in fuzz-dhcp-server because process timed out. +2023-05-04 01:03:18,377 - root - INFO - Deleting corpus and seed corpus of fuzz-dhcp-server to save disk. +2023-05-04 01:03:18,399 - root - INFO - Deleting fuzz target: fuzz-dhcp-server. +2023-05-04 01:03:18,400 - root - INFO - Done deleting. +2023-05-04 01:03:18,400 - root - INFO - Fuzzer fuzz-dhcp-server finished running without reportable crashes. +2023-05-04 01:03:18,401 - root - INFO - Running fuzzer: fuzz-bcd. +2023-05-04 01:03:18,401 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip +2023-05-04 01:03:18,404 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:18,582 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip HTTP/1.1" 200 2293254 +2023-05-04 01:03:18,804 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83175 inline 8-bit counters): 82573 [0x7f1b5387edf0, 0x7f1b5389307d), 602 [0x5f8718, 0x5f8972), +INFO: Loaded 2 PC tables (83175 PCs): 82573 [0x7f1b53893080,0x7f1b539d5950), 602 [0x5f8978,0x5faf18), +INFO: 1260 files found in /github/workspace/cifuzz-corpus/fuzz-bcd +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 946175 bytes +INFO: seed corpus: files: 1260 min: 1b max: 946175b total: 10373697b rss: 48Mb +#1261 INITED cov: 137 ft: 653 corp: 282/1416Kb exec/s: 0 rss: 91Mb +#65536 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#131072 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#262144 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 37449 rss: 98Mb +#475081 DONE cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 33934 rss: 98Mb +Done 475081 runs in 14 second(s) +stat::number_of_executed_units: 475081 +stat::average_exec_per_sec: 33934 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 98 +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-1.log 2>&1 +2023-05-04 01:03:41,821 - root - INFO - Not reporting crash in fuzz-bcd because process timed out. +2023-05-04 01:03:41,822 - root - INFO - Deleting corpus and seed corpus of fuzz-bcd to save disk. +2023-05-04 01:03:41,848 - root - INFO - Deleting fuzz target: fuzz-bcd. +2023-05-04 01:03:41,848 - root - INFO - Done deleting. +2023-05-04 01:03:41,848 - root - INFO - Fuzzer fuzz-bcd finished running without reportable crashes. +2023-05-04 01:03:41,848 - root - INFO - Running fuzzer: fuzz-varlink. +2023-05-04 01:03:41,849 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip +2023-05-04 01:03:41,852 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:41,906 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip HTTP/1.1" 200 2586434 +2023-05-04 01:03:42,671 - root - INFO - Starting fuzzing +2023-05-04 01:04:05,709 - root - INFO - Not reporting crash in fuzz-varlink because process timed out. +Fuzzing logs: +/github/workspace/build-out/fuzz-varlink -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpbtf4f932/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-varlink >fuzz-0.log 2>&1 +2023-05-04 01:04:05,709 - root - INFO - Deleting corpus and seed corpus of fuzz-varlink to save disk. +2023-05-04 01:04:05,806 - root - INFO - Deleting fuzz target: fuzz-varlink. +2023-05-04 01:04:05,806 - root - INFO - Done deleting. +2023-05-04 01:04:05,806 - root - INFO - Fuzzer fuzz-varlink finished running without reportable crashes. +2023-05-04 01:04:05,806 - root - INFO - Running fuzzer: fuzz-unit-file. +2023-05-04 01:04:05,807 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip +2023-05-04 01:04:05,809 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:04:05,897 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip HTTP/1.1" 200 4999974 +2023-05-04 01:04:07,869 - root - INFO - Starting fuzzing +2023-05-04 01:04:09,516 - root - INFO - Fuzzer: fuzz-unit-file. Detected bug. +Fuzzing logs: +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-0.log 2>&1 +2023-05-04 01:04:09,517 - root - INFO - Trying to reproduce crash using: /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03. +================== Job 0 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7f3b0de4cdf0, 0x7f3b0de6107d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7f3b0de61080,0x7f3b0dfa3950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==74==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7fffeea64fe0 sp 0x7fffeea64fd8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in LLVMFuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==74==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 67 +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7ff1ba038df0, 0x7ff1ba04d07d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7ff1ba04d080,0x7ff1ba18f950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==78==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7ffc2e6825c0 sp 0x7ffc2e6825b8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--samLLVM2FuzzerTestOneInput --fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in samsamLLVM2FuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==78==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 68 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_systemd_stack.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_systemd_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..e632d3e659b53090d776c36a46885c6934d51f23 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_systemd_stack.txt @@ -0,0 +1,302 @@ +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82577 inline 8-bit counters): 82573 [0x7fc55e6bedf0, 0x7fc55e6d307d), 4 [0x5e9c28, 0x5e9c2c), +2023-05-04 01:02:55,065 - root - INFO - Not reporting crash in fuzz-bus-label because process timed out. +2023-05-04 01:02:55,069 - root - INFO - Deleting corpus and seed corpus of fuzz-bus-label to save disk. +INFO: Loaded 2 PC tables (82577 PCs): 82573 [0x7fc55e6d3080,0x7fc55e815950), 4 [0x5a6c78,0x5a6cb8), +INFO: 256 files found in /github/workspace/cifuzz-corpus/fuzz-bus-label +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 256 min: 1b max: 5242880b total: 30968483b rss: 48Mb +#257 INITED cov: 41 ft: 230 corp: 111/4360b exec/s: 0 rss: 73Mb +#131072 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#262144 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#524288 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 77Mb +#609082 DONE cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43505 rss: 77Mb +Done 609082 runs in 14 second(s) +stat::number_of_executed_units: 609082 +stat::average_exec_per_sec: 43505 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 77 +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-1.log 2>&1 +2023-05-04 01:02:55,082 - root - INFO - Deleting fuzz target: fuzz-bus-label. +2023-05-04 01:02:55,083 - root - INFO - Done deleting. +2023-05-04 01:02:55,084 - root - INFO - Fuzzer fuzz-bus-label finished running without reportable crashes. +2023-05-04 01:02:55,084 - root - INFO - Running fuzzer: fuzz-dhcp-server. +2023-05-04 01:02:55,085 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip +2023-05-04 01:02:55,088 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:02:55,145 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip HTTP/1.1" 200 806749 +2023-05-04 01:02:55,350 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83640 inline 8-bit counters): 82573 [0x7fe86ff70df0, 0x7fe86ff8507d), 1067 [0x60c638, 0x60ca63), +INFO: Loaded 2 PC tables (83640 PCs): 82573 [0x7fe86ff85080,0x7fe8700c7950), 1067 [0x60ca68,0x610d18), +INFO: 1153 files found in /github/workspace/cifuzz-corpus/fuzz-dhcp-server +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 1153 min: 1b max: 5242879b total: 17056071b rss: 50Mb +#1155 INITED cov: 577 ft: 1116 corp: 203/54Kb exec/s: 0 rss: 86Mb +#1167 NEW cov: 577 ft: 1117 corp: 204/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeASCIIInt-CrossOver- +#1509 NEW cov: 577 ft: 1118 corp: 205/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeBit-CopyPart- +#63018 NEW cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21006 rss: 86Mb L: 245/1071 MS: 4 InsertByte-ChangeByte-CMP-InsertByte- DE: "2\000\000\000\000\000\000\000"- +#65536 pulse cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21845 rss: 86Mb +Loaded 1024/1155 files from /github/workspace/cifuzz-corpus/fuzz-dhcp-server +#99784 NEW cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19956 rss: 105Mb L: 243/1071 MS: 2 ChangeASCIIInt-ChangeBinInt- +#131072 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 21845 rss: 105Mb +#262144 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 20164 rss: 105Mb +#275639 DONE cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19688 rss: 105Mb +###### Recommended dictionary. ###### +"2\000\000\000\000\000\000\000" # Uses: 17879 +###### End of recommended dictionary. ###### +Done 275639 runs in 14 second(s) +stat::number_of_executed_units: 275639 +stat::average_exec_per_sec: 19688 +stat::new_units_added: 4 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 105 +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-1.log 2>&1 +2023-05-04 01:03:18,374 - root - INFO - Not reporting crash in fuzz-dhcp-server because process timed out. +2023-05-04 01:03:18,377 - root - INFO - Deleting corpus and seed corpus of fuzz-dhcp-server to save disk. +2023-05-04 01:03:18,399 - root - INFO - Deleting fuzz target: fuzz-dhcp-server. +2023-05-04 01:03:18,400 - root - INFO - Done deleting. +2023-05-04 01:03:18,400 - root - INFO - Fuzzer fuzz-dhcp-server finished running without reportable crashes. +2023-05-04 01:03:18,401 - root - INFO - Running fuzzer: fuzz-bcd. +2023-05-04 01:03:18,401 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip +2023-05-04 01:03:18,404 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:18,582 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip HTTP/1.1" 200 2293254 +2023-05-04 01:03:18,804 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83175 inline 8-bit counters): 82573 [0x7f1b5387edf0, 0x7f1b5389307d), 602 [0x5f8718, 0x5f8972), +INFO: Loaded 2 PC tables (83175 PCs): 82573 [0x7f1b53893080,0x7f1b539d5950), 602 [0x5f8978,0x5faf18), +INFO: 1260 files found in /github/workspace/cifuzz-corpus/fuzz-bcd +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 946175 bytes +INFO: seed corpus: files: 1260 min: 1b max: 946175b total: 10373697b rss: 48Mb +#1261 INITED cov: 137 ft: 653 corp: 282/1416Kb exec/s: 0 rss: 91Mb +#65536 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#131072 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#262144 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 37449 rss: 98Mb +#475081 DONE cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 33934 rss: 98Mb +Done 475081 runs in 14 second(s) +stat::number_of_executed_units: 475081 +stat::average_exec_per_sec: 33934 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 98 +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-1.log 2>&1 +2023-05-04 01:03:41,821 - root - INFO - Not reporting crash in fuzz-bcd because process timed out. +2023-05-04 01:03:41,822 - root - INFO - Deleting corpus and seed corpus of fuzz-bcd to save disk. +2023-05-04 01:03:41,848 - root - INFO - Deleting fuzz target: fuzz-bcd. +2023-05-04 01:03:41,848 - root - INFO - Done deleting. +2023-05-04 01:03:41,848 - root - INFO - Fuzzer fuzz-bcd finished running without reportable crashes. +2023-05-04 01:03:41,848 - root - INFO - Running fuzzer: fuzz-varlink. +2023-05-04 01:03:41,849 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip +2023-05-04 01:03:41,852 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:41,906 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip HTTP/1.1" 200 2586434 +2023-05-04 01:03:42,671 - root - INFO - Starting fuzzing +2023-05-04 01:04:05,709 - root - INFO - Not reporting crash in fuzz-varlink because process timed out. +Fuzzing logs: +/github/workspace/build-out/fuzz-varlink -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpbtf4f932/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-varlink >fuzz-0.log 2>&1 +2023-05-04 01:04:05,709 - root - INFO - Deleting corpus and seed corpus of fuzz-varlink to save disk. +2023-05-04 01:04:05,806 - root - INFO - Deleting fuzz target: fuzz-varlink. +2023-05-04 01:04:05,806 - root - INFO - Done deleting. +2023-05-04 01:04:05,806 - root - INFO - Fuzzer fuzz-varlink finished running without reportable crashes. +2023-05-04 01:04:05,806 - root - INFO - Running fuzzer: fuzz-unit-file. +2023-05-04 01:04:05,807 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip +2023-05-04 01:04:05,809 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:04:05,897 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip HTTP/1.1" 200 4999974 +2023-05-04 01:04:07,869 - root - INFO - Starting fuzzing +2023-05-04 01:04:09,516 - root - INFO - Fuzzer: fuzz-unit-file. Detected bug. +Fuzzing logs: +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-0.log 2>&1 +2023-05-04 01:04:09,517 - root - INFO - Trying to reproduce crash using: /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03. +================== Job 0 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7f3b0de4cdf0, 0x7f3b0de6107d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7f3b0de61080,0x7f3b0dfa3950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==74==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7fffeea64fe0 sp 0x7fffeea64fd8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in samLLVM2FuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==74==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 67 +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7ff1ba038df0, 0x7ff1ba04d07d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7ff1ba04d080,0x7ff1ba18f950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==78==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7ffc2e6825c0 sp 0x7ffc2e6825b8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in samLLVM2FuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--samLLVM2FuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in samsamLLVM2FuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==78==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 68 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..120de50346ebeb22f0e173becb2f623e54e61139 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile @@ -0,0 +1,35 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in shell-quote v1.7.3. + +FROM ghcr.io/aixcc-finals/base-builder + +RUN apt update && \ + apt install -y \ + vim \ + npm && \ + git clone \ + --depth 1 \ + https://github.com/substack/node-shell-quote.git && \ + npm config set @gitlab-org:registry \ + https://gitlab.com/api/v4/packages/npm/ + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bdf30d06cc05af35782b5ee878a7a65a5ccdf107 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile @@ -0,0 +1,12 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 + +SystemSan: SystemSan.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +run: clean SystemSan target.js + ./SystemSan jsfuzz ./target.js + +clean: + rm -f SystemSan /tmp/tripwire diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js new file mode 100644 index 0000000000000000000000000000000000000000..82608cd2169fc7d757e0d69782a8eaa3b5e9cc88 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js @@ -0,0 +1,35 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* Exploit shell quote with fuzzer's input as a parameter of echo. + * This PoC is extended from a report in GitHub Advisory Database: + * https://github.com/advisories/GHSA-g4rg-993r-mgx7 + * The original report records a shell injection exploit in shell-quote v1.7.2, + * we show that a similar shell corruption exploit still persists in v1.7.3, + * after a commit that intends to fix the original exploit. + * */ + +/* Fuzz the target program with buf generated by Jsfuzz. */ +function fuzz(buf) { + buf = String(buf) + const childProcess = require('child_process'); + const shellQuote = require('shell-quote'); + childProcess.execSync(shellQuote.quote(['echo', buf])); +} + +/* Run Jsfuzz. */ +module.exports = { + fuzz +}; diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c577797f37169886ac3ffd48e12ad21c5986689d --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile @@ -0,0 +1,32 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in pytorch-lightning. + +FROM ghcr.io/aixcc-finals/base-builder-python + +RUN apt update && \ + apt install -y vim && \ + git clone \ + --depth 1 \ + --branch 1.5.10 \ + https://github.com/PyTorchLightning/pytorch-lightning.git + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2169bc15a592d7136d9d166159eb09dec8c49d01 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile @@ -0,0 +1,12 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 + +SystemSan: SystemSan.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +run: clean SystemSan fuzz_pytorch_lightning.py + ./SystemSan ./fuzz_pytorch_lightning.py -dict=vuln.dict + +clean: + rm -f SystemSan /tmp/tripwire diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c9b1adbf5a1b1241e50b8e88a03529cfb69e0b0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build and install project (using current CFLAGS, CXXFLAGS). +cd pytorch-lightning +pip3 install . + +# Build fuzzers in $OUT. +for fuzzer in $(find $SRC -name '*_fuzzer.py'); do + compile_python_fuzzer $fuzzer +done diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..0d07da3a6269381d688e8f3ac7da5d5d0ee7d04a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py @@ -0,0 +1,65 @@ +#!/usr/local/bin/python3 +# +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Exploit pytorch lightning with fuzzer's input as a random env variable. + +This PoC is extended from a report in GitHub Advisory Database: +https://github.com/advisories/GHSA-r5qj-cvf9-p85h +The original report documents an exploit using a specific environment variable, +we show a way to achieve the same exploit with an arbitrary env variable. +""" + +import os +import sys +import atheris + +with atheris.instrument_imports(): + from pytorch_lightning import Trainer + from pytorch_lightning.utilities.argparse import parse_env_variables + + +def prepare_fuzzing_input(data): + """Prepare the data needed by the exploit with input data from fuzzers.""" + data = data.replace(b'\0', b'') + env_name = 'AN_ARBITRARY_ENV_NAME' + return data, env_name + + +def exploit_target(env_value, env_name): + """This target is based on a snippet from the official documentation of + `parse_env_variables`: + https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.utilities.argparse.html # pylint: disable=line-too-long + It might not be the most realistic example, + but serves as a PoC to show that SystemSan works for Python.""" + os.environb[env_name.encode()] = env_value + parse_env_variables(Trainer, template=env_name) + + +def TestOneInput(data): # pylint: disable=invalid-name + """Exploit the target only with input data from fuzzers.""" + env_value, env_name = prepare_fuzzing_input(data) + exploit_target(env_value, env_name) + + +def main(): + """Fuzz target with atheris.""" + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..0d19aa407357659d0beb8487443c65eead7dab6a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict @@ -0,0 +1 @@ +"os.system('/tmp/tripwire')" diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h new file mode 100644 index 0000000000000000000000000000000000000000..849af4e980679c3b8cbbd875216a06ba7b909f3a --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h @@ -0,0 +1,26 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +/* Linux */ +#include + + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s); diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..579a46da68b2fb092a02ef73990be8d10dac7098 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/Dockerfile @@ -0,0 +1,18 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +FROM gcr.io/cloud-builders/gcloud + +RUN apt-get update && apt-get install -y jq \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/README.md b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67c59f71bd6108f0d12d1125e39f5a2a1eda9128 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/README.md @@ -0,0 +1,49 @@ +# Chronos: rebuilding OSS-Fuzz harnesses using cached builds + +## Pre-built images. + +Daily pre-built images are available at: + +- `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/-ofg-cached-address` +- `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/-ofg-cached-coverage` + +They can be used as drop-in replacements for the usual `gcr.io/oss-fuzz/` images. + +These images are generated in 2 ways: +- (Preferred) [Generate](https://github.com/google/oss-fuzz/blob/master/infra/base-images/base-builder/bash_parser.py) + a replay build script that can be re-run alongside existing build artifacts, + leveraging existing build system mechanisms to avoid rebuilding (e.g. running + `make` twice should not actually rebuild everything). This is error-prone, so + we validate the script works by running it. +- (Fallback, if the replay build script didn't work). We leverage + [ccache](https://ccache.dev/), to provide a compiler cache. This is often not + as fast as the replay build script, because some project builds spend + significant time doing non-compiler tasks (e.g. checking out submodules, + running configure scripts). + +Note: this mechanism does not work for every single OSS-Fuzz project today. The +resulting image may either: +- Not provide much performance improvement compared with a normal image, or +- Not exist at all (if neither approach worked). + +Stats from a recent run: +(Feb 3 2025). + +## Usage locally + +**Example 1: htslib** + +From the OSS-Fuzz root + +```sh +$ RUN_ALL=1 ./infra/experimental/chronos/build_cache_local.sh htslib c address +... +... +Vanilla compile time: +17 +Replay worked +Replay compile time: +2 +Ccache compile time: +9 +``` diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_all.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8f578084205f3ef21338021a525e1b043478302 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_all.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build all C/C++ projects. +c_project_yaml=$(find projects/ -name project.yaml -exec grep -l 'language: c' {} \;) +projs=$(echo $c_project_yaml | xargs dirname | xargs basename -a | sort) + +cd infra/experimental/chronos + +for proj in $projs; do + if [ ! -f ../../../projects/$proj/Dockerfile ]; then + # Incomplete integration. + echo "Skipping $proj as it's incomplete." + continue + fi + + echo ./build_on_cloudbuild.sh $proj c + ./build_on_cloudbuild.sh $proj c +done \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f3f20804f4ef9e9dbedd3275286bb4353ef422d --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh @@ -0,0 +1,163 @@ +#!/bin/bash -eu +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +_PROJECT=$1 +_FUZZING_LANGUAGE=$2 +_SANITIZER=${3:-address} + +BASE=$PWD + +# Final image is either ccache or replay script, depending on which worked. +FINAL_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-${_SANITIZER} + +# Always build an image with ccache. +CCACHE_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-${_SANITIZER} + +# Step 1: build the base image +cd projects/${_PROJECT} +docker build -t gcr.io/oss-fuzz/${_PROJECT} . + + +# Step 2: create a container where `compile` has run which enables ccaching +# and also generates a replay build script. +cd ${BASE} +mkdir -p ccaches/${_PROJECT} +mkdir -p build/out/${_PROJECT} +B_START=$SECONDS + +docker container rm -f ${_PROJECT}-origin-${_SANITIZER} + +docker run \ + --env=SANITIZER=${_SANITIZER} \ + --env=CCACHE_DIR=/workspace/ccache \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --env=CAPTURE_REPLAY_SCRIPT=1 \ + --name=${_PROJECT}-origin-${_SANITIZER} \ + -v=$PWD/ccaches/${_PROJECT}/ccache:/workspace/ccache \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + gcr.io/oss-fuzz/${_PROJECT} \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && compile" +B_TIME=$(($SECONDS - $B_START)) + +# Step 3: save (commit, locally) the cached container as an image +docker container commit -c "ENV REPLAY_ENABLED=1" -c "ENV CAPTURE_REPLAY_SCRIPT=" ${_PROJECT}-origin-${_SANITIZER} $FINAL_IMAGE_NAME + +# Step 4: save the list of executables created from a vanilla build. This is +# needed for validating if replay and ccaching works. +# notes: run a shell the container with e.g. +# `docker run --entrypoint /bin/bash -it local/ossfuzz/htslib-origin-address` +executables_vanilla="$(find ./build/out/${_PROJECT} -executable -type f | sort)" + + +# Step 5: Build with replay enabled, and validate the executables are the same +# in terms of naming. +# Note that an important step is removing everything in $OUT/ which is done +# in the docker command. +R_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + --name=${_PROJECT}-origin-${_SANITIZER}-replay-recached \ + $FINAL_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +R_TIME=$(($SECONDS - $R_START)) + +# Step 6: Extract the newly build executables +executables_replay="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + +echo "Executables vanilla: " +echo ${executables_vanilla} + +echo "------------------------------------------------------" +echo "Executables replay: " +echo ${executables_replay} + +REPLAY_WORKED= + +# Step 7: match executables from vanilla builds and replay builds. +# If this step is successful, then the process can exit as it's ready. +if [[ "$executables_replay" == "$executables_vanilla" ]] +then + REPLAY_WORKED=1 + + if [ -z "${RUN_ALL+1}" ]; then + echo "${_PROJECT}: Replay worked." + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME};" + exit 0 + fi +else + echo "${_PROJECT}: Replay did not work" + R_TIME="N/A" +fi + +# Step 8: prepare Dockerfile for ccache +cp -rf ccaches/${_PROJECT}/ccache ./projects/${_PROJECT}/ccache-cache + +infra/experimental/chronos/prepare-ccache ${_PROJECT} + +cd projects/${_PROJECT} + +# Step 9: Build an image with CCache's new items (modifications are done on the +# dockerfile) +docker build -t $CCACHE_IMAGE_NAME . + +cd ${BASE} + +# Step 10: Run a `compile` with ccache's image. +# Run the ccache build +A_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --name=${_PROJECT}-origin-${_SANITIZER}-recached \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + $CCACHE_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +A_TIME=$(($SECONDS - $A_START)) + +# Step 11: extract the executables from the ccache build +executables_ccache="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + + +# Step 12: validate the ccache builds are successful +if [[ "$executables_ccache" == "$executables_vanilla" ]] +then + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME}; CCache=${A_TIME};" + + if [[ -z "${REPLAY_WORKED}" || ${R_TIME} -gt ${A_TIME} ]]; then + if [ ${R_TIME} -gt ${A_TIME} ]; then + echo "Replay was slower than ccache." + fi + + # Replay didn't work or was slower, so make the default "cached" image use the ccache one. + docker image tag \ + $CCACHE_IMAGE_NAME \ + $FINAL_IMAGE_NAME + fi + + exit 0 +else + echo "${_PROJECT}: Replay and ccaching did not work." + exit 1 +fi + diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/chronos.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/chronos.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd83b49095eafd5264d16195d5f80c4d204e8dbd --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/chronos.sh @@ -0,0 +1,81 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# This script records the ENV and commands needed for fuzz target recompilation. +# It intercepts bash commands to save: 1) the ENV variable values before +# building the fuzz target (`recompile_env.sh`) and 2) all subsequent bash +# commands from that point (`recompile`). Combined with Docker, this setup +# allows for recompiling the fuzz target without rebuilding the entire project. +# Usage: +# 1. Set FUZZ_TARGET (e.g., in project's Dockerfile) +# 2. Source this file before compiling the fuzz target (e.g., source chronos.sh +# at the beginning of project's build.sh). + +export START_RECORDING="false" +RECOMPILE_ENV="/usr/local/bin/recompile_env.sh" + + +# Initialize the recompile script as compile in case Chronos did not trap any +# command containing the fuzz target. +initialize_recompile_script() { + export RECOMPILE_SCRIPT="/usr/local/bin/recompile" + cp "/usr/local/bin/compile" "$RECOMPILE_SCRIPT" +} + +reset_recompile_script() { + rm "$RECOMPILE_SCRIPT" + echo "#!/bin/bash" > "$RECOMPILE_SCRIPT" + echo "source $RECOMPILE_ENV" >> "$RECOMPILE_SCRIPT" + chmod +x "$RECOMPILE_SCRIPT" +} + + +# Execute or record command for recompilation. +execute_or_record_command() { + record_command() { + echo "cd \"$(pwd)\"" >> "$RECOMPILE_SCRIPT" + echo "$@" >> "$RECOMPILE_SCRIPT" + } + + # Check if any element in the command array contains the FUZZ_TARGET. + if [[ "$BASH_COMMAND" == *"$FUZZ_TARGET"* ]]; then + export START_RECORDING="true" + # Save all environment variables, excluding read-only ones + reset_recompile_script + declare -p | grep -Ev 'declare -[^ ]*r[^ ]*' > "$RECOMPILE_ENV" + fi + + if [[ "$START_RECORDING" == "true" ]]; then + record_command "$BASH_COMMAND" + echo "Recorded execution of: $BASH_COMMAND" + fi +} + + +main() { + # Initialize. + initialize_recompile_script + + # Set up trap for DEBUG to intercept commands. + trap 'execute_or_record_command' DEBUG + + # Enable extended debugging mode + shopt -s extdebug + # Ensure trap works in subshells and functions. + set -T +} + +main diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7f584fc77bf03a7a1a71c784be1fce9c83aa5cd5 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml @@ -0,0 +1,58 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +# Supports building by way of ccache now. +# High-level steps: +# 1) Build image for project +# 2) Run an ASAN build and store ccache +# 3) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 4) Build image for project and copy ccache in, storing image as *-ofg-cache-address +# 5) Run an coverage build and store ccache +# 6) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 7) Build image for project and copy ccache in, storing image as *-ofg-cache-coverage +# TODO (David): add support for use of dedicated replay_build.sh +steps: +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - address + env: + - RUN_ALL=1 +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - coverage + env: + - RUN_ALL=1 +images: +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-coverage +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-coverage +timeout: 72000s # 20 hours, same as build_lib.py +logsBucket: oss-fuzz-gcb-logs +tags: +- ${_PROJECT} +- chronos +options: + pool: + name: projects/oss-fuzz/locations/us-central1/workerPools/buildpool-chronos diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e336525bedafd2843b82f45f5cc92721375362c3 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - -t + - gcloud + - . + dir: infra/experimental/chronos +- name: 'gcloud' + args: + - infra/experimental/chronos/build_all.sh + entrypoint: /bin/bash +timeout: 1800s +serviceAccount: 'projects/oss-fuzz/serviceAccounts/llm-eval@oss-fuzz.iam.gserviceaccount.com' +options: + logging: CLOUD_LOGGING_ONLY +tags: +- chronos-all \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh new file mode 100644 index 0000000000000000000000000000000000000000..f48b335c552a0dd5347d72dcd5d0b566e6782ab6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh @@ -0,0 +1,63 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Sample projects: simd, wt, libheif, htslib +PROJECT=liblouis +LOG=replay-${PROJECT}.txt +OUT1=replay-out-${PROJECT}-1 +OUT2=replay-out-${PROJECT}-2 +python infra/helper.py build_image --no-pull "$PROJECT" + +# AddressSanitizer. +mkdir -p build/out/${PROJECT} +echo "start" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +# Remove container name we are about to use. +docker container rm "${PROJECT}-origin-asan" + +# Build once, clean container if needed +docker run -v $PWD/build/out/${PROJECT}:/out \ + -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + --name "${PROJECT}-origin-asan" \ + "gcr.io/oss-fuzz/${PROJECT}" -c "compile" + +# Copy outs and log data +cp -rf $PWD/build/out/${PROJECT} ${OUT1} +rm -rf $PWD/build/out/${PROJECT} +ls -la $PWD/build/out/ >> ${LOG} +echo "next" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +docker commit "${PROJECT}-origin-asan" "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" + +# Run the replay command +docker run -v $PWD/build/out/${PROJECT}:/out \ + -e REPLAY_ENABLED=1 -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" -c "compile" +echo "finish" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +cp -rf $PWD/build/out/${PROJECT} ${OUT2} + +# Now match the artifacts +SUCCESS=$(infra/experimental/chronos/match_artifacts $OUT1 $OUT2) + +if [[ $SUCCESS -eq 0 ]]; then + echo "SUCCESS REPLAY" >> ${LOG} +else + echo "FAIL REPLAY" >> ${LOG} +fi diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/prepare-ccache b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/prepare-ccache new file mode 100644 index 0000000000000000000000000000000000000000..3b0f56719680dc7cbda30a7ab2b18b61365de5bb --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/prepare-ccache @@ -0,0 +1,22 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "COPY ccache-cache/ /ccache/cache"; + echo "ENV PATH=\"/ccache/bin:\$PATH\"" +} >> "projects/$PROJECT/Dockerfile" diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3142ae038ae6b65902623f39df75b349ff7f67b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md @@ -0,0 +1,3 @@ +# Moved + +This has moved to . diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/.gitignore b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..30d9eff972346c4978622c6f567e7808ad21764d --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/.gitignore @@ -0,0 +1 @@ +wycheproof.zip \ No newline at end of file diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/generate_job.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/generate_job.py new file mode 100644 index 0000000000000000000000000000000000000000..508162e3110522d09ec4f671c7ac2c2e188e5ee7 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/generate_job.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Script for generating an OSS-Fuzz job for a wycheproof project.""" +import sys + + +def main(): + """Usage generate_job.py .""" + project = sys.argv[1] + print(f'Name: wycheproof_nosanitizer_{project}') + job_definition = f"""CUSTOM_BINARY = False +BAD_BUILD_CHECK = False +APP_NAME = WycheproofTarget.bash +THREAD_ALIVE_CHECK_INTERVAL = 10 +TEST_TIMEOUT = 3600 +CRASH_RETRIES = 1 +AGGREGATE_COVERAGE = False +TESTCASE_COVERAGE = False +FILE_GITHUB_ISSUE = False +MANAGED = False +MAX_FUZZ_THREADS = 1 +RELEASE_BUILD_BUCKET_PATH = gs://clusterfuzz-builds-wycheproof/{project}/{project}-none-([0-9]+).zip +PROJECT_NAME = {project} +SUMMARY_PREFIX = {project} +REVISION_VARS_URL = https://commondatastorage.googleapis.com/clusterfuzz-builds-wycheproof/{project}/{project}-none-%s.srcmap.json +FUZZ_LOGS_BUCKET = {project}-logs.clusterfuzz-external.appspot.com +CORPUS_BUCKET = {project}-corpus.clusterfuzz-external.appspot.com +QUARANTINE_BUCKET = {project}-quarantine.clusterfuzz-external.appspot.com +BACKUP_BUCKET = {project}-backup.clusterfuzz-external.appspot.com +AUTOMATIC_LABELS = Proj-{project},Engine-wycheproof +""" + print(job_definition) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/launcher.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca8435d12c20fd7f5f932cda0588ca10ff1070b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/launcher.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Script for running wycheproof.""" + +import logging +import sys +import subprocess + + +def main(): + """Runs wycheproof.""" + if len(sys.argv) < 3: + logging.error('Usage: %s .', sys.argv[0]) + return 1 + + return subprocess.run(sys.argv[1:], check=False).returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/package.bash b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/package.bash new file mode 100644 index 0000000000000000000000000000000000000000..842222587d1c414fba9451a9ac573f9cf35c93e1 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/package.bash @@ -0,0 +1,18 @@ +#!/bin/bash +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# Script for zipping ClusterFuzz's blackbox fuzzer for wycheproof. +zip wycheproof.zip run.py launcher.py diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/run.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/run.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca11ef3e1a6c49744094776babbd0e029809c6f --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/wycheproof/run.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Script for creating "testcases" to run wycheproof on.""" + +import argparse +import os +import sys + + +def get_args(): + """Returns parsed program arguments.""" + parser = argparse.ArgumentParser() + parser.add_argument( + '--input_dir', + help='Ignored.', + ) + parser.add_argument('--output_dir', + help='Directory for writing testcases.', + required=True) + parser.add_argument('--no_of_files', type=int, help='Ignored.') + return parser.parse_args() + + +def main(): + """Generates a dummy testcase for use by a ClusterFuzz blackbox fuzzer.""" + args = get_args() + if not os.path.exists(args.output_dir): + os.mkdir(args.output_dir) + testcase = os.path.join(args.output_dir, 'fuzz-0') + with open(testcase, 'w') as file_handle: + file_handle.write(' ') + return 0 + + +if __name__ == '__main__': + sys.exit(main())