tokenized_buffer_fuzzer.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 <cstring>
  5. #include "common/check.h"
  6. #include "llvm/ADT/StringRef.h"
  7. #include "toolchain/diagnostics/null_diagnostics.h"
  8. #include "toolchain/lex/tokenized_buffer.h"
  9. namespace Carbon::Testing {
  10. // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style.
  11. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data,
  12. std::size_t size) {
  13. // Ignore large inputs.
  14. // TODO: Investigate replacement with an error limit. Content with errors on
  15. // escaped quotes (`\"` repeated) have O(M * N) behavior for M errors in a
  16. // file length N, so either that will need to also be fixed or M will need to
  17. // shrink for large (1MB+) inputs.
  18. // This also affects parse/parse_fuzzer.cpp.
  19. if (size > 100000) {
  20. return 0;
  21. }
  22. static constexpr llvm::StringLiteral TestFileName = "test.carbon";
  23. llvm::vfs::InMemoryFileSystem fs;
  24. llvm::StringRef data_ref(reinterpret_cast<const char*>(data), size);
  25. CARBON_CHECK(fs.addFile(
  26. TestFileName, /*ModificationTime=*/0,
  27. llvm::MemoryBuffer::getMemBuffer(data_ref, /*BufferName=*/TestFileName,
  28. /*RequiresNullTerminator=*/false)));
  29. auto source =
  30. SourceBuffer::CreateFromFile(fs, TestFileName, NullDiagnosticConsumer());
  31. auto buffer = Lex::TokenizedBuffer::Lex(*source, NullDiagnosticConsumer());
  32. if (buffer.has_errors()) {
  33. return 0;
  34. }
  35. // Walk the lexed and tokenized buffer to ensure it isn't corrupt in some way.
  36. //
  37. // TODO: We should enhance this to do more sanity checks on the resulting
  38. // token stream.
  39. for (Lex::Token token : buffer.tokens()) {
  40. int line_number = buffer.GetLineNumber(token);
  41. CARBON_CHECK(line_number > 0) << "Invalid line number!";
  42. CARBON_CHECK(line_number < INT_MAX) << "Invalid line number!";
  43. int column_number = buffer.GetColumnNumber(token);
  44. CARBON_CHECK(column_number > 0) << "Invalid line number!";
  45. CARBON_CHECK(column_number < INT_MAX) << "Invalid line number!";
  46. }
  47. return 0;
  48. }
  49. } // namespace Carbon::Testing