check_fuzzer.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 "common/exe_path.h"
  5. #include "llvm/ADT/StringRef.h"
  6. #include "llvm/Support/MemoryBuffer.h"
  7. #include "llvm/Support/VirtualFileSystem.h"
  8. #include "testing/fuzzing/libfuzzer.h"
  9. #include "toolchain/driver/driver.h"
  10. namespace Carbon::Testing {
  11. static const InstallPaths* install_paths = nullptr;
  12. // NOLINTNEXTLINE(readability-non-const-parameter): External API required types.
  13. extern "C" auto LLVMFuzzerInitialize(int* argc, char*** argv) -> int {
  14. CARBON_CHECK(*argc >= 1, "Need the `argv[0]` value to initialize!");
  15. install_paths = new InstallPaths(
  16. InstallPaths::MakeForBazelRunfiles(FindExecutablePath((*argv)[0])));
  17. return 0;
  18. }
  19. // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style.
  20. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data,
  21. std::size_t size) {
  22. // Ignore large inputs.
  23. // TODO: See tokenized_buffer_fuzzer.cpp.
  24. if (size > 100000) {
  25. return 0;
  26. }
  27. static constexpr llvm::StringLiteral TestFileName = "test.carbon";
  28. llvm::vfs::InMemoryFileSystem fs;
  29. llvm::StringRef data_ref(reinterpret_cast<const char*>(data), size);
  30. CARBON_CHECK(fs.addFile(
  31. TestFileName, /*ModificationTime=*/0,
  32. llvm::MemoryBuffer::getMemBuffer(data_ref, /*BufferName=*/TestFileName,
  33. /*RequiresNullTerminator=*/false)));
  34. llvm::raw_null_ostream null_ostream;
  35. Driver driver(fs, install_paths, null_ostream, null_ostream);
  36. // TODO: Get checking to a point where it can handle invalid parse trees
  37. // without crashing.
  38. if (!driver.RunCommand({"compile", "--phase=parse", TestFileName}).success) {
  39. return 0;
  40. }
  41. driver.RunCommand({"compile", "--phase=check", TestFileName});
  42. return 0;
  43. }
  44. } // namespace Carbon::Testing