Path: blob/main/contrib/llvm-project/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp
35231 views
//===-- llvm-c++filt.cpp --------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/ADT/StringExtras.h"9#include "llvm/Demangle/Demangle.h"10#include "llvm/Demangle/StringViewExtras.h"11#include "llvm/Option/Arg.h"12#include "llvm/Option/ArgList.h"13#include "llvm/Option/Option.h"14#include "llvm/Support/CommandLine.h"15#include "llvm/Support/LLVMDriver.h"16#include "llvm/Support/WithColor.h"17#include "llvm/Support/raw_ostream.h"18#include "llvm/TargetParser/Host.h"19#include "llvm/TargetParser/Triple.h"20#include <cstdlib>21#include <iostream>2223using namespace llvm;2425namespace {26enum ID {27OPT_INVALID = 0, // This is not an option ID.28#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),29#include "Opts.inc"30#undef OPTION31};3233#define PREFIX(NAME, VALUE) \34static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \35static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \36NAME##_init, std::size(NAME##_init) - 1);37#include "Opts.inc"38#undef PREFIX3940using namespace llvm::opt;41static constexpr opt::OptTable::Info InfoTable[] = {42#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),43#include "Opts.inc"44#undef OPTION45};4647class CxxfiltOptTable : public opt::GenericOptTable {48public:49CxxfiltOptTable() : opt::GenericOptTable(InfoTable) {50setGroupedShortOptions(true);51}52};53} // namespace5455static bool ParseParams;56static bool StripUnderscore;57static bool Types;5859static StringRef ToolName;6061static void error(const Twine &Message) {62WithColor::error(errs(), ToolName) << Message << '\n';63exit(1);64}6566static std::string demangle(const std::string &Mangled) {67using llvm::itanium_demangle::starts_with;68std::string_view DecoratedStr = Mangled;69bool CanHaveLeadingDot = true;70if (StripUnderscore && DecoratedStr[0] == '_') {71DecoratedStr.remove_prefix(1);72CanHaveLeadingDot = false;73}7475std::string Result;76if (nonMicrosoftDemangle(DecoratedStr, Result, CanHaveLeadingDot,77ParseParams))78return Result;7980std::string Prefix;81char *Undecorated = nullptr;8283if (Types)84Undecorated = itaniumDemangle(DecoratedStr, ParseParams);8586if (!Undecorated && starts_with(DecoratedStr, "__imp_")) {87Prefix = "import thunk for ";88Undecorated = itaniumDemangle(DecoratedStr.substr(6), ParseParams);89}9091Result = Undecorated ? Prefix + Undecorated : Mangled;92free(Undecorated);93return Result;94}9596// Split 'Source' on any character that fails to pass 'IsLegalChar'. The97// returned vector consists of pairs where 'first' is the delimited word, and98// 'second' are the delimiters following that word.99static void SplitStringDelims(100StringRef Source,101SmallVectorImpl<std::pair<StringRef, StringRef>> &OutFragments,102function_ref<bool(char)> IsLegalChar) {103// The beginning of the input string.104const auto Head = Source.begin();105106// Obtain any leading delimiters.107auto Start = std::find_if(Head, Source.end(), IsLegalChar);108if (Start != Head)109OutFragments.push_back({"", Source.slice(0, Start - Head)});110111// Capture each word and the delimiters following that word.112while (Start != Source.end()) {113Start = std::find_if(Start, Source.end(), IsLegalChar);114auto End = std::find_if_not(Start, Source.end(), IsLegalChar);115auto DEnd = std::find_if(End, Source.end(), IsLegalChar);116OutFragments.push_back({Source.slice(Start - Head, End - Head),117Source.slice(End - Head, DEnd - Head)});118Start = DEnd;119}120}121122// This returns true if 'C' is a character that can show up in an123// Itanium-mangled string.124static bool IsLegalItaniumChar(char C) {125// Itanium CXX ABI [External Names]p5.1.1:126// '$' and '.' in mangled names are reserved for private implementations.127return isAlnum(C) || C == '.' || C == '$' || C == '_';128}129130// If 'Split' is true, then 'Mangled' is broken into individual words and each131// word is demangled. Otherwise, the entire string is treated as a single132// mangled item. The result is output to 'OS'.133static void demangleLine(llvm::raw_ostream &OS, StringRef Mangled, bool Split) {134std::string Result;135if (Split) {136SmallVector<std::pair<StringRef, StringRef>, 16> Words;137SplitStringDelims(Mangled, Words, IsLegalItaniumChar);138for (const auto &Word : Words)139Result += ::demangle(std::string(Word.first)) + Word.second.str();140} else141Result = ::demangle(std::string(Mangled));142OS << Result << '\n';143OS.flush();144}145146int llvm_cxxfilt_main(int argc, char **argv, const llvm::ToolContext &) {147BumpPtrAllocator A;148StringSaver Saver(A);149CxxfiltOptTable Tbl;150ToolName = argv[0];151opt::InputArgList Args = Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,152[&](StringRef Msg) { error(Msg); });153if (Args.hasArg(OPT_help)) {154Tbl.printHelp(outs(),155(Twine(ToolName) + " [options] <mangled>").str().c_str(),156"LLVM symbol undecoration tool");157// TODO Replace this with OptTable API once it adds extrahelp support.158outs() << "\nPass @FILE as argument to read options from FILE.\n";159return 0;160}161if (Args.hasArg(OPT_version)) {162outs() << ToolName << '\n';163cl::PrintVersionMessage();164return 0;165}166167// The default value depends on the default triple. Mach-O has symbols168// prefixed with "_", so strip by default.169if (opt::Arg *A =170Args.getLastArg(OPT_strip_underscore, OPT_no_strip_underscore))171StripUnderscore = A->getOption().matches(OPT_strip_underscore);172else173StripUnderscore = Triple(sys::getProcessTriple()).isOSBinFormatMachO();174175ParseParams = !Args.hasArg(OPT_no_params);176177Types = Args.hasArg(OPT_types);178179std::vector<std::string> Decorated = Args.getAllArgValues(OPT_INPUT);180if (Decorated.empty())181for (std::string Mangled; std::getline(std::cin, Mangled);)182demangleLine(llvm::outs(), Mangled, true);183else184for (const auto &Symbol : Decorated)185demangleLine(llvm::outs(), Symbol, false);186187return EXIT_SUCCESS;188}189190191