1 //===-- Fuzzer.cpp - Fuzz the pseudoparser --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang-pseudo/DirectiveTree.h"
10 #include "clang-pseudo/Forest.h"
11 #include "clang-pseudo/GLR.h"
12 #include "clang-pseudo/Token.h"
13 #include "clang-pseudo/cli/CLI.h"
14 #include "clang-pseudo/grammar/Grammar.h"
15 #include "clang-pseudo/grammar/LRTable.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <algorithm>
21 
22 namespace clang {
23 namespace pseudo {
24 namespace {
25 
26 class Fuzzer {
27   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
28   bool Print;
29 
30 public:
31   Fuzzer(bool Print) : Print(Print) {}
32 
33   void operator()(llvm::StringRef Code) {
34     std::string CodeStr = Code.str(); // Must be null-terminated.
35     auto RawStream = lex(CodeStr, LangOpts);
36     auto DirectiveStructure = DirectiveTree::parse(RawStream);
37     clang::pseudo::chooseConditionalBranches(DirectiveStructure, RawStream);
38     // FIXME: strip preprocessor directives
39     auto ParseableStream =
40         clang::pseudo::stripComments(cook(RawStream, LangOpts));
41 
42     clang::pseudo::ForestArena Arena;
43     clang::pseudo::GSS GSS;
44     const Language &Lang = getLanguageFromFlags();
45     auto &Root =
46         glrParse(ParseableStream,
47                  clang::pseudo::ParseParams{Lang.G, Lang.Table, Arena, GSS},
48                  *Lang.G.findNonterminal("translation-unit"));
49     if (Print)
50       llvm::outs() << Root.dumpRecursive(Lang.G);
51   }
52 };
53 
54 Fuzzer *Fuzz = nullptr;
55 
56 } // namespace
57 } // namespace pseudo
58 } // namespace clang
59 
60 extern "C" {
61 
62 // Set up the fuzzer from command line flags:
63 //  -print                     - used for testing the fuzzer
64 int LLVMFuzzerInitialize(int *Argc, char ***Argv) {
65   bool PrintForest = false;
66   auto ConsumeArg = [&](llvm::StringRef Arg) -> bool {
67     if (Arg == "-print") {
68       PrintForest = true;
69       return true;
70     }
71     return false;
72   };
73   *Argc = std::remove_if(*Argv + 1, *Argv + *Argc, ConsumeArg) - *Argv;
74 
75   clang::pseudo::Fuzz = new clang::pseudo::Fuzzer(PrintForest);
76   return 0;
77 }
78 
79 int LLVMFuzzerTestOneInput(uint8_t *Data, size_t Size) {
80   (*clang::pseudo::Fuzz)(llvm::StringRef(reinterpret_cast<char *>(Data), Size));
81   return 0;
82 }
83 }
84