1 //===-- core_main.cpp - Core Index Tool testbed ---------------------------===//
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/AST/Mangle.h"
10 #include "clang/Basic/LangOptions.h"
11 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
12 #include "clang/Frontend/ASTUnit.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Frontend/CompilerInvocation.h"
15 #include "clang/Frontend/FrontendAction.h"
16 #include "clang/Index/IndexDataConsumer.h"
17 #include "clang/Index/IndexingAction.h"
18 #include "clang/Index/USRGeneration.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Serialization/ASTReader.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/Program.h"
25 #include "llvm/Support/Signals.h"
26 #include "llvm/Support/StringSaver.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 using namespace clang;
30 using namespace clang::index;
31 using namespace llvm;
32 
33 extern "C" int indextest_core_main(int argc, const char **argv);
34 extern "C" int indextest_perform_shell_execution(const char *command_line);
35 
36 namespace {
37 
38 enum class ActionType {
39   None,
40   PrintSourceSymbols,
41 };
42 
43 namespace options {
44 
45 static cl::OptionCategory IndexTestCoreCategory("index-test-core options");
46 
47 static cl::opt<ActionType>
48 Action(cl::desc("Action:"), cl::init(ActionType::None),
49        cl::values(
50           clEnumValN(ActionType::PrintSourceSymbols,
51                      "print-source-symbols", "Print symbols from source")),
52        cl::cat(IndexTestCoreCategory));
53 
54 static cl::extrahelp MoreHelp(
55   "\nAdd \"-- <compiler arguments>\" at the end to setup the compiler "
56   "invocation\n"
57 );
58 
59 static cl::opt<bool>
60 DumpModuleImports("dump-imported-module-files",
61                cl::desc("Print symbols and input files from imported modules"));
62 
63 static cl::opt<bool>
64 IncludeLocals("include-locals", cl::desc("Print local symbols"));
65 
66 static cl::opt<std::string>
67 ModuleFilePath("module-file",
68                cl::desc("Path to module file to print symbols from"));
69 static cl::opt<std::string>
70   ModuleFormat("fmodule-format", cl::init("raw"),
71         cl::desc("Container format for clang modules and PCH, 'raw' or 'obj'"));
72 
73 }
74 } // anonymous namespace
75 
76 static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS);
77 static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
78                                   raw_ostream &OS);
79 static void printSymbolNameAndUSR(const clang::Module *Mod, raw_ostream &OS);
80 
81 namespace {
82 
83 class PrintIndexDataConsumer : public IndexDataConsumer {
84   raw_ostream &OS;
85   std::unique_ptr<ASTNameGenerator> ASTNameGen;
86   std::shared_ptr<Preprocessor> PP;
87 
88 public:
89   PrintIndexDataConsumer(raw_ostream &OS) : OS(OS) {
90   }
91 
92   void initialize(ASTContext &Ctx) override {
93     ASTNameGen.reset(new ASTNameGenerator(Ctx));
94   }
95 
96   void setPreprocessor(std::shared_ptr<Preprocessor> PP) override {
97     this->PP = std::move(PP);
98   }
99 
100   bool handleDeclOccurrence(const Decl *D, SymbolRoleSet Roles,
101                             ArrayRef<SymbolRelation> Relations,
102                             SourceLocation Loc, ASTNodeInfo ASTNode) override {
103     ASTContext &Ctx = D->getASTContext();
104     SourceManager &SM = Ctx.getSourceManager();
105 
106     Loc = SM.getFileLoc(Loc);
107     FileID FID = SM.getFileID(Loc);
108     unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
109     unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
110     OS << Line << ':' << Col << " | ";
111 
112     printSymbolInfo(getSymbolInfo(D), OS);
113     OS << " | ";
114 
115     printSymbolNameAndUSR(D, Ctx, OS);
116     OS << " | ";
117 
118     if (ASTNameGen->writeName(D, OS))
119       OS << "<no-cgname>";
120     OS << " | ";
121 
122     printSymbolRoles(Roles, OS);
123     OS << " | ";
124 
125     OS << "rel: " << Relations.size() << '\n';
126 
127     for (auto &SymRel : Relations) {
128       OS << '\t';
129       printSymbolRoles(SymRel.Roles, OS);
130       OS << " | ";
131       printSymbolNameAndUSR(SymRel.RelatedSymbol, Ctx, OS);
132       OS << '\n';
133     }
134 
135     return true;
136   }
137 
138   bool handleModuleOccurrence(const ImportDecl *ImportD,
139                               const clang::Module *Mod, SymbolRoleSet Roles,
140                               SourceLocation Loc) override {
141     ASTContext &Ctx = ImportD->getASTContext();
142     SourceManager &SM = Ctx.getSourceManager();
143 
144     Loc = SM.getFileLoc(Loc);
145     FileID FID = SM.getFileID(Loc);
146     unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
147     unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
148     OS << Line << ':' << Col << " | ";
149 
150     printSymbolInfo(getSymbolInfo(ImportD), OS);
151     OS << " | ";
152 
153     printSymbolNameAndUSR(Mod, OS);
154     OS << " | ";
155 
156     printSymbolRoles(Roles, OS);
157     OS << " |\n";
158 
159     return true;
160   }
161 
162   bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI,
163                              SymbolRoleSet Roles, SourceLocation Loc) override {
164     assert(PP);
165     SourceManager &SM = PP->getSourceManager();
166 
167     Loc = SM.getFileLoc(Loc);
168     FileID FID = SM.getFileID(Loc);
169     unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
170     unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
171     OS << Line << ':' << Col << " | ";
172 
173     printSymbolInfo(getSymbolInfoForMacro(*MI), OS);
174     OS << " | ";
175 
176     OS << Name->getName();
177     OS << " | ";
178 
179     SmallString<256> USRBuf;
180     if (generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
181                             USRBuf)) {
182       OS << "<no-usr>";
183     } else {
184       OS << USRBuf;
185     }
186     OS << " | ";
187 
188     printSymbolRoles(Roles, OS);
189     OS << " |\n";
190     return true;
191   }
192 };
193 
194 } // anonymous namespace
195 
196 //===----------------------------------------------------------------------===//
197 // Print Source Symbols
198 //===----------------------------------------------------------------------===//
199 
200 static void dumpModuleFileInputs(serialization::ModuleFile &Mod,
201                                  ASTReader &Reader,
202                                  raw_ostream &OS) {
203   OS << "---- Module Inputs ----\n";
204   Reader.visitInputFiles(Mod, /*IncludeSystem=*/true, /*Complain=*/false,
205                         [&](const serialization::InputFile &IF, bool isSystem) {
206     OS << (isSystem ? "system" : "user") << " | ";
207     OS << IF.getFile()->getName() << '\n';
208   });
209 }
210 
211 static bool printSourceSymbols(const char *Executable,
212                                ArrayRef<const char *> Args,
213                                bool dumpModuleImports, bool indexLocals) {
214   SmallVector<const char *, 4> ArgsWithProgName;
215   ArgsWithProgName.push_back(Executable);
216   ArgsWithProgName.append(Args.begin(), Args.end());
217   IntrusiveRefCntPtr<DiagnosticsEngine>
218     Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
219   auto CInvok = createInvocationFromCommandLine(ArgsWithProgName, Diags);
220   if (!CInvok)
221     return true;
222 
223   raw_ostream &OS = outs();
224   auto DataConsumer = std::make_shared<PrintIndexDataConsumer>(OS);
225   IndexingOptions IndexOpts;
226   IndexOpts.IndexFunctionLocals = indexLocals;
227   std::unique_ptr<FrontendAction> IndexAction =
228       createIndexingAction(DataConsumer, IndexOpts);
229 
230   auto PCHContainerOps = std::make_shared<PCHContainerOperations>();
231   std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
232       std::move(CInvok), PCHContainerOps, Diags, IndexAction.get()));
233 
234   if (!Unit)
235     return true;
236 
237   if (dumpModuleImports) {
238     if (auto Reader = Unit->getASTReader()) {
239       Reader->getModuleManager().visit([&](serialization::ModuleFile &Mod) -> bool {
240         OS << "==== Module " << Mod.ModuleName << " ====\n";
241         indexModuleFile(Mod, *Reader, *DataConsumer, IndexOpts);
242         dumpModuleFileInputs(Mod, *Reader, OS);
243         return true; // skip module dependencies.
244       });
245     }
246   }
247 
248   return false;
249 }
250 
251 static bool printSourceSymbolsFromModule(StringRef modulePath,
252                                          StringRef format) {
253   FileSystemOptions FileSystemOpts;
254   auto pchContOps = std::make_shared<PCHContainerOperations>();
255   // Register the support for object-file-wrapped Clang modules.
256   pchContOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
257   auto pchRdr = pchContOps->getReaderOrNull(format);
258   if (!pchRdr) {
259     errs() << "unknown module format: " << format << '\n';
260     return true;
261   }
262 
263   IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
264       CompilerInstance::createDiagnostics(new DiagnosticOptions());
265   std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
266       std::string(modulePath), *pchRdr, ASTUnit::LoadASTOnly, Diags,
267       FileSystemOpts, /*UseDebugInfo=*/false,
268       /*OnlyLocalDecls=*/true, CaptureDiagsKind::None,
269       /*AllowASTWithCompilerErrors=*/true,
270       /*UserFilesAreVolatile=*/false);
271   if (!AU) {
272     errs() << "failed to create TU for: " << modulePath << '\n';
273     return true;
274   }
275 
276   PrintIndexDataConsumer DataConsumer(outs());
277   IndexingOptions IndexOpts;
278   indexASTUnit(*AU, DataConsumer, IndexOpts);
279 
280   return false;
281 }
282 
283 //===----------------------------------------------------------------------===//
284 // Helper Utils
285 //===----------------------------------------------------------------------===//
286 
287 static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS) {
288   OS << getSymbolKindString(SymInfo.Kind);
289   if (SymInfo.SubKind != SymbolSubKind::None)
290     OS << '/' << getSymbolSubKindString(SymInfo.SubKind);
291   if (SymInfo.Properties) {
292     OS << '(';
293     printSymbolProperties(SymInfo.Properties, OS);
294     OS << ')';
295   }
296   OS << '/' << getSymbolLanguageString(SymInfo.Lang);
297 }
298 
299 static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
300                                   raw_ostream &OS) {
301   if (printSymbolName(D, Ctx.getLangOpts(), OS)) {
302     OS << "<no-name>";
303   }
304   OS << " | ";
305 
306   SmallString<256> USRBuf;
307   if (generateUSRForDecl(D, USRBuf)) {
308     OS << "<no-usr>";
309   } else {
310     OS << USRBuf;
311   }
312 }
313 
314 static void printSymbolNameAndUSR(const clang::Module *Mod, raw_ostream &OS) {
315   assert(Mod);
316   OS << Mod->getFullModuleName() << " | ";
317   generateFullUSRForModule(Mod, OS);
318 }
319 
320 //===----------------------------------------------------------------------===//
321 // Command line processing.
322 //===----------------------------------------------------------------------===//
323 
324 int indextest_core_main(int argc, const char **argv) {
325   sys::PrintStackTraceOnErrorSignal(argv[0]);
326   PrettyStackTraceProgram X(argc, argv);
327   void *MainAddr = (void*) (intptr_t) indextest_core_main;
328   std::string Executable = llvm::sys::fs::getMainExecutable(argv[0], MainAddr);
329 
330   assert(argv[1] == StringRef("core"));
331   ++argv;
332   --argc;
333 
334   std::vector<const char *> CompArgs;
335   const char **DoubleDash = std::find(argv, argv + argc, StringRef("--"));
336   if (DoubleDash != argv + argc) {
337     CompArgs = std::vector<const char *>(DoubleDash + 1, argv + argc);
338     argc = DoubleDash - argv;
339   }
340 
341   cl::HideUnrelatedOptions(options::IndexTestCoreCategory);
342   cl::ParseCommandLineOptions(argc, argv, "index-test-core");
343 
344   if (options::Action == ActionType::None) {
345     errs() << "error: action required; pass '-help' for options\n";
346     return 1;
347   }
348 
349   if (options::Action == ActionType::PrintSourceSymbols) {
350     if (!options::ModuleFilePath.empty()) {
351       return printSourceSymbolsFromModule(options::ModuleFilePath,
352                                           options::ModuleFormat);
353     }
354     if (CompArgs.empty()) {
355       errs() << "error: missing compiler args; pass '-- <compiler arguments>'\n";
356       return 1;
357     }
358     return printSourceSymbols(Executable.c_str(), CompArgs,
359                               options::DumpModuleImports,
360                               options::IncludeLocals);
361   }
362 
363   return 0;
364 }
365 
366 //===----------------------------------------------------------------------===//
367 // Utility functions
368 //===----------------------------------------------------------------------===//
369 
370 int indextest_perform_shell_execution(const char *command_line) {
371   BumpPtrAllocator Alloc;
372   llvm::StringSaver Saver(Alloc);
373   SmallVector<const char *, 4> Args;
374   llvm::cl::TokenizeGNUCommandLine(command_line, Saver, Args);
375   auto Program = llvm::sys::findProgramByName(Args[0]);
376   if (std::error_code ec = Program.getError()) {
377     llvm::errs() << "command not found: " << Args[0] << "\n";
378     return ec.value();
379   }
380   SmallVector<StringRef, 8> execArgs(Args.begin(), Args.end());
381   return llvm::sys::ExecuteAndWait(*Program, execArgs);
382 }
383