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