| // Copyright 2026 The Dawn & Tint Authors | |
| // | |
| // Redistribution and use in source and binary forms, with or without | |
| // modification, are permitted provided that the following conditions are met: | |
| // | |
| // 1. Redistributions of source code must retain the above copyright notice, this | |
| // list of conditions and the following disclaimer. | |
| // | |
| // 2. Redistributions in binary form must reproduce the above copyright notice, | |
| // this list of conditions and the following disclaimer in the documentation | |
| // and/or other materials provided with the distribution. | |
| // | |
| // 3. Neither the name of the copyright holder nor the names of its | |
| // contributors may be used to endorse or promote products derived from | |
| // this software without specific prior written permission. | |
| // | |
| // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
| // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
| // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
| // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
| // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
| // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
| // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| #include "src/tint/cmd/fuzz/common/fuzztest/init.h" | |
| #include <algorithm> | |
| #include <cstddef> | |
| #include <filesystem> | |
| #include <fstream> | |
| #include <iostream> | |
| #include <system_error> | |
| #include <utility> | |
| #include "src/tint/utils/command/args.h" | |
| #include "src/tint/utils/command/cli.h" | |
| #include "src/tint/utils/macros/compiler.h" | |
| #include "src/tint/utils/system/executable_path.h" | |
| TINT_BEGIN_DISABLE_ALL_WARNINGS(); | |
| #include "fuzztest/fuzztest_macros.h" | |
| #include "fuzztest/init_fuzztest.h" | |
| #include "gtest/gtest.h" | |
| TINT_END_DISABLE_ALL_WARNINGS(); | |
| namespace tint::fuzz::common { | |
| namespace { | |
| #if !defined(FUZZTEST_USE_CENTIPEDE) | |
| /// Default libFuzzer `-max_len` synthesized in compatibility mode when unspecified so FuzzTest's | |
| /// serialized `FUZZTESTv1` `IRObject` payloads (for 10,000-byte raw WGSL seeds, grammar ASTs, and | |
| /// IR protobufs) are not truncated by libFuzzer's 4,096-byte default limit. | |
| constexpr std::string_view kDefaultLibFuzzerMaxLenFlag = "-max_len=65536"; | |
| #endif | |
| /// Header prefix written by FuzzTest's `IRObject` corpus serializer in compatibility mode. | |
| constexpr std::string_view kFuzzTestCorpusHeader = "FUZZTESTv1"; | |
| /// Configuration state for FuzzTest fuzzing. Is a separate singleton, | |
| /// so that both the CLI and FUZZ_TEST entry points can access it | |
| struct FuzzTestConfig { | |
| std::string dict_path; | |
| std::vector<std::filesystem::path> seed_dirs; | |
| }; | |
| FuzzTestConfig& GetConfig() { | |
| static FuzzTestConfig cfg; | |
| return cfg; | |
| } | |
| /// Checks that all characters are within the ASCII range | |
| bool IsAllAscii(std::string_view str) { | |
| return std::ranges::all_of(str, | |
| [](const char c) { return static_cast<unsigned char>(c) <= 127u; }); | |
| } | |
| /// Read up to a maximum number of bytes out of a file, rejecting overly long inputs | |
| bool ReadBinaryFileBounded(const std::filesystem::path& path, | |
| size_t max_bytes, | |
| std::string* out_data) { | |
| std::error_code ec; | |
| if (std::filesystem::is_directory(path, ec) || ec) { | |
| return false; | |
| } | |
| std::ifstream stream(path, std::ios::binary | std::ios::ate); | |
| if (!stream.good()) { | |
| return false; | |
| } | |
| const std::streampos end_pos = stream.tellg(); | |
| if (end_pos <= 0 || static_cast<size_t>(end_pos) > max_bytes) { | |
| return false; | |
| } | |
| const auto file_size = static_cast<size_t>(end_pos); | |
| stream.seekg(0, std::ios::beg); | |
| std::string data(file_size, '\0'); | |
| stream.read(data.data(), static_cast<std::streamsize>(file_size)); | |
| if (stream.gcount() != static_cast<std::streamsize>(file_size)) { | |
| return false; | |
| } | |
| *out_data = std::move(data); | |
| return true; | |
| } | |
| /// Adapts the Tint Fuzzer style environment for FuzzTest execution | |
| class FuzzTestContext { | |
| public: | |
| FuzzTestContext(FuzzerType type, | |
| std::string_view default_fuzz_test, | |
| Options* options, | |
| FuzzerMode mode) | |
| : type_(type), | |
| default_fuzz_test_(default_fuzz_test), | |
| options_(options), | |
| mode_(mode), | |
| opt_list_fuzz_tests_( | |
| opts_.Add<tint::cli::BoolOption>("list_fuzz_tests", | |
| "List registered Suite.Test fuzz tests and exit")), | |
| opt_gtest_list_tests_(opts_.Add<tint::cli::BoolOption>("gtest_list_tests", | |
| "List GoogleTest tests and exit")), | |
| opt_fuzz_(opts_.Add<tint::cli::StringOption>( | |
| "fuzz", | |
| "Select the fuzz test to run (default: " + std::string(default_fuzz_test) + ")")), | |
| opt_fuzz_for_( | |
| opts_.Add<tint::cli::StringOption>("fuzz_for", "Fuzz for a specified duration")), | |
| opt_replay_corpus_( | |
| opts_.Add<tint::cli::StringOption>("replay_corpus", "Replay inputs from a corpus")), | |
| opt_replay_corpus_for_(opts_.Add<tint::cli::StringOption>( | |
| "replay_corpus_for", | |
| "Replay inputs from a corpus for a specified duration")), | |
| opt_gtest_filter_( | |
| opts_.Add<tint::cli::StringOption>("gtest_filter", "Filter GoogleTest tests")), | |
| opt_stack_limit_kb_( | |
| opts_.Add<tint::cli::StringOption>("stack_limit_kb", "Stack limit in KiB")), | |
| opt_seed_dir_(opts_.Add<tint::cli::StringOption>( | |
| "seed_dir", | |
| "Additional directory of raw seed files to load")) { | |
| if (type_ == FuzzerType::kWGSL) { | |
| opt_dict_ = &opts_.Add<tint::cli::StringOption>( | |
| "dict", "Dictionary file for raw WGSL string domains"); | |
| } | |
| #if !defined(FUZZTEST_USE_CENTIPEDE) | |
| opt_max_len_ = | |
| &opts_.Add<tint::cli::StringOption>("max_len", "Maximum input length for libFuzzer"); | |
| #endif | |
| } | |
| /// Parses wrapper and Tint flags, initializes the active fuzzing/test frameworks, and executes | |
| /// the selected fuzz tests. | |
| /// @param argc argument count from `main` | |
| /// @param argv argument vector from `main` (may be compacted in-place) | |
| /// @returns process exit code from option parsing or test execution | |
| int Run(int argc, char** argv) { | |
| auto& cfg = GetConfig(); | |
| cfg.dict_path.clear(); | |
| cfg.seed_dirs.clear(); | |
| tint::cli::ParseOptions parse_opts; | |
| parse_opts.ignore_unknown = true; | |
| if (auto res = opts_.Parse(&argc, &argv, parse_opts); res != tint::Success) { | |
| std::cerr << res.Failure() << "\n"; | |
| return 1; | |
| } | |
| if (opt_seed_dir_.value.has_value() && !opt_seed_dir_.value->empty()) { | |
| std::error_code ec; | |
| if (std::filesystem::is_directory(*opt_seed_dir_.value, ec) && !ec) { | |
| cfg.seed_dirs.emplace_back(*opt_seed_dir_.value); | |
| } else { | |
| std::cerr << "Warning: --seed_dir '" << *opt_seed_dir_.value | |
| << "' does not exist or is not a directory\n"; | |
| } | |
| } | |
| if (opt_dict_ != nullptr && opt_dict_->value.has_value()) { | |
| cfg.dict_path = *opt_dict_->value; | |
| } | |
| const bool is_listing = opt_list_fuzz_tests_.value.value_or(false) || | |
| opt_gtest_list_tests_.value.value_or(false); | |
| bool showed_help = false; | |
| if (!is_listing) { | |
| const int res = ParseFuzzerOptions(type_, &argc, &argv, options_, &showed_help); | |
| if (res != 0) { | |
| return res; | |
| } | |
| if (showed_help) { | |
| #if defined(FUZZTEST_USE_CENTIPEDE) | |
| std::cerr << "\nFuzzTest prototype options:\n"; | |
| opts_.ShowHelp(std::cerr, true); | |
| std::cerr << "\n"; | |
| return 0; | |
| #else | |
| // `ParseFuzzerOptions` leaves `"Standard libfuzzer "` without a trailing newline | |
| // and rewrites `argv` to `{argv[0], "-help=1"}`. | |
| std::cerr << "options follow below.\n\nFuzzTest prototype options:\n"; | |
| opts_.ShowHelp(std::cerr, true); | |
| std::cerr << "\n"; | |
| #endif | |
| } | |
| #if TINT_BUILD_FUZZER_VULKAN_SUPPORT | |
| if (!showed_help && mode_ == FuzzerMode::kMesa && !ConfigureMesaOptions()) { | |
| return 0; | |
| } | |
| #endif | |
| } | |
| std::vector<std::string> forwarded_args; | |
| const auto remaining = tint::args::Vectorize(argc, const_cast<const char**>(argv)); | |
| forwarded_args.reserve(remaining.Length() + 10); | |
| forwarded_args.push_back(tint::ExecutablePath()); | |
| for (std::string_view arg : remaining) { | |
| if (!showed_help && !arg.empty() && !arg.starts_with("-")) { | |
| // Only treat existing directories as raw seed sources. Non-directory tokens are | |
| // forwarded without warning because they may be individual libFuzzer input/repro | |
| // files (validated by LLVMFuzzerRunDriver) or values of unknown space-separated | |
| // framework flags. | |
| std::error_code ec; | |
| if (std::filesystem::is_directory(arg, ec) && !ec) { | |
| cfg.seed_dirs.emplace_back(arg); | |
| } | |
| } | |
| forwarded_args.emplace_back(arg); | |
| } | |
| SynthesizeFrameworkFlags(showed_help, is_listing, &forwarded_args); | |
| return LaunchFrameworks(&forwarded_args); | |
| } | |
| private: | |
| #if TINT_BUILD_FUZZER_VULKAN_SUPPORT | |
| /// Configures `options_` for Mesa Lavapipe SPIR-V fuzzing. | |
| /// @returns true if startup should continue, false if the Vulkan ICD JSON is unavailable | |
| bool ConfigureMesaOptions() { | |
| options_->filter = "tint::spirv::writer::IRFuzzer"; | |
| std::error_code ec; | |
| if (options_->vk_icd.empty() || !std::filesystem::exists(options_->vk_icd, ec) || ec) { | |
| std::cerr << "Vulkan ICD JSON not found or does not exist: '" << options_->vk_icd | |
| << "'. Exiting early.\n"; | |
| return false; | |
| } | |
| return true; | |
| } | |
| #endif | |
| /// Appends normalized wrapper flags and engine defaults to `forwarded_args`. | |
| void SynthesizeFrameworkFlags(bool showed_help, | |
| [[maybe_unused]] bool is_listing, | |
| std::vector<std::string>* forwarded_args) { | |
| if (showed_help) { | |
| if (!default_fuzz_test_.empty()) { | |
| forwarded_args->push_back("--fuzz=" + std::string(default_fuzz_test_)); | |
| } | |
| forwarded_args->emplace_back("--stack_limit_kb=0"); | |
| return; | |
| } | |
| #if !defined(FUZZTEST_USE_CENTIPEDE) | |
| if (opt_dict_ != nullptr && opt_dict_->value.has_value()) { | |
| forwarded_args->push_back("-dict=" + *opt_dict_->value); | |
| } | |
| #endif | |
| auto forward_str = [&](std::string_view prefix, const tint::cli::StringOption& opt) { | |
| if (opt.value.has_value()) { | |
| forwarded_args->push_back(std::string(prefix) + *opt.value); | |
| } | |
| }; | |
| auto forward_bool = [&](std::string_view prefix, const tint::cli::BoolOption& opt) { | |
| if (opt.value.has_value()) { | |
| forwarded_args->push_back(std::string(prefix) + (*opt.value ? "true" : "false")); | |
| } | |
| }; | |
| // Normalize bare `--list_fuzz_tests` to `--list_fuzz_tests=true` so Abseil flag parsing | |
| // succeeds in GN `is_component_build = true` builds across DSOs. | |
| forward_bool("--list_fuzz_tests=", opt_list_fuzz_tests_); | |
| forward_bool("--gtest_list_tests=", opt_gtest_list_tests_); | |
| forward_str("--fuzz=", opt_fuzz_); | |
| forward_str("--fuzz_for=", opt_fuzz_for_); | |
| forward_str("--replay_corpus=", opt_replay_corpus_); | |
| forward_str("--replay_corpus_for=", opt_replay_corpus_for_); | |
| forward_str("--gtest_filter=", opt_gtest_filter_); | |
| const bool has_explicit_mode = | |
| opt_list_fuzz_tests_.value.has_value() || opt_gtest_list_tests_.value.has_value() || | |
| opt_fuzz_.value.has_value() || opt_replay_corpus_.value.has_value() || | |
| opt_replay_corpus_for_.value.has_value() || opt_gtest_filter_.value.has_value(); | |
| const bool use_default_fuzz_test = !has_explicit_mode && !default_fuzz_test_.empty(); | |
| if (use_default_fuzz_test) { | |
| forwarded_args->push_back("--fuzz=" + std::string(default_fuzz_test_)); | |
| } | |
| // Disable FuzzTest's 128 KiB default stack limit when unspecified to match libFuzzer and | |
| // Chromium's `fuzzer_test.gni` configuration; Tint writers, DXC, and Mesa Lavapipe | |
| // routinely exceed 128 KiB of stack under ASan. | |
| forwarded_args->push_back("--stack_limit_kb=" + opt_stack_limit_kb_.value.value_or("0")); | |
| #if !defined(FUZZTEST_USE_CENTIPEDE) | |
| const bool has_fuzz_mode = | |
| use_default_fuzz_test || opt_fuzz_.value.has_value() || opt_fuzz_for_.value.has_value(); | |
| if (opt_max_len_ != nullptr && opt_max_len_->value.has_value()) { | |
| forwarded_args->push_back("-max_len=" + *opt_max_len_->value); | |
| } else if (has_fuzz_mode && !is_listing) { | |
| forwarded_args->emplace_back(kDefaultLibFuzzerMaxLenFlag); | |
| } | |
| #endif | |
| } | |
| /// Initializes GoogleTest, Abseil, and FuzzTest from `forwarded_args` and executes tests. | |
| int LaunchFrameworks(std::vector<std::string>* forwarded_args) { | |
| std::vector<char*> eff_argv; | |
| eff_argv.reserve(forwarded_args->size() + 1); | |
| for (auto& s : *forwarded_args) { | |
| eff_argv.push_back(s.data()); | |
| } | |
| eff_argv.push_back(nullptr); | |
| int eff_argc = static_cast<int>(forwarded_args->size()); | |
| testing::InitGoogleTest(&eff_argc, eff_argv.data()); | |
| #if defined(FUZZTEST_USE_CENTIPEDE) | |
| ::fuzztest::ParseAbslFlags(eff_argc, eff_argv.data()); | |
| #else | |
| // Pass only `--*` options to Abseil so single-dash libFuzzer flags (such as `-jobs=0` or | |
| // `-rss_limit_mb=...`) are handled exclusively by `LLVMFuzzerRunDriver`. | |
| std::vector<char*> absl_argv; | |
| absl_argv.reserve(static_cast<size_t>(eff_argc) + 1); | |
| if (eff_argc > 0) { | |
| absl_argv.push_back(eff_argv[0]); | |
| for (int i = 1; i < eff_argc; ++i) { | |
| char* arg = eff_argv[static_cast<size_t>(i)]; | |
| if (arg != nullptr && std::string_view(arg).starts_with("--")) { | |
| absl_argv.push_back(arg); | |
| } | |
| } | |
| } | |
| absl_argv.push_back(nullptr); | |
| ::fuzztest::ParseAbslFlags(static_cast<int>(absl_argv.size() - 1), absl_argv.data()); | |
| #endif | |
| char** argv_ptr = eff_argv.data(); | |
| ::fuzztest::InitFuzzTest(&eff_argc, &argv_ptr); | |
| return RUN_ALL_TESTS(); | |
| } | |
| FuzzerType type_; | |
| std::string_view default_fuzz_test_; | |
| Options* options_; | |
| [[maybe_unused]] FuzzerMode mode_; | |
| tint::cli::OptionSet opts_; | |
| tint::cli::BoolOption& opt_list_fuzz_tests_; | |
| tint::cli::BoolOption& opt_gtest_list_tests_; | |
| tint::cli::StringOption& opt_fuzz_; | |
| tint::cli::StringOption& opt_fuzz_for_; | |
| tint::cli::StringOption& opt_replay_corpus_; | |
| tint::cli::StringOption& opt_replay_corpus_for_; | |
| tint::cli::StringOption& opt_gtest_filter_; | |
| tint::cli::StringOption& opt_stack_limit_kb_; | |
| tint::cli::StringOption& opt_seed_dir_; | |
| tint::cli::StringOption* opt_dict_ = nullptr; | |
| #if !defined(FUZZTEST_USE_CENTIPEDE) | |
| tint::cli::StringOption* opt_max_len_ = nullptr; | |
| #endif | |
| }; | |
| } // namespace | |
| int RunFuzzTestMain(FuzzerType type, | |
| int argc, | |
| char** argv, | |
| std::string_view default_fuzz_test, | |
| Options* options, | |
| FuzzerMode mode) { | |
| return FuzzTestContext(type, default_fuzz_test, options, mode).Run(argc, argv); | |
| } | |
| void ForEachRawSeedFile(const std::function<void(std::string&&)>& visitor, size_t max_bytes) { | |
| const auto& cfg = GetConfig(); | |
| if (cfg.seed_dirs.empty()) { | |
| return; | |
| } | |
| std::vector<std::filesystem::path> candidate_files; | |
| constexpr auto kIterOpts = std::filesystem::directory_options::skip_permission_denied; | |
| for (const auto& dir : cfg.seed_dirs) { | |
| std::error_code ec; | |
| if (!std::filesystem::is_directory(dir, ec) || ec) { | |
| continue; | |
| } | |
| for (std::filesystem::recursive_directory_iterator it(dir, kIterOpts, ec), end; | |
| !ec && it != end; it.increment(ec)) { | |
| std::error_code entry_ec; | |
| if (it->is_regular_file(entry_ec) && !entry_ec) { | |
| candidate_files.push_back(it->path().lexically_normal()); | |
| } | |
| } | |
| } | |
| std::ranges::sort(candidate_files); | |
| auto unique_end = std::ranges::unique(candidate_files); | |
| candidate_files.erase(unique_end.begin(), unique_end.end()); | |
| for (const auto& file_path : candidate_files) { | |
| std::string data; | |
| if (!ReadBinaryFileBounded(file_path, max_bytes, &data)) { | |
| continue; | |
| } | |
| if (std::string_view(data).starts_with(kFuzzTestCorpusHeader)) { | |
| continue; | |
| } | |
| visitor(std::move(data)); | |
| } | |
| } | |
| std::vector<std::string> LoadWgslDictionary() { | |
| const std::string& dict_path = GetConfig().dict_path; | |
| if (dict_path.empty()) { | |
| return {}; | |
| } | |
| std::string text; | |
| if (!ReadBinaryFileBounded(dict_path, kMaxRawSeedReadBytes, &text)) { | |
| std::cerr << "Warning: Failed to read WGSL dictionary '" << dict_path << "'\n"; | |
| return {}; | |
| } | |
| auto parsed = ::fuzztest::ParseDictionary(text); | |
| if (!parsed.ok()) { | |
| std::cerr << "Warning: Failed to parse WGSL dictionary '" << dict_path | |
| << "': " << parsed.status().message() << "\n"; | |
| return {}; | |
| } | |
| std::vector<std::string> entries; | |
| entries.reserve(parsed->size()); | |
| for (auto& entry : *parsed) { | |
| if (!entry.empty() && entry.size() <= kMaxWgslFuzzSize && IsAllAscii(entry)) { | |
| entries.push_back(std::move(entry)); | |
| } | |
| } | |
| return entries; | |
| } | |
| std::vector<std::string> LoadRawWgslSeeds() { | |
| std::vector<std::string> seeds; | |
| ForEachRawSeedFile( | |
| [&seeds](std::string&& data) { | |
| if (IsAllAscii(data)) { | |
| seeds.push_back(std::move(data)); | |
| } | |
| }, | |
| kMaxWgslFuzzSize); | |
| return seeds; | |
| } | |
| } // namespace tint::fuzz::common |