handle_cxx.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //==-- handle_cxx.cpp - Helper function for Clang fuzzers ------------------==//
  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. // Implements HandleCXX for use by the Clang fuzzers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "handle_cxx.h"
  13. #include "clang/CodeGen/CodeGenAction.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Lex/PreprocessorOptions.h"
  16. #include "clang/Tooling/Tooling.h"
  17. #include "llvm/Option/Option.h"
  18. using namespace clang;
  19. void clang_fuzzer::HandleCXX(const std::string &S,
  20. const char *FileName,
  21. const std::vector<const char *> &ExtraArgs) {
  22. llvm::opt::ArgStringList CC1Args;
  23. CC1Args.push_back("-cc1");
  24. for (auto &A : ExtraArgs)
  25. CC1Args.push_back(A);
  26. CC1Args.push_back(FileName);
  27. llvm::IntrusiveRefCntPtr<FileManager> Files(
  28. new FileManager(FileSystemOptions()));
  29. IgnoringDiagConsumer Diags;
  30. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  31. DiagnosticsEngine Diagnostics(
  32. IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
  33. &Diags, false);
  34. std::unique_ptr<clang::CompilerInvocation> Invocation(
  35. tooling::newInvocation(&Diagnostics, CC1Args));
  36. std::unique_ptr<llvm::MemoryBuffer> Input =
  37. llvm::MemoryBuffer::getMemBuffer(S);
  38. Invocation->getPreprocessorOpts().addRemappedFile(FileName,
  39. Input.release());
  40. std::unique_ptr<tooling::ToolAction> action(
  41. tooling::newFrontendActionFactory<clang::EmitObjAction>());
  42. std::shared_ptr<PCHContainerOperations> PCHContainerOps =
  43. std::make_shared<PCHContainerOperations>();
  44. action->runInvocation(std::move(Invocation), Files.get(), PCHContainerOps,
  45. &Diags);
  46. }