tokenized_buffer_fuzzer.cpp 2.0 KB

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