tokenized_buffer_fuzzer.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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_tree_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 = SourceBuffer::CreateFromFile(fs, llvm::nulls(), TestFileName);
  30. auto buffer = Lex::TokenizedBuffer::Lex(*source, NullDiagnosticConsumer());
  31. if (buffer.has_errors()) {
  32. return 0;
  33. }
  34. // Walk the lexed and tokenized buffer to ensure it isn't corrupt in some way.
  35. //
  36. // TODO: We should enhance this to do more sanity checks on the resulting
  37. // token stream.
  38. for (Lex::Token token : buffer.tokens()) {
  39. int line_number = buffer.GetLineNumber(token);
  40. CARBON_CHECK(line_number > 0) << "Invalid line number!";
  41. CARBON_CHECK(line_number < INT_MAX) << "Invalid line number!";
  42. int column_number = buffer.GetColumnNumber(token);
  43. CARBON_CHECK(column_number > 0) << "Invalid line number!";
  44. CARBON_CHECK(column_number < INT_MAX) << "Invalid line number!";
  45. }
  46. return 0;
  47. }
  48. } // namespace Carbon::Testing