xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===-- llvm-c++filt.cpp --------------------------------------------------===//
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 "llvm/ADT/StringExtras.h"
10 #include "llvm/Demangle/Demangle.h"
11 #include "llvm/Demangle/StringViewExtras.h"
12 #include "llvm/Option/Arg.h"
13 #include "llvm/Option/ArgList.h"
14 #include "llvm/Option/Option.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/InitLLVM.h"
17 #include "llvm/Support/LLVMDriver.h"
18 #include "llvm/Support/WithColor.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/TargetParser/Host.h"
21 #include "llvm/TargetParser/Triple.h"
22 #include <cstdlib>
23 #include <iostream>
24 
25 using namespace llvm;
26 
27 namespace {
28 enum ID {
29   OPT_INVALID = 0, // This is not an option ID.
30 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
31 #include "Opts.inc"
32 #undef OPTION
33 };
34 
35 #define PREFIX(NAME, VALUE)                                                    \
36   static constexpr llvm::StringLiteral NAME##_init[] = VALUE;                  \
37   static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME(                   \
38       NAME##_init, std::size(NAME##_init) - 1);
39 #include "Opts.inc"
40 #undef PREFIX
41 
42 using namespace llvm::opt;
43 static constexpr opt::OptTable::Info InfoTable[] = {
44 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
45 #include "Opts.inc"
46 #undef OPTION
47 };
48 
49 class CxxfiltOptTable : public opt::GenericOptTable {
50 public:
51   CxxfiltOptTable() : opt::GenericOptTable(InfoTable) {
52     setGroupedShortOptions(true);
53   }
54 };
55 } // namespace
56 
57 static bool ParseParams;
58 static bool StripUnderscore;
59 static bool Types;
60 
61 static StringRef ToolName;
62 
63 static void error(const Twine &Message) {
64   WithColor::error(errs(), ToolName) << Message << '\n';
65   exit(1);
66 }
67 
68 static std::string demangle(const std::string &Mangled) {
69   using llvm::itanium_demangle::starts_with;
70   std::string_view DecoratedStr = Mangled;
71   bool CanHaveLeadingDot = true;
72   if (StripUnderscore && DecoratedStr[0] == '_') {
73     DecoratedStr.remove_prefix(1);
74     CanHaveLeadingDot = false;
75   }
76 
77   std::string Result;
78   if (nonMicrosoftDemangle(DecoratedStr, Result, CanHaveLeadingDot,
79                            ParseParams))
80     return Result;
81 
82   std::string Prefix;
83   char *Undecorated = nullptr;
84 
85   if (Types)
86     Undecorated = itaniumDemangle(DecoratedStr, ParseParams);
87 
88   if (!Undecorated && starts_with(DecoratedStr, "__imp_")) {
89     Prefix = "import thunk for ";
90     Undecorated = itaniumDemangle(DecoratedStr.substr(6), ParseParams);
91   }
92 
93   Result = Undecorated ? Prefix + Undecorated : Mangled;
94   free(Undecorated);
95   return Result;
96 }
97 
98 // Split 'Source' on any character that fails to pass 'IsLegalChar'.  The
99 // returned vector consists of pairs where 'first' is the delimited word, and
100 // 'second' are the delimiters following that word.
101 static void SplitStringDelims(
102     StringRef Source,
103     SmallVectorImpl<std::pair<StringRef, StringRef>> &OutFragments,
104     function_ref<bool(char)> IsLegalChar) {
105   // The beginning of the input string.
106   const auto Head = Source.begin();
107 
108   // Obtain any leading delimiters.
109   auto Start = std::find_if(Head, Source.end(), IsLegalChar);
110   if (Start != Head)
111     OutFragments.push_back({"", Source.slice(0, Start - Head)});
112 
113   // Capture each word and the delimiters following that word.
114   while (Start != Source.end()) {
115     Start = std::find_if(Start, Source.end(), IsLegalChar);
116     auto End = std::find_if_not(Start, Source.end(), IsLegalChar);
117     auto DEnd = std::find_if(End, Source.end(), IsLegalChar);
118     OutFragments.push_back({Source.slice(Start - Head, End - Head),
119                             Source.slice(End - Head, DEnd - Head)});
120     Start = DEnd;
121   }
122 }
123 
124 // This returns true if 'C' is a character that can show up in an
125 // Itanium-mangled string.
126 static bool IsLegalItaniumChar(char C) {
127   // Itanium CXX ABI [External Names]p5.1.1:
128   // '$' and '.' in mangled names are reserved for private implementations.
129   return isAlnum(C) || C == '.' || C == '$' || C == '_';
130 }
131 
132 // If 'Split' is true, then 'Mangled' is broken into individual words and each
133 // word is demangled.  Otherwise, the entire string is treated as a single
134 // mangled item.  The result is output to 'OS'.
135 static void demangleLine(llvm::raw_ostream &OS, StringRef Mangled, bool Split) {
136   std::string Result;
137   if (Split) {
138     SmallVector<std::pair<StringRef, StringRef>, 16> Words;
139     SplitStringDelims(Mangled, Words, IsLegalItaniumChar);
140     for (const auto &Word : Words)
141       Result += ::demangle(std::string(Word.first)) + Word.second.str();
142   } else
143     Result = ::demangle(std::string(Mangled));
144   OS << Result << '\n';
145   OS.flush();
146 }
147 
148 int llvm_cxxfilt_main(int argc, char **argv, const llvm::ToolContext &) {
149   InitLLVM X(argc, argv);
150   BumpPtrAllocator A;
151   StringSaver Saver(A);
152   CxxfiltOptTable Tbl;
153   ToolName = argv[0];
154   opt::InputArgList Args = Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,
155                                          [&](StringRef Msg) { error(Msg); });
156   if (Args.hasArg(OPT_help)) {
157     Tbl.printHelp(outs(),
158                   (Twine(ToolName) + " [options] <mangled>").str().c_str(),
159                   "LLVM symbol undecoration tool");
160     // TODO Replace this with OptTable API once it adds extrahelp support.
161     outs() << "\nPass @FILE as argument to read options from FILE.\n";
162     return 0;
163   }
164   if (Args.hasArg(OPT_version)) {
165     outs() << ToolName << '\n';
166     cl::PrintVersionMessage();
167     return 0;
168   }
169 
170   // The default value depends on the default triple. Mach-O has symbols
171   // prefixed with "_", so strip by default.
172   if (opt::Arg *A =
173           Args.getLastArg(OPT_strip_underscore, OPT_no_strip_underscore))
174     StripUnderscore = A->getOption().matches(OPT_strip_underscore);
175   else
176     StripUnderscore = Triple(sys::getProcessTriple()).isOSBinFormatMachO();
177 
178   ParseParams = !Args.hasArg(OPT_no_params);
179 
180   Types = Args.hasArg(OPT_types);
181 
182   std::vector<std::string> Decorated = Args.getAllArgValues(OPT_INPUT);
183   if (Decorated.empty())
184     for (std::string Mangled; std::getline(std::cin, Mangled);)
185       demangleLine(llvm::outs(), Mangled, true);
186   else
187     for (const auto &Symbol : Decorated)
188       demangleLine(llvm::outs(), Symbol, false);
189 
190   return EXIT_SUCCESS;
191 }
192