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