1//===-- ModelInjector.cpp ---------------------------------------*- C++ -*-===//
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 "ModelInjector.h"
10#include "clang/AST/Decl.h"
11#include "clang/AST/DeclObjC.h"
12#include "clang/Basic/DiagnosticDriver.h"
13#include "clang/Basic/LangStandard.h"
14#include "clang/Basic/Stack.h"
15#include "clang/Frontend/ASTUnit.h"
16#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/FrontendAction.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Serialization/ASTReader.h"
20#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
21#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
22#include "llvm/Support/CrashRecoveryContext.h"
23#include "llvm/Support/FileSystem.h"
24#include <utility>
25
26using namespace clang;
27using namespace ento;
28
29ModelInjector::ModelInjector(CompilerInstance &CI) : CI(CI) {
30 if (CI.getAnalyzerOpts().ShouldEmitErrorsOnInvalidConfigValue &&
31 !CI.getAnalyzerOpts().ModelPath.empty()) {
32 auto S = CI.getVirtualFileSystem().status(Path: CI.getAnalyzerOpts().ModelPath);
33 if (!S || S->getType() != llvm::sys::fs::file_type::directory_file)
34 CI.getDiagnostics().Report(DiagID: diag::err_analyzer_config_invalid_input)
35 << "model-path" << "a filename";
36 }
37}
38
39Stmt *ModelInjector::getBody(const FunctionDecl *D) {
40 onBodySynthesis(D);
41 return Bodies[D->getName()];
42}
43
44Stmt *ModelInjector::getBody(const ObjCMethodDecl *D) {
45 onBodySynthesis(D);
46 return Bodies[D->getName()];
47}
48
49void ModelInjector::onBodySynthesis(const NamedDecl *D) {
50
51 // FIXME: what about overloads? Declarations can be used as keys but what
52 // about file name index? Mangled names may not be suitable for that either.
53 if (Bodies.count(Key: D->getName()) != 0)
54 return;
55
56 llvm::IntrusiveRefCntPtr<SourceManager> SM = CI.getSourceManagerPtr();
57 FileID mainFileID = SM->getMainFileID();
58
59 llvm::StringRef modelPath = CI.getAnalyzerOpts().ModelPath;
60
61 llvm::SmallString<128> fileName;
62
63 if (!modelPath.empty())
64 fileName =
65 llvm::StringRef(modelPath.str() + "/" + D->getName().str() + ".model");
66 else
67 fileName = llvm::StringRef(D->getName().str() + ".model");
68
69 if (!CI.getVirtualFileSystem().exists(Path: fileName)) {
70 Bodies[D->getName()] = nullptr;
71 return;
72 }
73
74 auto Invocation = std::make_shared<CompilerInvocation>(args&: CI.getInvocation());
75
76 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
77 InputKind IK = Language::CXX; // FIXME
78 FrontendOpts.Inputs.clear();
79 FrontendOpts.Inputs.emplace_back(Args&: fileName, Args&: IK);
80 FrontendOpts.DisableFree = true;
81
82 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
83
84 // Modules are parsed by a separate CompilerInstance, so this code mimics that
85 // behavior for models
86 CompilerInstance Instance(std::move(Invocation),
87 CI.getPCHContainerOperations());
88 Instance.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
89 Instance.createDiagnostics(
90 Client: new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()),
91 /*ShouldOwnClient=*/true);
92
93 Instance.getDiagnostics().setSourceManager(SM.get());
94
95 // The instance wants to take ownership, however DisableFree frontend option
96 // is set to true to avoid double free issues
97 Instance.setVirtualFileSystem(CI.getVirtualFileSystemPtr());
98 Instance.setFileManager(CI.getFileManagerPtr());
99 Instance.setSourceManager(SM);
100 Instance.setPreprocessor(CI.getPreprocessorPtr());
101 Instance.setASTContext(CI.getASTContextPtr());
102
103 Instance.getPreprocessor().InitializeForModelFile();
104
105 ParseModelFileAction parseModelFile(Bodies);
106
107 llvm::CrashRecoveryContext CRC;
108
109 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(Act&: parseModelFile); },
110 RequestedStackSize: DesiredStackSize);
111
112 Instance.getPreprocessor().FinalizeForModelFile();
113
114 Instance.resetAndLeakSourceManager();
115 Instance.resetAndLeakFileManager();
116 Instance.resetAndLeakPreprocessor();
117
118 // The preprocessor enters to the main file id when parsing is started, so
119 // the main file id is changed to the model file during parsing and it needs
120 // to be reset to the former main file id after parsing of the model file
121 // is done.
122 SM->setMainFileID(mainFileID);
123}
124