string_literal_fuzzer.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 "common/check.h"
  6. #include "llvm/ADT/StringRef.h"
  7. #include "testing/fuzzing/libfuzzer.h"
  8. #include "toolchain/diagnostics/null_diagnostics.h"
  9. #include "toolchain/lex/string_literal.h"
  10. namespace Carbon::Testing {
  11. // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style.
  12. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data, size_t size) {
  13. auto literal = Lex::StringLiteral::Lex(
  14. llvm::StringRef(reinterpret_cast<const char*>(data), size));
  15. if (!literal) {
  16. // Lexically not a string literal.
  17. return 0;
  18. }
  19. if (!literal->is_terminated()) {
  20. // Found errors while parsing.
  21. return 0;
  22. }
  23. fprintf(stderr, "valid: %d\n", literal->is_terminated());
  24. fprintf(stderr, "size: %lu\n", literal->text().size());
  25. fprintf(stderr, "text: %s\n", literal->text().str().c_str());
  26. // Check multiline flag was computed correctly.
  27. switch (literal->kind()) {
  28. case Lex::StringLiteral::Kind::Char:
  29. break;
  30. case Lex::StringLiteral::Kind::SingleLine:
  31. CARBON_CHECK(!literal->text().contains('\n'));
  32. break;
  33. case Lex::StringLiteral::Kind::MultiLine:
  34. case Lex::StringLiteral::Kind::MultiLineWithDoubleQuotes:
  35. CARBON_CHECK(literal->text().contains('\n'));
  36. break;
  37. }
  38. auto* null_emitter = &Diagnostics::NullEmitter<const char*>();
  39. if (literal->kind() == Lex::StringLiteral::Kind::Char) {
  40. volatile auto value = literal->ComputeCharLiteralValue(*null_emitter);
  41. (void)value;
  42. } else {
  43. llvm::BumpPtrAllocator allocator;
  44. volatile auto value = literal->ComputeStringValue(allocator, *null_emitter);
  45. (void)value;
  46. }
  47. return 0;
  48. }
  49. } // namespace Carbon::Testing