tokenized_buffer_fuzzer.cpp 2.0 KB

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