tokenized_buffer_fuzzer.cpp 1.9 KB

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