10b57cec5SDimitry Andric //===-- llvm-c++filt.cpp --------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
10480093f4SDimitry Andric #include "llvm/ADT/Triple.h"
110b57cec5SDimitry Andric #include "llvm/Demangle/Demangle.h"
12fe6060f1SDimitry Andric #include "llvm/Option/Arg.h"
13fe6060f1SDimitry Andric #include "llvm/Option/ArgList.h"
14fe6060f1SDimitry Andric #include "llvm/Option/Option.h"
150b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
16480093f4SDimitry Andric #include "llvm/Support/Host.h"
170b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h"
18fe6060f1SDimitry Andric #include "llvm/Support/WithColor.h"
190b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
200b57cec5SDimitry Andric #include <cstdlib>
210b57cec5SDimitry Andric #include <iostream>
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric using namespace llvm;
240b57cec5SDimitry Andric 
25fe6060f1SDimitry Andric namespace {
26fe6060f1SDimitry Andric enum ID {
27fe6060f1SDimitry Andric   OPT_INVALID = 0, // This is not an option ID.
28fe6060f1SDimitry Andric #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
29fe6060f1SDimitry Andric                HELPTEXT, METAVAR, VALUES)                                      \
30fe6060f1SDimitry Andric   OPT_##ID,
31fe6060f1SDimitry Andric #include "Opts.inc"
32fe6060f1SDimitry Andric #undef OPTION
330b57cec5SDimitry Andric };
340b57cec5SDimitry Andric 
35bdd1243dSDimitry Andric #define PREFIX(NAME, VALUE)                                                    \
36bdd1243dSDimitry Andric   static constexpr llvm::StringLiteral NAME##_init[] = VALUE;                  \
37bdd1243dSDimitry Andric   static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME(                   \
38bdd1243dSDimitry Andric       NAME##_init, std::size(NAME##_init) - 1);
39fe6060f1SDimitry Andric #include "Opts.inc"
40fe6060f1SDimitry Andric #undef PREFIX
410b57cec5SDimitry Andric 
42bdd1243dSDimitry Andric static constexpr opt::OptTable::Info InfoTable[] = {
43fe6060f1SDimitry Andric #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
44fe6060f1SDimitry Andric                HELPTEXT, METAVAR, VALUES)                                      \
45fe6060f1SDimitry Andric   {                                                                            \
46fe6060f1SDimitry Andric       PREFIX,      NAME,      HELPTEXT,                                        \
47fe6060f1SDimitry Andric       METAVAR,     OPT_##ID,  opt::Option::KIND##Class,                        \
48fe6060f1SDimitry Andric       PARAM,       FLAGS,     OPT_##GROUP,                                     \
49fe6060f1SDimitry Andric       OPT_##ALIAS, ALIASARGS, VALUES},
50fe6060f1SDimitry Andric #include "Opts.inc"
51fe6060f1SDimitry Andric #undef OPTION
52fe6060f1SDimitry Andric };
530b57cec5SDimitry Andric 
54bdd1243dSDimitry Andric class CxxfiltOptTable : public opt::GenericOptTable {
55fe6060f1SDimitry Andric public:
56bdd1243dSDimitry Andric   CxxfiltOptTable() : opt::GenericOptTable(InfoTable) {
57bdd1243dSDimitry Andric     setGroupedShortOptions(true);
58bdd1243dSDimitry Andric   }
59fe6060f1SDimitry Andric };
60fe6060f1SDimitry Andric } // namespace
610b57cec5SDimitry Andric 
62fe6060f1SDimitry Andric static bool StripUnderscore;
63fe6060f1SDimitry Andric static bool Types;
640b57cec5SDimitry Andric 
65fe6060f1SDimitry Andric static StringRef ToolName;
66fe6060f1SDimitry Andric 
67fe6060f1SDimitry Andric static void error(const Twine &Message) {
68fe6060f1SDimitry Andric   WithColor::error(errs(), ToolName) << Message << '\n';
69fe6060f1SDimitry Andric   exit(1);
70480093f4SDimitry Andric }
71480093f4SDimitry Andric 
72480093f4SDimitry Andric static std::string demangle(const std::string &Mangled) {
730b57cec5SDimitry Andric   const char *DecoratedStr = Mangled.c_str();
74fe6060f1SDimitry Andric   if (StripUnderscore)
750b57cec5SDimitry Andric     if (DecoratedStr[0] == '_')
760b57cec5SDimitry Andric       ++DecoratedStr;
770b57cec5SDimitry Andric 
78349cc55cSDimitry Andric   std::string Result;
79349cc55cSDimitry Andric   if (nonMicrosoftDemangle(DecoratedStr, Result))
80349cc55cSDimitry Andric     return Result;
81349cc55cSDimitry Andric 
82349cc55cSDimitry Andric   std::string Prefix;
830b57cec5SDimitry Andric   char *Undecorated = nullptr;
840b57cec5SDimitry Andric 
85349cc55cSDimitry Andric   if (Types)
86349cc55cSDimitry Andric     Undecorated = itaniumDemangle(DecoratedStr, nullptr, nullptr, nullptr);
870b57cec5SDimitry Andric 
88349cc55cSDimitry Andric   if (!Undecorated && strncmp(DecoratedStr, "__imp_", 6) == 0) {
89480093f4SDimitry Andric     Prefix = "import thunk for ";
90349cc55cSDimitry Andric     Undecorated = itaniumDemangle(DecoratedStr + 6, nullptr, nullptr, nullptr);
910b57cec5SDimitry Andric   }
920b57cec5SDimitry Andric 
93349cc55cSDimitry Andric   Result = Undecorated ? Prefix + Undecorated : Mangled;
940b57cec5SDimitry Andric   free(Undecorated);
950b57cec5SDimitry Andric   return Result;
960b57cec5SDimitry Andric }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric // Split 'Source' on any character that fails to pass 'IsLegalChar'.  The
990b57cec5SDimitry Andric // returned vector consists of pairs where 'first' is the delimited word, and
1000b57cec5SDimitry Andric // 'second' are the delimiters following that word.
1010b57cec5SDimitry Andric static void SplitStringDelims(
1020b57cec5SDimitry Andric     StringRef Source,
1030b57cec5SDimitry Andric     SmallVectorImpl<std::pair<StringRef, StringRef>> &OutFragments,
1040b57cec5SDimitry Andric     function_ref<bool(char)> IsLegalChar) {
1050b57cec5SDimitry Andric   // The beginning of the input string.
1060b57cec5SDimitry Andric   const auto Head = Source.begin();
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // Obtain any leading delimiters.
1090b57cec5SDimitry Andric   auto Start = std::find_if(Head, Source.end(), IsLegalChar);
1100b57cec5SDimitry Andric   if (Start != Head)
1110b57cec5SDimitry Andric     OutFragments.push_back({"", Source.slice(0, Start - Head)});
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   // Capture each word and the delimiters following that word.
1140b57cec5SDimitry Andric   while (Start != Source.end()) {
1150b57cec5SDimitry Andric     Start = std::find_if(Start, Source.end(), IsLegalChar);
1160b57cec5SDimitry Andric     auto End = std::find_if_not(Start, Source.end(), IsLegalChar);
1170b57cec5SDimitry Andric     auto DEnd = std::find_if(End, Source.end(), IsLegalChar);
1180b57cec5SDimitry Andric     OutFragments.push_back({Source.slice(Start - Head, End - Head),
1190b57cec5SDimitry Andric                             Source.slice(End - Head, DEnd - Head)});
1200b57cec5SDimitry Andric     Start = DEnd;
1210b57cec5SDimitry Andric   }
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric // This returns true if 'C' is a character that can show up in an
1250b57cec5SDimitry Andric // Itanium-mangled string.
1260b57cec5SDimitry Andric static bool IsLegalItaniumChar(char C) {
1270b57cec5SDimitry Andric   // Itanium CXX ABI [External Names]p5.1.1:
1280b57cec5SDimitry Andric   // '$' and '.' in mangled names are reserved for private implementations.
129349cc55cSDimitry Andric   return isAlnum(C) || C == '.' || C == '$' || C == '_';
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric // If 'Split' is true, then 'Mangled' is broken into individual words and each
1330b57cec5SDimitry Andric // word is demangled.  Otherwise, the entire string is treated as a single
1340b57cec5SDimitry Andric // mangled item.  The result is output to 'OS'.
1350b57cec5SDimitry Andric static void demangleLine(llvm::raw_ostream &OS, StringRef Mangled, bool Split) {
1360b57cec5SDimitry Andric   std::string Result;
1370b57cec5SDimitry Andric   if (Split) {
1380b57cec5SDimitry Andric     SmallVector<std::pair<StringRef, StringRef>, 16> Words;
1390b57cec5SDimitry Andric     SplitStringDelims(Mangled, Words, IsLegalItaniumChar);
1400b57cec5SDimitry Andric     for (const auto &Word : Words)
1415ffd83dbSDimitry Andric       Result += ::demangle(std::string(Word.first)) + Word.second.str();
1420b57cec5SDimitry Andric   } else
1435ffd83dbSDimitry Andric     Result = ::demangle(std::string(Mangled));
1440b57cec5SDimitry Andric   OS << Result << '\n';
1450b57cec5SDimitry Andric   OS.flush();
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
14881ad6265SDimitry Andric int llvm_cxxfilt_main(int argc, char **argv) {
1490b57cec5SDimitry Andric   InitLLVM X(argc, argv);
150fe6060f1SDimitry Andric   BumpPtrAllocator A;
151fe6060f1SDimitry Andric   StringSaver Saver(A);
152fe6060f1SDimitry Andric   CxxfiltOptTable Tbl;
153fe6060f1SDimitry Andric   ToolName = argv[0];
154fe6060f1SDimitry Andric   opt::InputArgList Args = Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,
155fe6060f1SDimitry Andric                                          [&](StringRef Msg) { error(Msg); });
156fe6060f1SDimitry Andric   if (Args.hasArg(OPT_help)) {
157fe6060f1SDimitry Andric     Tbl.printHelp(outs(),
158fe6060f1SDimitry Andric                   (Twine(ToolName) + " [options] <mangled>").str().c_str(),
159fe6060f1SDimitry Andric                   "LLVM symbol undecoration tool");
160fe6060f1SDimitry Andric     // TODO Replace this with OptTable API once it adds extrahelp support.
161fe6060f1SDimitry Andric     outs() << "\nPass @FILE as argument to read options from FILE.\n";
162fe6060f1SDimitry Andric     return 0;
163fe6060f1SDimitry Andric   }
164fe6060f1SDimitry Andric   if (Args.hasArg(OPT_version)) {
165fe6060f1SDimitry Andric     outs() << ToolName << '\n';
166fe6060f1SDimitry Andric     cl::PrintVersionMessage();
167fe6060f1SDimitry Andric     return 0;
168fe6060f1SDimitry Andric   }
1690b57cec5SDimitry Andric 
170fe6060f1SDimitry Andric   // The default value depends on the default triple. Mach-O has symbols
171fe6060f1SDimitry Andric   // prefixed with "_", so strip by default.
172fe6060f1SDimitry Andric   if (opt::Arg *A =
173fe6060f1SDimitry Andric           Args.getLastArg(OPT_strip_underscore, OPT_no_strip_underscore))
174fe6060f1SDimitry Andric     StripUnderscore = A->getOption().matches(OPT_strip_underscore);
175fe6060f1SDimitry Andric   else
176fe6060f1SDimitry Andric     StripUnderscore = Triple(sys::getProcessTriple()).isOSBinFormatMachO();
1770b57cec5SDimitry Andric 
178fe6060f1SDimitry Andric   Types = Args.hasArg(OPT_types);
179fe6060f1SDimitry Andric 
180fe6060f1SDimitry Andric   std::vector<std::string> Decorated = Args.getAllArgValues(OPT_INPUT);
1810b57cec5SDimitry Andric   if (Decorated.empty())
1820b57cec5SDimitry Andric     for (std::string Mangled; std::getline(std::cin, Mangled);)
1830b57cec5SDimitry Andric       demangleLine(llvm::outs(), Mangled, true);
1840b57cec5SDimitry Andric   else
1850b57cec5SDimitry Andric     for (const auto &Symbol : Decorated)
1860b57cec5SDimitry Andric       demangleLine(llvm::outs(), Symbol, false);
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   return EXIT_SUCCESS;
1890b57cec5SDimitry Andric }
190