tokenized_buffer_fuzzer.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 "lexer/tokenized_buffer.h"
  8. #include "llvm/ADT/StringRef.h"
  9. namespace Carbon {
  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. // We need two bytes of data to compute a file name length.
  14. if (size < 2) {
  15. return 0;
  16. }
  17. uint16_t raw_filename_length;
  18. std::memcpy(&raw_filename_length, data, 2);
  19. data += 2;
  20. size -= 2;
  21. size_t filename_length = raw_filename_length;
  22. // We need enough data to populate this filename length.
  23. if (size < filename_length) {
  24. return 0;
  25. }
  26. llvm::StringRef filename(reinterpret_cast<const char*>(data),
  27. filename_length);
  28. data += filename_length;
  29. size -= filename_length;
  30. // The rest of the data is the source text.
  31. auto source = SourceBuffer::CreateFromText(
  32. llvm::StringRef(reinterpret_cast<const char*>(data), size), filename);
  33. // Use a real diagnostic emitter to get lazy codepaths to execute.
  34. DiagnosticEmitter emitter = NullDiagnosticEmitter();
  35. auto buffer = TokenizedBuffer::Lex(source, emitter);
  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. assert(line_number > 0 && "Invalid line number!");
  47. assert(line_number < INT_MAX && "Invalid line number!");
  48. int column_number = buffer.GetColumnNumber(token);
  49. (void)column_number;
  50. assert(column_number > 0 && "Invalid line number!");
  51. assert(column_number < INT_MAX && "Invalid line number!");
  52. }
  53. return 0;
  54. }
  55. } // namespace Carbon