llvm-project
189 строк · 6.2 Кб
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/LLVMDriver.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 {28OPT_INVALID = 0, // This is not an option ID.29#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),30#include "Opts.inc"31#undef OPTION32};33
34#define PREFIX(NAME, VALUE) \35static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \36static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \37NAME##_init, std::size(NAME##_init) - 1);38#include "Opts.inc"39#undef PREFIX40
41using namespace llvm::opt;42static constexpr opt::OptTable::Info InfoTable[] = {43#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),44#include "Opts.inc"45#undef OPTION46};47
48class CxxfiltOptTable : public opt::GenericOptTable {49public:50CxxfiltOptTable() : opt::GenericOptTable(InfoTable) {51setGroupedShortOptions(true);52}53};54} // namespace55
56static bool ParseParams;57static bool StripUnderscore;58static bool Types;59
60static StringRef ToolName;61
62static void error(const Twine &Message) {63WithColor::error(errs(), ToolName) << Message << '\n';64exit(1);65}
66
67static std::string demangle(const std::string &Mangled) {68using llvm::itanium_demangle::starts_with;69std::string_view DecoratedStr = Mangled;70bool CanHaveLeadingDot = true;71if (StripUnderscore && DecoratedStr[0] == '_') {72DecoratedStr.remove_prefix(1);73CanHaveLeadingDot = false;74}75
76std::string Result;77if (nonMicrosoftDemangle(DecoratedStr, Result, CanHaveLeadingDot,78ParseParams))79return Result;80
81std::string Prefix;82char *Undecorated = nullptr;83
84if (Types)85Undecorated = itaniumDemangle(DecoratedStr, ParseParams);86
87if (!Undecorated && starts_with(DecoratedStr, "__imp_")) {88Prefix = "import thunk for ";89Undecorated = itaniumDemangle(DecoratedStr.substr(6), ParseParams);90}91
92Result = Undecorated ? Prefix + Undecorated : Mangled;93free(Undecorated);94return 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(101StringRef Source,102SmallVectorImpl<std::pair<StringRef, StringRef>> &OutFragments,103function_ref<bool(char)> IsLegalChar) {104// The beginning of the input string.105const auto Head = Source.begin();106
107// Obtain any leading delimiters.108auto Start = std::find_if(Head, Source.end(), IsLegalChar);109if (Start != Head)110OutFragments.push_back({"", Source.slice(0, Start - Head)});111
112// Capture each word and the delimiters following that word.113while (Start != Source.end()) {114Start = std::find_if(Start, Source.end(), IsLegalChar);115auto End = std::find_if_not(Start, Source.end(), IsLegalChar);116auto DEnd = std::find_if(End, Source.end(), IsLegalChar);117OutFragments.push_back({Source.slice(Start - Head, End - Head),118Source.slice(End - Head, DEnd - Head)});119Start = 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.128return 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) {135std::string Result;136if (Split) {137SmallVector<std::pair<StringRef, StringRef>, 16> Words;138SplitStringDelims(Mangled, Words, IsLegalItaniumChar);139for (const auto &Word : Words)140Result += ::demangle(std::string(Word.first)) + Word.second.str();141} else142Result = ::demangle(std::string(Mangled));143OS << Result << '\n';144OS.flush();145}
146
147int llvm_cxxfilt_main(int argc, char **argv, const llvm::ToolContext &) {148BumpPtrAllocator A;149StringSaver Saver(A);150CxxfiltOptTable Tbl;151ToolName = argv[0];152opt::InputArgList Args = Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,153[&](StringRef Msg) { error(Msg); });154if (Args.hasArg(OPT_help)) {155Tbl.printHelp(outs(),156(Twine(ToolName) + " [options] <mangled>").str().c_str(),157"LLVM symbol undecoration tool");158// TODO Replace this with OptTable API once it adds extrahelp support.159outs() << "\nPass @FILE as argument to read options from FILE.\n";160return 0;161}162if (Args.hasArg(OPT_version)) {163outs() << ToolName << '\n';164cl::PrintVersionMessage();165return 0;166}167
168// The default value depends on the default triple. Mach-O has symbols169// prefixed with "_", so strip by default.170if (opt::Arg *A =171Args.getLastArg(OPT_strip_underscore, OPT_no_strip_underscore))172StripUnderscore = A->getOption().matches(OPT_strip_underscore);173else174StripUnderscore = Triple(sys::getProcessTriple()).isOSBinFormatMachO();175
176ParseParams = !Args.hasArg(OPT_no_params);177
178Types = Args.hasArg(OPT_types);179
180std::vector<std::string> Decorated = Args.getAllArgValues(OPT_INPUT);181if (Decorated.empty())182for (std::string Mangled; std::getline(std::cin, Mangled);)183demangleLine(llvm::outs(), Mangled, true);184else185for (const auto &Symbol : Decorated)186demangleLine(llvm::outs(), Symbol, false);187
188return EXIT_SUCCESS;189}
190