fuzzer_util.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/fuzzing/fuzzer_util.h"
  5. #include <google/protobuf/text_format.h>
  6. #include "common/check.h"
  7. #include "common/error.h"
  8. #include "explorer/parse_and_execute/parse_and_execute.h"
  9. #include "llvm/Support/FileSystem.h"
  10. #include "llvm/Support/Path.h"
  11. #include "testing/fuzzing/proto_to_carbon.h"
  12. #include "tools/cpp/runfiles/runfiles.h"
  13. namespace Carbon::Testing {
  14. auto GetRunfilesFile(const std::string& file) -> ErrorOr<std::string> {
  15. using bazel::tools::cpp::runfiles::Runfiles;
  16. std::string error;
  17. // `Runfiles::Create()` fails if passed an empty `argv0`.
  18. std::unique_ptr<Runfiles> runfiles(Runfiles::Create(
  19. /*argv0=*/llvm::sys::fs::getMainExecutable(nullptr, nullptr), &error));
  20. if (runfiles == nullptr) {
  21. return Error(error);
  22. }
  23. std::string full_path = runfiles->Rlocation(file);
  24. if (!llvm::sys::fs::exists(full_path)) {
  25. return ErrorBuilder() << full_path << " doesn't exist";
  26. }
  27. return full_path;
  28. }
  29. auto ParseAndExecuteProto(const Fuzzing::Carbon& carbon) -> ErrorOr<int> {
  30. llvm::vfs::InMemoryFileSystem fs;
  31. const ErrorOr<std::string> prelude_path =
  32. GetRunfilesFile("carbon/explorer/data/prelude.carbon");
  33. // Can't do anything without a prelude, so it's a fatal error.
  34. CARBON_CHECK(prelude_path.ok()) << prelude_path.error();
  35. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> prelude =
  36. llvm::MemoryBuffer::getFile(*prelude_path);
  37. CARBON_CHECK(!prelude.getError()) << prelude.getError().message();
  38. CARBON_CHECK(fs.addFile("prelude.carbon", /*ModificationTime=*/0,
  39. std::move(*prelude)));
  40. const std::string source = ProtoToCarbon(carbon, /*maybe_add_main=*/true);
  41. CARBON_CHECK(fs.addFile("fuzzer.carbon", /*ModificationTime=*/0,
  42. llvm::MemoryBuffer::getMemBuffer(source)));
  43. TraceStream trace_stream;
  44. return ParseAndExecute(fs, "prelude.carbon", "fuzzer.carbon",
  45. /*parser_debug=*/false, &trace_stream, &llvm::nulls());
  46. }
  47. } // namespace Carbon::Testing