blob: afe57d4a666cfdf717a00802536bc98ba234358a [file] [log] [blame]
Manuel Klimek667c1522015-03-28 00:07:39 +00001//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements a function that runs Clang on a single
12/// input. This function is then linked into the Fuzzer library.
13///
14//===----------------------------------------------------------------------===//
15
16#include "clang/Tooling/Tooling.h"
17#include "clang/Frontend/FrontendActions.h"
18#include "clang/Frontend/CompilerInstance.h"
Mehdi Amini320a5a62016-07-18 20:33:09 +000019#include "clang/Lex/PreprocessorOptions.h"
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000020#include "llvm/Option/Option.h"
Manuel Klimek667c1522015-03-28 00:07:39 +000021
22using namespace clang;
23
Kostya Serebryanye39fec52015-10-02 23:34:37 +000024extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
Manuel Klimek667c1522015-03-28 00:07:39 +000025 std::string s((const char *)data, size);
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000026 llvm::opt::ArgStringList CC1Args;
27 CC1Args.push_back("-cc1");
Kostya Serebryany7862b012015-05-04 21:14:45 +000028 CC1Args.push_back("./test.cc");
Manuel Klimek667c1522015-03-28 00:07:39 +000029 llvm::IntrusiveRefCntPtr<FileManager> Files(
30 new FileManager(FileSystemOptions()));
Manuel Klimek667c1522015-03-28 00:07:39 +000031 IgnoringDiagConsumer Diags;
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000032 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
33 DiagnosticsEngine Diagnostics(
34 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
35 &Diags, false);
36 std::unique_ptr<clang::CompilerInvocation> Invocation(
37 tooling::newInvocation(&Diagnostics, CC1Args));
38 std::unique_ptr<llvm::MemoryBuffer> Input =
39 llvm::MemoryBuffer::getMemBuffer(s);
Kostya Serebryany7862b012015-05-04 21:14:45 +000040 Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release());
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000041 std::unique_ptr<tooling::ToolAction> action(
42 tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>());
Alexey Samsonov2f640d92015-06-25 20:21:59 +000043 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
Adrian Prantld5aae932015-07-17 04:07:47 +000044 std::make_shared<PCHContainerOperations>();
Alexey Samsonov2f640d92015-06-25 20:21:59 +000045 action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps,
46 &Diags);
Kostya Serebryanye39fec52015-10-02 23:34:37 +000047 return 0;
Manuel Klimek667c1522015-03-28 00:07:39 +000048}