tokenized_buffer_fuzzer.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 {
  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. // We need two bytes of data to compute a file name length.
  16. if (size < 2) {
  17. return 0;
  18. }
  19. uint16_t raw_filename_length;
  20. std::memcpy(&raw_filename_length, data, 2);
  21. data += 2;
  22. size -= 2;
  23. size_t filename_length = raw_filename_length;
  24. // We need enough data to populate this filename length.
  25. if (size < filename_length) {
  26. return 0;
  27. }
  28. llvm::StringRef filename(reinterpret_cast<const char*>(data),
  29. filename_length);
  30. data += filename_length;
  31. size -= filename_length;
  32. // The rest of the data is the source text.
  33. auto source = SourceBuffer::CreateFromText(
  34. llvm::StringRef(reinterpret_cast<const char*>(data), size), filename);
  35. auto buffer = TokenizedBuffer::Lex(source, NullDiagnosticConsumer());
  36. if (buffer.HasErrors()) {
  37. return 0;
  38. }
  39. // Walk the lexed and tokenized buffer to ensure it isn't corrupt in some way.
  40. //
  41. // TODO: We should enhance this to do more sanity checks on the resulting
  42. // token stream.
  43. for (TokenizedBuffer::Token token : buffer.Tokens()) {
  44. int line_number = buffer.GetLineNumber(token);
  45. (void)line_number;
  46. CHECK(line_number > 0) << "Invalid line number!";
  47. CHECK(line_number < INT_MAX) << "Invalid line number!";
  48. int column_number = buffer.GetColumnNumber(token);
  49. (void)column_number;
  50. CHECK(column_number > 0) << "Invalid line number!";
  51. CHECK(column_number < INT_MAX) << "Invalid line number!";
  52. }
  53. return 0;
  54. }
  55. } // namespace Carbon