Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/EnumDumper.cpp
//===- EnumDumper.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "EnumDumper.h" #include "BuiltinDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" using namespace llvm; EnumDumper::EnumDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void EnumDumper::start(const PDBSymbolTypeEnum &Symbol) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "enum "; WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); if (!opts::NoEnumDefs) { auto BuiltinType = Symbol.getUnderlyingType(); if (BuiltinType->getBuiltinType() != PDB_BuiltinType::Int || BuiltinType->getLength() != 4) { Printer << " : "; BuiltinDumper Dumper(Printer); Dumper.start(*BuiltinType); } Printer << " {"; Printer.Indent(); auto EnumValues = Symbol.findAllChildren<PDBSymbolData>(); while (auto EnumValue = EnumValues->getNext()) { if (EnumValue->getDataKind() != PDB_DataKind::Constant) continue; Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << EnumValue->getName(); Printer << " = "; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << EnumValue->getValue(); } Printer.Unindent(); Printer.NewLine(); Printer << "}"; } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/BuiltinDumper.h
//===- BuiltinDumper.h ---------------------------------------- *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_BUILTINDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_BUILTINDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class BuiltinDumper : public PDBSymDumper { public: BuiltinDumper(LinePrinter &P); void start(const PDBSymbolTypeBuiltin &Symbol); private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/ClassDefinitionDumper.h
//===- ClassDefinitionDumper.h - --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_CLASSDEFINITIONDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_CLASSDEFINITIONDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include <list> #include <memory> #include <unordered_map> namespace llvm { class LinePrinter; class ClassDefinitionDumper : public PDBSymDumper { public: ClassDefinitionDumper(LinePrinter &P); void start(const PDBSymbolTypeUDT &Exe); void dump(const PDBSymbolTypeBaseClass &Symbol) override; void dump(const PDBSymbolData &Symbol) override; void dump(const PDBSymbolTypeEnum &Symbol) override; void dump(const PDBSymbolFunc &Symbol) override; void dump(const PDBSymbolTypeTypedef &Symbol) override; void dump(const PDBSymbolTypeUDT &Symbol) override; void dump(const PDBSymbolTypeVTable &Symbol) override; private: LinePrinter &Printer; struct SymbolGroup { SymbolGroup() {} SymbolGroup(SymbolGroup &&Other) { Functions = std::move(Other.Functions); Data = std::move(Other.Data); Unknown = std::move(Other.Unknown); } std::list<std::unique_ptr<PDBSymbolFunc>> Functions; std::list<std::unique_ptr<PDBSymbolData>> Data; std::list<std::unique_ptr<PDBSymbol>> Unknown; SymbolGroup(const SymbolGroup &other) = delete; SymbolGroup &operator=(const SymbolGroup &other) = delete; }; typedef std::unordered_map<int, SymbolGroup> SymbolGroupByAccess; int dumpAccessGroup(PDB_MemberAccess Access, const SymbolGroup &Group); }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Support DebugInfoPDB ) add_llvm_tool(llvm-pdbdump llvm-pdbdump.cpp BuiltinDumper.cpp ClassDefinitionDumper.cpp CompilandDumper.cpp EnumDumper.cpp ExternalSymbolDumper.cpp FunctionDumper.cpp LinePrinter.cpp TypeDumper.cpp TypedefDumper.cpp VariableDumper.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/VariableDumper.cpp
//===- VariableDumper.cpp - -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "VariableDumper.h" #include "BuiltinDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "FunctionDumper.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/Support/Format.h" using namespace llvm; VariableDumper::VariableDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void VariableDumper::start(const PDBSymbolData &Var) { if (Var.isCompilerGenerated() && opts::ExcludeCompilerGenerated) return; if (Printer.IsSymbolExcluded(Var.getName())) return; auto VarType = Var.getType(); switch (auto LocType = Var.getLocationType()) { case PDB_LocType::Static: Printer.NewLine(); Printer << "data ["; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(Var.getVirtualAddress(), 10); Printer << "] "; WithColor(Printer, PDB_ColorItem::Keyword).get() << "static "; dumpSymbolTypeAndName(*VarType, Var.getName()); break; case PDB_LocType::Constant: if (isa<PDBSymbolTypeEnum>(*VarType)) break; Printer.NewLine(); Printer << "data "; WithColor(Printer, PDB_ColorItem::Keyword).get() << "const "; dumpSymbolTypeAndName(*VarType, Var.getName()); Printer << " = "; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << Var.getValue(); break; case PDB_LocType::ThisRel: Printer.NewLine(); Printer << "data "; WithColor(Printer, PDB_ColorItem::Offset).get() << "+" << format_hex(Var.getOffset(), 4) << " "; dumpSymbolTypeAndName(*VarType, Var.getName()); break; case PDB_LocType::BitField: Printer.NewLine(); Printer << "data "; WithColor(Printer, PDB_ColorItem::Offset).get() << "+" << format_hex(Var.getOffset(), 4) << " "; dumpSymbolTypeAndName(*VarType, Var.getName()); Printer << " : "; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << Var.getLength(); break; default: Printer.NewLine(); Printer << "data "; Printer << "unknown(" << LocType << ") "; WithColor(Printer, PDB_ColorItem::Identifier).get() << Var.getName(); break; } } void VariableDumper::dump(const PDBSymbolTypeBuiltin &Symbol) { BuiltinDumper Dumper(Printer); Dumper.start(Symbol); } void VariableDumper::dump(const PDBSymbolTypeEnum &Symbol) { WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); } void VariableDumper::dump(const PDBSymbolTypeFunctionSig &Symbol) {} void VariableDumper::dump(const PDBSymbolTypePointer &Symbol) { auto PointeeType = Symbol.getPointeeType(); if (!PointeeType) return; if (auto Func = dyn_cast<PDBSymbolFunc>(PointeeType.get())) { FunctionDumper NestedDumper(Printer); FunctionDumper::PointerType Pointer = Symbol.isReference() ? FunctionDumper::PointerType::Reference : FunctionDumper::PointerType::Pointer; NestedDumper.start(*Func, Pointer); } else { if (Symbol.isConstType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "const "; if (Symbol.isVolatileType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "volatile "; PointeeType->dump(*this); Printer << (Symbol.isReference() ? "&" : "*"); } } void VariableDumper::dump(const PDBSymbolTypeTypedef &Symbol) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "typedef "; WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); } void VariableDumper::dump(const PDBSymbolTypeUDT &Symbol) { WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); } void VariableDumper::dumpSymbolTypeAndName(const PDBSymbol &Type, StringRef Name) { if (auto *ArrayType = dyn_cast<PDBSymbolTypeArray>(&Type)) { std::string IndexSpec; raw_string_ostream IndexStream(IndexSpec); std::unique_ptr<PDBSymbol> ElementType = ArrayType->getElementType(); while (auto NestedArray = dyn_cast<PDBSymbolTypeArray>(ElementType.get())) { IndexStream << "["; IndexStream << NestedArray->getCount(); IndexStream << "]"; ElementType = NestedArray->getElementType(); } IndexStream << "[" << ArrayType->getCount() << "]"; ElementType->dump(*this); WithColor(Printer, PDB_ColorItem::Identifier).get() << " " << Name; Printer << IndexStream.str(); } else { if (!tryDumpFunctionPointer(Type, Name)) { Type.dump(*this); WithColor(Printer, PDB_ColorItem::Identifier).get() << " " << Name; } } } bool VariableDumper::tryDumpFunctionPointer(const PDBSymbol &Type, StringRef Name) { // Function pointers come across as pointers to function signatures. But the // signature carries no name, so we have to handle this case separately. if (auto *PointerType = dyn_cast<PDBSymbolTypePointer>(&Type)) { auto PointeeType = PointerType->getPointeeType(); if (auto *FunctionSig = dyn_cast<PDBSymbolTypeFunctionSig>(PointeeType.get())) { FunctionDumper Dumper(Printer); FunctionDumper::PointerType PT = FunctionDumper::PointerType::Pointer; if (PointerType->isReference()) PT = FunctionDumper::PointerType::Reference; std::string NameStr(Name.begin(), Name.end()); Dumper.start(*FunctionSig, NameStr.c_str(), PT); return true; } } return false; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/LLVMBuild.txt
;===- ./tools/llvm-pdbdump/LLVMBuild.txt -----------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-pdbdump parent = Tools required_libraries = DebugInfoPDB
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/llvm-pdbdump.cpp
//===- llvm-pdbdump.cpp - Dump debug info from a PDB file -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Dumps debug information present in PDB files. This utility makes use of // the Microsoft Windows SDK, so will not compile or run on non-Windows // platforms. // //===----------------------------------------------------------------------===// #include "llvm-pdbdump.h" #include "CompilandDumper.h" #include "ExternalSymbolDumper.h" #include "FunctionDumper.h" #include "LinePrinter.h" #include "TypeDumper.h" #include "VariableDumper.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Config/config.h" #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" #include "llvm/DebugInfo/PDB/IPDBRawSymbol.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDB.h" #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolExe.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Process.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Signals.h" #if defined(HAVE_DIA_SDK) #include <windows.h> #endif using namespace llvm; namespace opts { enum class PDB_DumpType { ByType, ByObjFile, Both }; cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input PDB files>"), cl::OneOrMore); cl::OptionCategory TypeCategory("Symbol Type Options"); cl::OptionCategory FilterCategory("Filtering Options"); cl::OptionCategory OtherOptions("Other Options"); cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"), cl::cat(TypeCategory)); cl::opt<bool> Symbols("symbols", cl::desc("Display symbols for each compiland"), cl::cat(TypeCategory)); cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"), cl::cat(TypeCategory)); cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"), cl::cat(TypeCategory)); cl::opt<bool> Types("types", cl::desc("Display types"), cl::cat(TypeCategory)); cl::opt<bool> All("all", cl::desc("Implies all other options in 'Symbol Types' category"), cl::cat(TypeCategory)); cl::opt<uint64_t> LoadAddress( "load-address", cl::desc("Assume the module is loaded at the specified address"), cl::cat(OtherOptions)); cl::list<std::string> ExcludeTypes("exclude-types", cl::desc("Exclude types by regular expression"), cl::ZeroOrMore, cl::cat(FilterCategory)); cl::list<std::string> ExcludeSymbols("exclude-symbols", cl::desc("Exclude symbols by regular expression"), cl::ZeroOrMore, cl::cat(FilterCategory)); cl::list<std::string> ExcludeCompilands("exclude-compilands", cl::desc("Exclude compilands by regular expression"), cl::ZeroOrMore, cl::cat(FilterCategory)); cl::opt<bool> ExcludeCompilerGenerated( "no-compiler-generated", cl::desc("Don't show compiler generated types and symbols"), cl::cat(FilterCategory)); cl::opt<bool> ExcludeSystemLibraries("no-system-libs", cl::desc("Don't show symbols from system libraries"), cl::cat(FilterCategory)); cl::opt<bool> NoClassDefs("no-class-definitions", cl::desc("Don't display full class definitions"), cl::cat(FilterCategory)); cl::opt<bool> NoEnumDefs("no-enum-definitions", cl::desc("Don't display full enum definitions"), cl::cat(FilterCategory)); } static void dumpInput(StringRef Path) { std::unique_ptr<IPDBSession> Session; PDB_ErrorCode Error = llvm::loadDataForPDB(PDB_ReaderType::DIA, Path, Session); switch (Error) { case PDB_ErrorCode::Success: break; case PDB_ErrorCode::NoPdbImpl: outs() << "Reading PDBs is not supported on this platform.\n"; return; case PDB_ErrorCode::InvalidPath: outs() << "Unable to load PDB at '" << Path << "'. Check that the file exists and is readable.\n"; return; case PDB_ErrorCode::InvalidFileFormat: outs() << "Unable to load PDB at '" << Path << "'. The file has an unrecognized format.\n"; return; default: outs() << "Unable to load PDB at '" << Path << "'. An unknown error occured.\n"; return; } if (opts::LoadAddress) Session->setLoadAddress(opts::LoadAddress); LinePrinter Printer(2, outs()); auto GlobalScope(Session->getGlobalScope()); std::string FileName(GlobalScope->getSymbolsFileName()); WithColor(Printer, PDB_ColorItem::None).get() << "Summary for "; WithColor(Printer, PDB_ColorItem::Path).get() << FileName; Printer.Indent(); uint64_t FileSize = 0; Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size"; if (!llvm::sys::fs::file_size(FileName, FileSize)) { Printer << ": " << FileSize << " bytes"; } else { Printer << ": (Unable to obtain file size)"; } Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid"; Printer << ": " << GlobalScope->getGuid(); Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age"; Printer << ": " << GlobalScope->getAge(); Printer.NewLine(); WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes"; Printer << ": "; if (GlobalScope->hasCTypes()) outs() << "HasCTypes "; if (GlobalScope->hasPrivateSymbols()) outs() << "HasPrivateSymbols "; Printer.Unindent(); if (opts::Compilands) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---COMPILANDS---"; Printer.Indent(); auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>(); CompilandDumper Dumper(Printer); while (auto Compiland = Compilands->getNext()) Dumper.start(*Compiland, false); Printer.Unindent(); } if (opts::Types) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---"; Printer.Indent(); TypeDumper Dumper(Printer); Dumper.start(*GlobalScope); Printer.Unindent(); } if (opts::Symbols) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---"; Printer.Indent(); auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>(); CompilandDumper Dumper(Printer); while (auto Compiland = Compilands->getNext()) Dumper.start(*Compiland, true); Printer.Unindent(); } if (opts::Globals) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---"; Printer.Indent(); { FunctionDumper Dumper(Printer); auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>(); while (auto Function = Functions->getNext()) { Printer.NewLine(); Dumper.start(*Function, FunctionDumper::PointerType::None); } } { auto Vars = GlobalScope->findAllChildren<PDBSymbolData>(); VariableDumper Dumper(Printer); while (auto Var = Vars->getNext()) Dumper.start(*Var); } { auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>(); CompilandDumper Dumper(Printer); while (auto Thunk = Thunks->getNext()) Dumper.dump(*Thunk); } Printer.Unindent(); } if (opts::Externals) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---"; Printer.Indent(); ExternalSymbolDumper Dumper(Printer); Dumper.start(*GlobalScope); } outs().flush(); } int main(int argc_, const char *argv_[]) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc_, argv_); SmallVector<const char *, 256> argv; llvm::SpecificBumpPtrAllocator<char> ArgAllocator; std::error_code EC = llvm::sys::Process::GetArgumentVector( argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator); if (EC) { llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n'; return 1; } llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n"); if (opts::All) { opts::Compilands = true; opts::Symbols = true; opts::Globals = true; opts::Types = true; opts::Externals = true; } if (opts::ExcludeCompilerGenerated) { opts::ExcludeTypes.push_back("__vc_attributes"); opts::ExcludeCompilands.push_back("* Linker *"); } if (opts::ExcludeSystemLibraries) { opts::ExcludeCompilands.push_back( "f:\\binaries\\Intermediate\\vctools\\crt_bld"); } #if defined(HAVE_DIA_SDK) CoInitializeEx(nullptr, COINIT_MULTITHREADED); #endif std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(), dumpInput); #if defined(HAVE_DIA_SDK) CoUninitialize(); #endif return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/EnumDumper.h
//===- EnumDumper.h - -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_ENUMDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_ENUMDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class EnumDumper : public PDBSymDumper { public: EnumDumper(LinePrinter &P); void start(const PDBSymbolTypeEnum &Symbol); private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/LinePrinter.h
//===- LinePrinter.h ------------------------------------------ *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_LINEPRINTER_H #define LLVM_TOOLS_LLVMPDBDUMP_LINEPRINTER_H #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Regex.h" #include <list> namespace llvm { class LinePrinter { friend class WithColor; public: LinePrinter(int Indent, raw_ostream &Stream); void Indent(); void Unindent(); void NewLine(); raw_ostream &getStream() { return OS; } int getIndentLevel() const { return CurrentIndent; } bool IsTypeExcluded(llvm::StringRef TypeName); bool IsSymbolExcluded(llvm::StringRef SymbolName); bool IsCompilandExcluded(llvm::StringRef CompilandName); private: template <typename Iter> void SetFilters(std::list<Regex> &List, Iter Begin, Iter End) { List.clear(); for (; Begin != End; ++Begin) List.emplace_back(StringRef(*Begin)); } raw_ostream &OS; int IndentSpaces; int CurrentIndent; std::list<Regex> CompilandFilters; std::list<Regex> TypeFilters; std::list<Regex> SymbolFilters; }; template <class T> inline raw_ostream &operator<<(LinePrinter &Printer, const T &Item) { Printer.getStream() << Item; return Printer.getStream(); } enum class PDB_ColorItem { None, Address, Type, Keyword, Offset, Identifier, Path, SectionHeader, LiteralValue, Register, }; class WithColor { public: WithColor(LinePrinter &P, PDB_ColorItem C); ~WithColor(); raw_ostream &get() { return OS; } private: void translateColor(PDB_ColorItem C, raw_ostream::Colors &Color, bool &Bold) const; raw_ostream &OS; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/TypeDumper.h
//===- TypeDumper.h - PDBSymDumper implementation for types *- C++ ------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_TYPEDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_TYPEDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class TypeDumper : public PDBSymDumper { public: TypeDumper(LinePrinter &P); void start(const PDBSymbolExe &Exe); void dump(const PDBSymbolTypeEnum &Symbol) override; void dump(const PDBSymbolTypeTypedef &Symbol) override; void dump(const PDBSymbolTypeUDT &Symbol) override; private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/VariableDumper.h
//===- VariableDumper.h - PDBSymDumper implementation for types -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_VARIABLEDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_VARIABLEDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" #include "llvm/ADT/StringRef.h" namespace llvm { class LinePrinter; class VariableDumper : public PDBSymDumper { public: VariableDumper(LinePrinter &P); void start(const PDBSymbolData &Var); void dump(const PDBSymbolTypeBuiltin &Symbol) override; void dump(const PDBSymbolTypeEnum &Symbol) override; void dump(const PDBSymbolTypeFunctionSig &Symbol) override; void dump(const PDBSymbolTypePointer &Symbol) override; void dump(const PDBSymbolTypeTypedef &Symbol) override; void dump(const PDBSymbolTypeUDT &Symbol) override; private: void dumpSymbolTypeAndName(const PDBSymbol &Type, StringRef Name); bool tryDumpFunctionPointer(const PDBSymbol &Type, StringRef Name); LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/ExternalSymbolDumper.h
//===- ExternalSymbolDumper.h --------------------------------- *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_EXTERNALSYMBOLDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_EXTERNALSYMBOLDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class ExternalSymbolDumper : public PDBSymDumper { public: ExternalSymbolDumper(LinePrinter &P); void start(const PDBSymbolExe &Symbol); void dump(const PDBSymbolPublicSymbol &Symbol) override; private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/TypedefDumper.cpp
//===- TypedefDumper.cpp - PDBSymDumper impl for typedefs -------- * C++ *-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "TypedefDumper.h" #include "BuiltinDumper.h" #include "FunctionDumper.h" #include "LinePrinter.h" #include "llvm-pdbdump.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBExtras.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" using namespace llvm; TypedefDumper::TypedefDumper(LinePrinter &P) : PDBSymDumper(true), Printer(P) {} void TypedefDumper::start(const PDBSymbolTypeTypedef &Symbol) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "typedef "; uint32_t TargetId = Symbol.getTypeId(); if (auto TypeSymbol = Symbol.getSession().getSymbolById(TargetId)) TypeSymbol->dump(*this); WithColor(Printer, PDB_ColorItem::Identifier).get() << " " << Symbol.getName(); } void TypedefDumper::dump(const PDBSymbolTypeArray &Symbol) {} void TypedefDumper::dump(const PDBSymbolTypeBuiltin &Symbol) { BuiltinDumper Dumper(Printer); Dumper.start(Symbol); } void TypedefDumper::dump(const PDBSymbolTypeEnum &Symbol) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "enum "; WithColor(Printer, PDB_ColorItem::Type).get() << " " << Symbol.getName(); } void TypedefDumper::dump(const PDBSymbolTypePointer &Symbol) { if (Symbol.isConstType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "const "; if (Symbol.isVolatileType()) WithColor(Printer, PDB_ColorItem::Keyword).get() << "volatile "; uint32_t PointeeId = Symbol.getTypeId(); auto PointeeType = Symbol.getSession().getSymbolById(PointeeId); if (!PointeeType) return; if (auto FuncSig = dyn_cast<PDBSymbolTypeFunctionSig>(PointeeType.get())) { FunctionDumper::PointerType Pointer = FunctionDumper::PointerType::Pointer; if (Symbol.isReference()) Pointer = FunctionDumper::PointerType::Reference; FunctionDumper NestedDumper(Printer); NestedDumper.start(*FuncSig, nullptr, Pointer); } else { PointeeType->dump(*this); Printer << ((Symbol.isReference()) ? "&" : "*"); } } void TypedefDumper::dump(const PDBSymbolTypeFunctionSig &Symbol) { FunctionDumper Dumper(Printer); Dumper.start(Symbol, nullptr, FunctionDumper::PointerType::None); } void TypedefDumper::dump(const PDBSymbolTypeUDT &Symbol) { WithColor(Printer, PDB_ColorItem::Keyword).get() << "class "; WithColor(Printer, PDB_ColorItem::Type).get() << Symbol.getName(); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-pdbdump/CompilandDumper.h
//===- CompilandDumper.h - llvm-pdbdump compiland symbol dumper *- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVMPDBDUMP_COMPILANDDUMPER_H #define LLVM_TOOLS_LLVMPDBDUMP_COMPILANDDUMPER_H #include "llvm/DebugInfo/PDB/PDBSymDumper.h" namespace llvm { class LinePrinter; class CompilandDumper : public PDBSymDumper { public: CompilandDumper(LinePrinter &P); void start(const PDBSymbolCompiland &Symbol, bool Children); void dump(const PDBSymbolCompilandDetails &Symbol) override; void dump(const PDBSymbolCompilandEnv &Symbol) override; void dump(const PDBSymbolData &Symbol) override; void dump(const PDBSymbolFunc &Symbol) override; void dump(const PDBSymbolLabel &Symbol) override; void dump(const PDBSymbolThunk &Symbol) override; void dump(const PDBSymbolTypeTypedef &Symbol) override; void dump(const PDBSymbolUnknown &Symbol) override; private: LinePrinter &Printer; }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-shlib/libllvm.cpp
//===-libllvm.cpp - LLVM Shared Library -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is empty and serves only the purpose of making CMake happy because // you can't define a target with no sources. // //===----------------------------------------------------------------------===// #include "llvm/Config/config.h" #if defined(DISABLE_LLVM_DYLIB_ATEXIT) extern "C" int __cxa_atexit(); extern "C" int __cxa_atexit() { return 0; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-shlib/CMakeLists.txt
# This tool creates a shared library from the LLVM libraries. Generating this # library is enabled by setting LLVM_BUILD_LLVM_DYLIB=yes on the CMake # commandline. By default the shared library only exports the LLVM C API. # You can configure which libraries from LLVM you want to include in the shared # library by setting LLVM_DYLIB_COMPONENTS to a semi-colon delimited list of # LLVM components. All compoenent names handled by llvm-config are valid. if(NOT DEFINED LLVM_DYLIB_COMPONENTS) set(LLVM_DYLIB_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Analysis BitReader BitWriter CodeGen Core DebugInfoDWARF DebugInfoPDB ExecutionEngine IPA IPO IRReader InstCombine Instrumentation Interpreter Linker MCDisassembler MCJIT ObjCARCOpts Object ScalarOpts Support Target TransformUtils Vectorize native ) endif() add_definitions( -DLLVM_VERSION_INFO=\"${PACKAGE_VERSION}\" ) set(SOURCES libllvm.cpp ) llvm_map_components_to_libnames(LIB_NAMES ${LLVM_DYLIB_COMPONENTS}) if(NOT DEFINED LLVM_DYLIB_EXPORTED_SYMBOL_FILE) if( WIN32 AND NOT CYGWIN ) message(FATAL_ERROR "Auto-generation not implemented for Win32 without GNU utils. Please specify LLVM_EXPORTED_SYMBOL_FILE.") endif() # To get the export list for a single llvm library: # nm ${LIB_PATH} | awk "/T _LLVM/ { print $3 }" | sort -u | sed -e "s/^_//g" > ${LIB_PATH}.exports set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_BINARY_DIR}/libllvm.exports) if (NOT LLVM_DYLIB_EXPORT_ALL) foreach (lib ${LIB_NAMES}) set(LIB_DIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX}) set(LIB_NAME ${LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}${lib}) set(LIB_PATH ${LIB_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX}) set(LIB_EXPORTS_PATH ${LIB_NAME}.exports) list(APPEND LLVM_DYLIB_REQUIRED_EXPORTS ${LIB_EXPORTS_PATH}) add_custom_command(OUTPUT ${LIB_EXPORTS_PATH} COMMAND nm ${LIB_PATH} | awk "/T _LLVM/ || /T LLVM/ { print $3 }" | sort -u | sed -e "s/^_//g" > ${LIB_EXPORTS_PATH} WORKING_DIRECTORY ${LIB_DIR} DEPENDS ${lib} COMMENT "Generating Export list for ${lib}..." VERBATIM ) endforeach () endif() if (LLVM_DYLIB_EXPORT_ALL) add_custom_command(OUTPUT ${LLVM_EXPORTED_SYMBOL_FILE} COMMAND echo \"LLVM*\" > ${LLVM_EXPORTED_SYMBOL_FILE} && echo \"_Z*llvm*\" >> ${LLVM_EXPORTED_SYMBOL_FILE} WORKING_DIRECTORY ${LIB_DIR} DEPENDS ${LLVM_DYLIB_REQUIRED_EXPORTS} COMMENT "Generating combined export list...") else() add_custom_command(OUTPUT ${LLVM_EXPORTED_SYMBOL_FILE} COMMAND cat ${LLVM_DYLIB_REQUIRED_EXPORTS} > ${LLVM_EXPORTED_SYMBOL_FILE} WORKING_DIRECTORY ${LIB_DIR} DEPENDS ${LLVM_DYLIB_REQUIRED_EXPORTS} COMMENT "Generating combined export list...") endif() add_custom_target(libLLVMExports DEPENDS ${LLVM_EXPORTED_SYMBOL_FILE}) else() set(LLVM_EXPORTED_SYMBOL_FILE ${LLVM_DYLIB_EXPORTED_SYMBOL_FILE}) add_custom_target(libLLVMExports DEPENDS ${LLVM_EXPORTED_SYMBOL_FILE}) endif() add_llvm_library(LLVM SHARED ${SOURCES}) list(REMOVE_DUPLICATES LIB_NAMES) if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") # FIXME: It should be "GNU ld for elf" # GNU ld doesn't resolve symbols in the version script. set(LIB_NAMES -Wl,--whole-archive ${LIB_NAMES} -Wl,--no-whole-archive) elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") set(LIB_NAMES -Wl,-all_load ${LIB_NAMES}) endif() target_link_libraries(LLVM PRIVATE ${LIB_NAMES}) add_dependencies(LLVM libLLVMExports) if (APPLE) set_property(TARGET LLVM APPEND_STRING PROPERTY LINK_FLAGS " -compatibility_version ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR} -current_version ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}") endif()
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/BreakpointPrinter.cpp
//===- BreakpointPrinter.cpp - Breakpoint location printer ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Breakpoint location printer. /// //===----------------------------------------------------------------------===// #include "BreakpointPrinter.h" #include "llvm/ADT/StringSet.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace llvm; namespace { struct BreakpointPrinter : public ModulePass { raw_ostream &Out; static char ID; DITypeIdentifierMap TypeIdentifierMap; BreakpointPrinter(raw_ostream &out) : ModulePass(ID), Out(out) {} void getContextName(const DIScope *Context, std::string &N) { if (auto *NS = dyn_cast<DINamespace>(Context)) { if (!NS->getName().empty()) { getContextName(NS->getScope(), N); N = N + NS->getName().str() + "::"; } } else if (auto *TY = dyn_cast<DIType>(Context)) { if (!TY->getName().empty()) { getContextName(TY->getScope().resolve(TypeIdentifierMap), N); N = N + TY->getName().str() + "::"; } } } bool runOnModule(Module &M) override { TypeIdentifierMap.clear(); NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu"); if (CU_Nodes) TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes); StringSet<> Processed; if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { std::string Name; auto *SP = cast_or_null<DISubprogram>(NMD->getOperand(i)); if (!SP) continue; getContextName(SP->getScope().resolve(TypeIdentifierMap), Name); Name = Name + SP->getDisplayName().str(); if (!Name.empty() && Processed.insert(Name).second) { Out << Name << "\n"; } } return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } }; char BreakpointPrinter::ID = 0; } ModulePass *llvm::createBreakpointPrinter(raw_ostream &out) { return new BreakpointPrinter(out); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/GraphPrinters.cpp
//===- GraphPrinters.cpp - DOT printers for various graph types -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several printers for various different types of graphs used // by the LLVM infrastructure. It uses the generic graph interface to convert // the graph into a .dot graph. These graphs can then be processed with the // "dot" tool to convert them to postscript or some other suitable format. // //===----------------------------------------------------------------------===// #include "llvm/IR/Dominators.h" #include "llvm/Pass.h" using namespace llvm; //===----------------------------------------------------------------------===// // DomInfoPrinter Pass //===----------------------------------------------------------------------===// namespace { class DomInfoPrinter : public FunctionPass { public: static char ID; // Pass identification, replacement for typeid DomInfoPrinter() : FunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequired<DominatorTreeWrapperPass>(); } bool runOnFunction(Function &F) override { getAnalysis<DominatorTreeWrapperPass>().dump(); return false; } }; } char DomInfoPrinter::ID = 0; static RegisterPass<DomInfoPrinter> DIP("print-dom-info", "Dominator Info Printer", true, true);
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/PrintSCC.cpp
//===- PrintSCC.cpp - Enumerate SCCs in some key graphs -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides passes to print out SCCs in a CFG or a CallGraph. // Normally, you would not use these passes; instead, you would use the // scc_iterator directly to enumerate SCCs and process them in some way. These // passes serve three purposes: // // (1) As a reference for how to use the scc_iterator. // (2) To print out the SCCs for a CFG or a CallGraph: // analyze -print-cfg-sccs to print the SCCs in each CFG of a module. // analyze -print-cfg-sccs -stats to print the #SCCs and the maximum SCC size. // analyze -print-cfg-sccs -debug > /dev/null to watch the algorithm in action. // // and similarly: // analyze -print-callgraph-sccs [-stats] [-debug] to print SCCs in the CallGraph // // (3) To test the scc_iterator. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SCCIterator.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { struct CFGSCC : public FunctionPass { static char ID; // Pass identification, replacement for typeid CFGSCC() : FunctionPass(ID) {} bool runOnFunction(Function& func) override; void print(raw_ostream &O, const Module* = nullptr) const override { } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } }; struct CallGraphSCC : public ModulePass { static char ID; // Pass identification, replacement for typeid CallGraphSCC() : ModulePass(ID) {} // run - Print out SCCs in the call graph for the specified module. bool runOnModule(Module &M) override; void print(raw_ostream &O, const Module* = nullptr) const override { } // getAnalysisUsage - This pass requires the CallGraph. void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequired<CallGraphWrapperPass>(); } }; } char CFGSCC::ID = 0; static RegisterPass<CFGSCC> Y("print-cfg-sccs", "Print SCCs of each function CFG"); char CallGraphSCC::ID = 0; static RegisterPass<CallGraphSCC> Z("print-callgraph-sccs", "Print SCCs of the Call Graph"); bool CFGSCC::runOnFunction(Function &F) { unsigned sccNum = 0; errs() << "SCCs for Function " << F.getName() << " in PostOrder:"; for (scc_iterator<Function*> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI) { const std::vector<BasicBlock *> &nextSCC = *SCCI; errs() << "\nSCC #" << ++sccNum << " : "; for (std::vector<BasicBlock*>::const_iterator I = nextSCC.begin(), E = nextSCC.end(); I != E; ++I) errs() << (*I)->getName() << ", "; if (nextSCC.size() == 1 && SCCI.hasLoop()) errs() << " (Has self-loop)."; } errs() << "\n"; return true; } // run - Print out SCCs in the call graph for the specified module. bool CallGraphSCC::runOnModule(Module &M) { CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); unsigned sccNum = 0; errs() << "SCCs for the program in PostOrder:"; for (scc_iterator<CallGraph*> SCCI = scc_begin(&CG); !SCCI.isAtEnd(); ++SCCI) { const std::vector<CallGraphNode*> &nextSCC = *SCCI; errs() << "\nSCC #" << ++sccNum << " : "; for (std::vector<CallGraphNode*>::const_iterator I = nextSCC.begin(), E = nextSCC.end(); I != E; ++I) errs() << ((*I)->getFunction() ? (*I)->getFunction()->getName() : "external node") << ", "; if (nextSCC.size() == 1 && SCCI.hasLoop()) errs() << " (Has self-loop)."; } errs() << "\n"; return true; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/NewPMDriver.h
//===- NewPMDriver.h - Function to drive opt with the new PM ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// A single function which is called to drive the opt behavior for the new /// PassManager. /// /// This is only in a separate TU with a header to avoid including all of the /// old pass manager headers and the new pass manager headers into the same /// file. Eventually all of the routines here will get folded back into /// opt.cpp. /// //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_OPT_NEWPMDRIVER_H #define LLVM_TOOLS_OPT_NEWPMDRIVER_H #include "llvm/ADT/StringRef.h" namespace llvm { class LLVMContext; class Module; class TargetMachine; class tool_output_file; namespace opt_tool { enum OutputKind { OK_NoOutput, OK_OutputAssembly, OK_OutputBitcode }; enum VerifierKind { VK_NoVerifier, VK_VerifyInAndOut, VK_VerifyEachPass }; } /// \brief Driver function to run the new pass manager over a module. /// /// This function only exists factored away from opt.cpp in order to prevent /// inclusion of the new pass manager headers and the old headers into the same /// file. It's interface is consequentially somewhat ad-hoc, but will go away /// when the transition finishes. bool runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M, TargetMachine *TM, tool_output_file *Out, StringRef PassPipeline, opt_tool::OutputKind OK, opt_tool::VerifierKind VK, bool ShouldPreserveAssemblyUseListOrder, bool ShouldPreserveBitcodeUseListOrder); } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/BreakpointPrinter.h
//===- BreakpointPrinter.h - Breakpoint location printer ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Breakpoint location printer. /// //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H #define LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H namespace llvm { class ModulePass; class raw_ostream; ModulePass *createBreakpointPrinter(raw_ostream &out); } #endif // LLVM_TOOLS_OPT_BREAKPOINTPRINTER_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/NewPMDriver.cpp
//===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// This file is just a split of the code that logically belongs in opt.cpp but /// that includes the new pass manager headers. /// //===----------------------------------------------------------------------===// #include "NewPMDriver.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/CGSCCPassManager.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/IR/Verifier.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; using namespace opt_tool; static cl::opt<bool> DebugPM("debug-pass-manager", cl::Hidden, cl::desc("Print pass management debugging information")); bool llvm::runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M, TargetMachine *TM, tool_output_file *Out, StringRef PassPipeline, OutputKind OK, VerifierKind VK, bool ShouldPreserveAssemblyUseListOrder, bool ShouldPreserveBitcodeUseListOrder) { PassBuilder PB(TM); FunctionAnalysisManager FAM(DebugPM); CGSCCAnalysisManager CGAM(DebugPM); ModuleAnalysisManager MAM(DebugPM); // Register all the basic analyses with the managers. PB.registerModuleAnalyses(MAM); PB.registerCGSCCAnalyses(CGAM); PB.registerFunctionAnalyses(FAM); // Cross register the analysis managers through their proxies. MAM.registerPass(FunctionAnalysisManagerModuleProxy(FAM)); MAM.registerPass(CGSCCAnalysisManagerModuleProxy(CGAM)); CGAM.registerPass(FunctionAnalysisManagerCGSCCProxy(FAM)); CGAM.registerPass(ModuleAnalysisManagerCGSCCProxy(MAM)); FAM.registerPass(CGSCCAnalysisManagerFunctionProxy(CGAM)); FAM.registerPass(ModuleAnalysisManagerFunctionProxy(MAM)); ModulePassManager MPM(DebugPM); if (VK > VK_NoVerifier) MPM.addPass(VerifierPass()); if (!PB.parsePassPipeline(MPM, PassPipeline, VK == VK_VerifyEachPass, DebugPM)) { errs() << Arg0 << ": unable to parse pass pipeline description.\n"; return false; } if (VK > VK_NoVerifier) MPM.addPass(VerifierPass()); // Add any relevant output pass at the end of the pipeline. switch (OK) { case OK_NoOutput: break; // No output pass needed. case OK_OutputAssembly: MPM.addPass( PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder)); break; case OK_OutputBitcode: MPM.addPass( BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder)); break; } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // Now that we have all of the passes ready, run them. MPM.run(M, &MAM); // Declare success. if (OK != OK_NoOutput) Out->keep(); return true; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Analysis BitWriter # CodeGen # HLSL Change Core DXIL # HLSL Change DxcBindingTable # HLSL Change HLSL # HLSL Change DxilContainer # HLSL Change for DxcOptimizerPass DxilRootSignature # HLSL Change for DxcOptimizerPass IPA IPO IRReader InstCombine # Instrumentation # HLSL Change Passes # HLSL Change # MC # HLSL Change # ObjCARCOpts # HLSL Change Passes PassPrinters # HLSL Change ScalarOpts Support Target TransformUtils Vectorize ) # Support plugins. set(LLVM_NO_DEAD_STRIP 1) set(LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS} mssupport dxcbindingtable hlsl) # HLSL Change add_llvm_tool(opt AnalysisWrappers.cpp BreakpointPrinter.cpp GraphPrinters.cpp NewPMDriver.cpp PrintSCC.cpp opt.cpp ) if(WIN32 AND HLSL_BUILD_DXILCONV) add_compile_definitions(HAS_DXILCONV) target_link_libraries(opt DxilConvPasses) add_dependencies(opt DxilConvPasses) endif(WIN32 AND HLSL_BUILD_DXILCONV) export_executable_symbols(opt) if(WITH_POLLY AND LINK_POLLY_INTO_TOOLS) target_link_libraries(opt Polly) if(POLLY_LINK_LIBS) foreach(lib ${POLLY_LINK_LIBS}) target_link_libraries(opt ${lib}) endforeach(lib) endif(POLLY_LINK_LIBS) endif(WITH_POLLY AND LINK_POLLY_INTO_TOOLS)
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/opt.cpp
//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Optimizations may be specified an arbitrary number of times on the command // line, They are run in the order specified. // //===----------------------------------------------------------------------===// #include "BreakpointPrinter.h" #include "NewPMDriver.h" #include "llvm/ADT/Triple.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/CallGraphSCCPass.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/RegionPass.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/LegacyPassNameParser.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/InitializePasses.h" #include "llvm/LinkAllIR.h" #include "llvm/LinkAllPasses.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/PassPrinters/PassPrinters.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SystemUtils.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Utils/Cloning.h" // HLSL Change Starts #include "dxc/HLSL/ComputeViewIdState.h" #include "dxc/HLSL/DxilGenerationPass.h" #include "dxc/Support/Global.h" #include "llvm/Analysis/ReducibilityAnalysis.h" #include "dxc/Support/WinIncludes.h" #include "llvm/Support/MSFileSystem.h" // HLSL Change Ends #include <algorithm> #include <memory> using namespace llvm; using namespace opt_tool; // The OptimizationList is automatically populated with registered Passes by the // PassNameParser. // static cl::list<const PassInfo*, bool, PassNameParser> PassList(cl::desc("Optimizations available:")); // This flag specifies a textual description of the optimization pass pipeline // to run over the module. This flag switches opt to use the new pass manager // infrastructure, completely disabling all of the flags specific to the old // pass management. static cl::opt<std::string> PassPipeline( "passes", cl::desc("A textual description of the pass pipeline for optimizing"), cl::Hidden); // Other command line options... // static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bitcode file>"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals")); static cl::opt<bool> PrintEachXForm("p", cl::desc("Print module after each transformation")); static cl::opt<bool> NoOutput("disable-output", cl::desc("Do not write result bitcode file"), cl::Hidden); static cl::opt<bool> OutputAssembly("S", cl::desc("Write output as LLVM assembly")); static cl::opt<bool> NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify after each transform")); static cl::opt<bool> StripDebug("strip-debug", cl::desc("Strip debugger symbol info from translation unit")); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); #if 0 // HLSL Change Starts: Disable LTO for DXIL static cl::opt<bool> StandardLinkOpts("std-link-opts", cl::desc("Include the standard link time optimizations")); #endif // HLSL Change Ends static cl::opt<bool> OptLevelO1("O1", cl::desc("Optimization level 1. Similar to clang -O1")); static cl::opt<bool> OptLevelO2("O2", cl::desc("Optimization level 2. Similar to clang -O2")); static cl::opt<bool> OptLevelOs("Os", cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); static cl::opt<bool> OptLevelOz("Oz", cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); static cl::opt<bool> OptLevelO3("O3", cl::desc("Optimization level 3. Similar to clang -O3")); static cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); static cl::opt<bool> UnitAtATime("funit-at-a-time", cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"), cl::init(true)); static cl::opt<bool> DisableLoopUnrolling("disable-loop-unrolling", cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false)); static cl::opt<bool> DisableLoopVectorization("disable-loop-vectorization", cl::desc("Disable the loop vectorization pass"), cl::init(false)); static cl::opt<bool> DisableSLPVectorization("disable-slp-vectorization", cl::desc("Disable the slp vectorization pass"), cl::init(false)); static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", cl::desc("Disable simplify-libcalls")); static cl::opt<bool> Quiet("q", cl::desc("Obsolete option"), cl::Hidden); static cl::alias QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); static cl::opt<bool> AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); static cl::opt<bool> PrintBreakpoints("print-breakpoints-for-testing", cl::desc("Print select breakpoints location for testing")); static cl::opt<std::string> DefaultDataLayout("default-data-layout", cl::desc("data layout string to use if not specified by module"), cl::value_desc("layout-string"), cl::init("")); static cl::opt<bool> PreserveBitcodeUseListOrder( "preserve-bc-uselistorder", cl::desc("Preserve use-list order when writing LLVM bitcode."), cl::init(true), cl::Hidden); static cl::opt<bool> PreserveAssemblyUseListOrder( "preserve-ll-uselistorder", cl::desc("Preserve use-list order when writing LLVM assembly."), cl::init(false), cl::Hidden); static cl::opt<bool> RunTwice("run-twice", cl::desc("Run all passes twice, re-using the same pass manager."), cl::init(false), cl::Hidden); static inline void addPass(legacy::PassManagerBase &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } /// This routine adds optimization passes based on selected optimization level, /// OptLevel. /// /// OptLevel - Optimization Level static void AddOptimizationPasses(legacy::PassManagerBase &MPM, legacy::FunctionPassManager &FPM, unsigned OptLevel, unsigned SizeLevel) { FPM.add(createVerifierPass()); // Verify that input is correct PassManagerBuilder Builder; Builder.OptLevel = OptLevel; Builder.SizeLevel = SizeLevel; if (DisableInline) { // No inlining pass } else if (OptLevel > 1) { Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel); } else { Builder.Inliner = createAlwaysInlinerPass(); } Builder.DisableUnitAtATime = !UnitAtATime; Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? DisableLoopUnrolling : OptLevel == 0; // This is final, unless there is a #pragma vectorize enable if (DisableLoopVectorization) Builder.LoopVectorize = false; // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) else if (!Builder.LoopVectorize) Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; // When #pragma vectorize is on for SLP, do the same as above Builder.SLPVectorize = DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2; Builder.populateFunctionPassManager(FPM); Builder.populateModulePassManager(MPM); } #if 0 // HLSL Change Starts: Disable LTO for DXIL static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { PassManagerBuilder Builder; Builder.VerifyInput = true; if (DisableOptimizations) Builder.OptLevel = 0; if (!DisableInline) Builder.Inliner = createFunctionInliningPass(); Builder.populateLTOPassManager(PM); } #endif // HLSL Change Ends //===----------------------------------------------------------------------===// // CodeGen-related helper functions. // static CodeGenOpt::Level GetCodeGenOptLevel() { if (OptLevelO1) return CodeGenOpt::Less; if (OptLevelO2) return CodeGenOpt::Default; if (OptLevelO3) return CodeGenOpt::Aggressive; return CodeGenOpt::None; } // Returns the TargetMachine instance or zero if no triple is provided. static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, StringRef FeaturesStr, const TargetOptions &Options) { std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, Error); // Some modules don't specify a triple, and this is okay. if (!TheTarget) { return nullptr; } return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RelocModel, CMModel, GetCodeGenOptLevel()); } #ifdef LINK_POLLY_INTO_TOOLS namespace polly { void initializePollyPasses(llvm::PassRegistry &Registry); } #endif // HLSL Change Start #ifdef HAS_DXILCONV void __cdecl initializeDxilConvPasses(llvm::PassRegistry &); #endif namespace hlsl { HRESULT SetupRegistryPassForHLSL(); } // namespace hlsl // HLSL Change End //===----------------------------------------------------------------------===// // main for opt // // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // HLSL Change Starts if (llvm::sys::fs::SetupPerThreadFileSystem()) return 1; llvm::sys::fs::AutoCleanupPerThreadFileSystem auto_cleanup_fs; if (FAILED(DxcInitThreadMalloc())) return 1; DxcSetThreadMallocToDefault(); llvm::sys::fs::MSFileSystem* msfPtr; if (FAILED(CreateMSFileSystemForDisk(&msfPtr))) return 1; std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr); llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); //llvm::STDStreamCloser stdStreamCloser; // HLSL Change Ends //sys::PrintStackTraceOnErrorSignal(); // HLSL Change //llvm::PrettyStackTraceProgram X(argc, argv); // HLSL Change // Enable debug stream buffering. EnableDebugBuffering = true; llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. LLVMContext &Context = getGlobalContext(); InitializeAllTargets(); // InitializeAllTargetMCs(); // HLSL Change: remove MC targets InitializeAllAsmPrinters(); // Initialize passes PassRegistry &Registry = *PassRegistry::getPassRegistry(); initializeCore(Registry); initializeScalarOpts(Registry); // initializeObjCARCOpts(Registry); // HLSL Change: remove ObjC ARC passes // initializeVectorization(Registry); // HLSL Change: remove vectorization passes initializeIPO(Registry); initializeAnalysis(Registry); initializeIPA(Registry); initializeTransformUtils(Registry); initializeInstCombine(Registry); // initializeInstrumentation(Registry); // HLSL Change: remove instrumentation initializeTarget(Registry); // For codegen passes, only passes that do IR to IR transformation are // supported. // initializeCodeGenPreparePass(Registry); // HLSL Change: remove EH passes //initializeAtomicExpandPass(Registry); // HLSL Change: remove EH passes initializeRewriteSymbolsPass(Registry); //initializeWinEHPreparePass(Registry); // HLSL Change: remove EH passes //initializeDwarfEHPreparePass(Registry); // HLSL Change: remove EH passes //initializeSjLjEHPreparePass(Registry); // HLSL Change: remove EH passes // HLSL Change Starts initializeDxilModuleInitPass(Registry); hlsl::SetupRegistryPassForHLSL(); #ifdef HAS_DXILCONV initializeDxilConvPasses(Registry); #endif initializeDxilRemoveUnstructuredLoopExitsPass(Registry); // HLSL Change Ends #ifdef LINK_POLLY_INTO_TOOLS polly::initializePollyPasses(Registry); #endif cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .bc modular optimizer and analysis printer\n"); if (AnalyzeOnly && NoOutput) { errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; return 1; } SMDiagnostic Err; // Load the input module... std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context); if (!M) { Err.print(argv[0], errs()); return 1; } // Strip debug info before running the verifier. if (StripDebug) StripDebugInfo(*M); // Immediately run the verifier to catch any problems before starting up the // pass pipelines. Otherwise we can crash on broken code during // doInitialization(). if (!NoVerify && verifyModule(*M, &errs())) { errs() << argv[0] << ": " << InputFilename << ": error: input module is broken!\n"; return 1; } // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) M->setTargetTriple(Triple::normalize(TargetTriple)); // Figure out what stream we are supposed to write to... std::unique_ptr<tool_output_file> Out; if (NoOutput) { if (!OutputFilename.empty()) errs() << "WARNING: The -o (output filename) option is ignored when\n" "the --disable-output option is used.\n"; } else { // Default to standard output. if (OutputFilename.empty()) OutputFilename = "-"; std::error_code EC; Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None)); if (EC) { errs() << EC.message() << '\n'; return 1; } } Triple ModuleTriple(M->getTargetTriple()); std::string CPUStr, FeaturesStr; TargetMachine *Machine = nullptr; const TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); if (ModuleTriple.getArch()) { CPUStr = getCPUStr(); FeaturesStr = getFeaturesStr(); Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); } std::unique_ptr<TargetMachine> TM(Machine); // Override function attributes based on CPUStr, FeaturesStr, and command line // flags. setFunctionAttributes(CPUStr, FeaturesStr, *M); // If the output is set to be emitted to standard out, and standard out is a // console, print out a warning message and refuse to do it. We don't // impress anyone by spewing tons of binary goo to a terminal. if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) NoOutput = true; if (PassPipeline.getNumOccurrences() > 0) { OutputKind OK = OK_NoOutput; if (!NoOutput) OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode; VerifierKind VK = VK_VerifyInAndOut; if (NoVerify) VK = VK_NoVerifier; else if (VerifyEach) VK = VK_VerifyEachPass; // The user has asked to use the new pass manager and provided a pipeline // string. Hand off the rest of the functionality to the new code for that // layer. return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(), PassPipeline, OK, VK, PreserveAssemblyUseListOrder, PreserveBitcodeUseListOrder) ? 0 : 1; } // Create a PassManager to hold and optimize the collection of passes we are // about to build. // legacy::PassManager Passes; // Add an appropriate TargetLibraryInfo pass for the module's triple. TargetLibraryInfoImpl TLII(ModuleTriple); // The -disable-simplify-libcalls flag actually disables all builtin optzns. if (DisableSimplifyLibCalls) TLII.disableAllFunctions(); Passes.add(new TargetLibraryInfoWrapperPass(TLII)); // Add an appropriate DataLayout instance for this module. const DataLayout &DL = M->getDataLayout(); if (DL.isDefault() && !DefaultDataLayout.empty()) { M->setDataLayout(DefaultDataLayout); } // Add internal analysis passes from the target machine. Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); std::unique_ptr<legacy::FunctionPassManager> FPasses; if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { FPasses.reset(new legacy::FunctionPassManager(M.get())); FPasses->add(createTargetTransformInfoWrapperPass( TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); } if (PrintBreakpoints) { // Default to standard output. if (!Out) { if (OutputFilename.empty()) OutputFilename = "-"; std::error_code EC; Out = llvm::make_unique<tool_output_file>(OutputFilename, EC, sys::fs::F_None); if (EC) { errs() << EC.message() << '\n'; return 1; } } Passes.add(createBreakpointPrinter(Out->os())); NoOutput = true; } // Create a new optimization pass for each one specified on the command line for (unsigned i = 0; i < PassList.size(); ++i) { #if 0 // HLSL Change Starts: Disable LTO for DXIL if (StandardLinkOpts && StandardLinkOpts.getPosition() < PassList.getPosition(i)) { AddStandardLinkPasses(Passes); StandardLinkOpts = false; } #endif // HLSL Change Ends if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 1, 0); OptLevelO1 = false; } if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 0); OptLevelO2 = false; } if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 1); OptLevelOs = false; } if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 2, 2); OptLevelOz = false; } if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { AddOptimizationPasses(Passes, *FPasses, 3, 0); OptLevelO3 = false; } const PassInfo *PassInf = PassList[i]; Pass *P = nullptr; if (PassInf->getTargetMachineCtor()) P = PassInf->getTargetMachineCtor()(TM.get()); else if (PassInf->getNormalCtor()) P = PassInf->getNormalCtor()(); else errs() << argv[0] << ": cannot create pass: " << PassInf->getPassName() << "\n"; if (P) { PassKind Kind = P->getPassKind(); addPass(Passes, P); if (AnalyzeOnly) { switch (Kind) { case PT_BasicBlock: Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet)); break; case PT_Region: Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); break; case PT_Loop: Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); break; case PT_Function: Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); break; case PT_CallGraphSCC: Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); break; default: Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); break; } } } if (PrintEachXForm) Passes.add( createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); } #if 0 // HLSL Change Starts: Disable LTO for DXIL if (StandardLinkOpts) { AddStandardLinkPasses(Passes); StandardLinkOpts = false; } #endif // HLSL Change Ends if (OptLevelO1) AddOptimizationPasses(Passes, *FPasses, 1, 0); if (OptLevelO2) AddOptimizationPasses(Passes, *FPasses, 2, 0); if (OptLevelOs) AddOptimizationPasses(Passes, *FPasses, 2, 1); if (OptLevelOz) AddOptimizationPasses(Passes, *FPasses, 2, 2); if (OptLevelO3) AddOptimizationPasses(Passes, *FPasses, 3, 0); if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { FPasses->doInitialization(); for (Function &F : *M) FPasses->run(F); FPasses->doFinalization(); } // Check that the module is well formed on completion of optimization if (!NoVerify && !VerifyEach) Passes.add(createVerifierPass()); // In run twice mode, we want to make sure the output is bit-by-bit // equivalent if we run the pass manager again, so setup two buffers and // a stream to write to them. Note that llc does something similar and it // may be worth to abstract this out in the future. SmallVector<char, 0> Buffer; SmallVector<char, 0> CompileTwiceBuffer; std::unique_ptr<raw_svector_ostream> BOS; raw_ostream *OS = nullptr; // Write bitcode or assembly to the output as the last step... if (!NoOutput && !AnalyzeOnly) { assert(Out); OS = &Out->os(); if (RunTwice) { BOS = make_unique<raw_svector_ostream>(Buffer); OS = BOS.get(); } if (OutputAssembly) Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); else Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder)); } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // Now that we have all of the passes ready, run them. // HLSL Change Starts - wrap in try-catch try { Passes.run(*M); } catch(...) { exit(1); } // HLSL Change Ends // If requested, run all passes again with the same pass manager to catch // bugs caused by persistent state in the passes if (RunTwice) { assert(Out); CompileTwiceBuffer = Buffer; Buffer.clear(); std::unique_ptr<Module> M2(CloneModule(M.get())); Passes.run(*M2); if (Buffer.size() != CompileTwiceBuffer.size() || (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 0)) { errs() << "Running the pass manager twice changed the output.\n" "Writing the result of the second run to the specified output." "To generate the one-run comparison binary, just run without\n" "the compile-twice option\n"; Out->os() << BOS->str(); Out->keep(); return 1; } Out->os() << BOS->str(); } // Declare success. if (!NoOutput || PrintBreakpoints) Out->keep(); return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/LLVMBuild.txt
;===- ./tools/opt/LLVMBuild.txt --------------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = opt parent = Tools required_libraries = AsmParser BitReader BitWriter HLSL DxcBindingTable IRReader IPO Scalar Passes PassPrinters all-targets ; CodeGen - HLSL Change ; Instrumentation - HLSL Change ; ObjCARC - HLSL Change ; DXIL - HLSL Change ; HLSL - HLSL Change ; PassPrinters - HLSL Change
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/opt/AnalysisWrappers.cpp
//===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines pass wrappers around LLVM analyses that don't make sense to // be passes. It provides a nice standard pass interface to these classes so // that they can be printed out by analyze. // // These classes are separated out of analyze.cpp so that it is more clear which // code is the integral part of the analyze tool, and which part of the code is // just making it so more passes are available. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/CallGraph.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { /// ExternalFunctionsPassedConstants - This pass prints out call sites to /// external functions that are called with constant arguments. This can be /// useful when looking for standard library functions we should constant fold /// or handle in alias analyses. struct ExternalFunctionsPassedConstants : public ModulePass { static char ID; // Pass ID, replacement for typeid ExternalFunctionsPassedConstants() : ModulePass(ID) {} bool runOnModule(Module &M) override { for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { if (!I->isDeclaration()) continue; bool PrintedFn = false; for (User *U : I->users()) { Instruction *UI = dyn_cast<Instruction>(U); if (!UI) continue; CallSite CS(cast<Value>(UI)); if (!CS) continue; for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); AI != E; ++AI) { if (!isa<Constant>(*AI)) continue; if (!PrintedFn) { errs() << "Function '" << I->getName() << "':\n"; PrintedFn = true; } errs() << *UI; break; } } } return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } }; } char ExternalFunctionsPassedConstants::ID = 0; static RegisterPass<ExternalFunctionsPassedConstants> P1("print-externalfnconstants", "Print external fn callsites passed constants"); namespace { struct CallGraphPrinter : public ModulePass { static char ID; // Pass ID, replacement for typeid CallGraphPrinter() : ModulePass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequiredTransitive<CallGraphWrapperPass>(); } bool runOnModule(Module &M) override { getAnalysis<CallGraphWrapperPass>().print(errs(), &M); return false; } }; } char CallGraphPrinter::ID = 0; static RegisterPass<CallGraphPrinter> P2("print-callgraph", "Print a call graph");
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/obj2yaml.cpp
//===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Error.h" #include "obj2yaml.h" #include "llvm/Object/Archive.h" #include "llvm/Object/COFF.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" using namespace llvm; using namespace llvm::object; static std::error_code dumpObject(const ObjectFile &Obj) { if (Obj.isCOFF()) return coff2yaml(outs(), cast<COFFObjectFile>(Obj)); if (Obj.isELF()) return elf2yaml(outs(), Obj); return obj2yaml_error::unsupported_obj_file_format; } static std::error_code dumpInput(StringRef File) { if (File != "-" && !sys::fs::exists(File)) return obj2yaml_error::file_not_found; ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File); if (std::error_code EC = BinaryOrErr.getError()) return EC; Binary &Binary = *BinaryOrErr.get().getBinary(); // TODO: If this is an archive, then burst it and dump each entry if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) return dumpObject(*Obj); return obj2yaml_error::unrecognized_file_format; } cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char *argv[]) { cl::ParseCommandLineOptions(argc, argv); sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. if (std::error_code EC = dumpInput(InputFilename)) { errs() << "Error: '" << EC.message() << "'\n"; return 1; } return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/Error.cpp
//===- Error.cpp - system_error extensions for obj2yaml ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Error.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class _obj2yaml_error_category : public std::error_category { public: const char *name() const LLVM_NOEXCEPT override; std::string message(int ev) const override; }; } // namespace const char *_obj2yaml_error_category::name() const LLVM_NOEXCEPT { return "obj2yaml"; } std::string _obj2yaml_error_category::message(int ev) const { switch (static_cast<obj2yaml_error>(ev)) { case obj2yaml_error::success: return "Success"; case obj2yaml_error::file_not_found: return "No such file."; case obj2yaml_error::unrecognized_file_format: return "Unrecognized file type."; case obj2yaml_error::unsupported_obj_file_format: return "Unsupported object file format."; } llvm_unreachable("An enumerator of obj2yaml_error does not have a message " "defined."); } namespace llvm { const std::error_category &obj2yaml_category() { static _obj2yaml_error_category o; return o; } } // namespace llvm
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Object Support ) add_llvm_tool(obj2yaml obj2yaml.cpp coff2yaml.cpp elf2yaml.cpp Error.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/obj2yaml.h
//===------ utils/obj2yaml.hpp - obj2yaml conversion tool -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // This file declares some helper routines, and also the format-specific // writers. To add a new format, add the declaration here, and, in a separate // source file, implement it. //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_OBJ2YAML_OBJ2YAML_H #define LLVM_TOOLS_OBJ2YAML_OBJ2YAML_H #include "llvm/Object/COFF.h" #include "llvm/Support/raw_ostream.h" #include <system_error> std::error_code coff2yaml(llvm::raw_ostream &Out, const llvm::object::COFFObjectFile &Obj); std::error_code elf2yaml(llvm::raw_ostream &Out, const llvm::object::ObjectFile &Obj); #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/coff2yaml.cpp
//===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "obj2yaml.h" #include "llvm/Object/COFF.h" #include "llvm/Object/COFFYAML.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/YAMLTraits.h" using namespace llvm; namespace { class COFFDumper { const object::COFFObjectFile &Obj; COFFYAML::Object YAMLObj; template <typename T> void dumpOptionalHeader(T OptionalHeader); void dumpHeader(); void dumpSections(unsigned numSections); void dumpSymbols(unsigned numSymbols); public: COFFDumper(const object::COFFObjectFile &Obj); COFFYAML::Object &getYAMLObj(); }; } COFFDumper::COFFDumper(const object::COFFObjectFile &Obj) : Obj(Obj) { const object::pe32_header *PE32Header = nullptr; Obj.getPE32Header(PE32Header); if (PE32Header) { dumpOptionalHeader(PE32Header); } else { const object::pe32plus_header *PE32PlusHeader = nullptr; Obj.getPE32PlusHeader(PE32PlusHeader); if (PE32PlusHeader) { dumpOptionalHeader(PE32PlusHeader); } } dumpHeader(); dumpSections(Obj.getNumberOfSections()); dumpSymbols(Obj.getNumberOfSymbols()); } template <typename T> void COFFDumper::dumpOptionalHeader(T OptionalHeader) { YAMLObj.OptionalHeader = COFFYAML::PEHeader(); YAMLObj.OptionalHeader->Header.AddressOfEntryPoint = OptionalHeader->AddressOfEntryPoint; YAMLObj.OptionalHeader->Header.AddressOfEntryPoint = OptionalHeader->AddressOfEntryPoint; YAMLObj.OptionalHeader->Header.ImageBase = OptionalHeader->ImageBase; YAMLObj.OptionalHeader->Header.SectionAlignment = OptionalHeader->SectionAlignment; YAMLObj.OptionalHeader->Header.FileAlignment = OptionalHeader->FileAlignment; YAMLObj.OptionalHeader->Header.MajorOperatingSystemVersion = OptionalHeader->MajorOperatingSystemVersion; YAMLObj.OptionalHeader->Header.MinorOperatingSystemVersion = OptionalHeader->MinorOperatingSystemVersion; YAMLObj.OptionalHeader->Header.MajorImageVersion = OptionalHeader->MajorImageVersion; YAMLObj.OptionalHeader->Header.MinorImageVersion = OptionalHeader->MinorImageVersion; YAMLObj.OptionalHeader->Header.MajorSubsystemVersion = OptionalHeader->MajorSubsystemVersion; YAMLObj.OptionalHeader->Header.MinorSubsystemVersion = OptionalHeader->MinorSubsystemVersion; YAMLObj.OptionalHeader->Header.Subsystem = OptionalHeader->Subsystem; YAMLObj.OptionalHeader->Header.DLLCharacteristics = OptionalHeader->DLLCharacteristics; YAMLObj.OptionalHeader->Header.SizeOfStackReserve = OptionalHeader->SizeOfStackReserve; YAMLObj.OptionalHeader->Header.SizeOfStackCommit = OptionalHeader->SizeOfStackCommit; YAMLObj.OptionalHeader->Header.SizeOfHeapReserve = OptionalHeader->SizeOfHeapReserve; YAMLObj.OptionalHeader->Header.SizeOfHeapCommit = OptionalHeader->SizeOfHeapCommit; unsigned I = 0; for (auto &DestDD : YAMLObj.OptionalHeader->DataDirectories) { const object::data_directory *DD; if (Obj.getDataDirectory(I++, DD)) continue; DestDD = COFF::DataDirectory(); DestDD->RelativeVirtualAddress = DD->RelativeVirtualAddress; DestDD->Size = DD->Size; } } void COFFDumper::dumpHeader() { YAMLObj.Header.Machine = Obj.getMachine(); YAMLObj.Header.Characteristics = Obj.getCharacteristics(); } void COFFDumper::dumpSections(unsigned NumSections) { std::vector<COFFYAML::Section> &YAMLSections = YAMLObj.Sections; for (const auto &ObjSection : Obj.sections()) { const object::coff_section *COFFSection = Obj.getCOFFSection(ObjSection); COFFYAML::Section NewYAMLSection; ObjSection.getName(NewYAMLSection.Name); NewYAMLSection.Header.Characteristics = COFFSection->Characteristics; NewYAMLSection.Header.VirtualAddress = ObjSection.getAddress(); NewYAMLSection.Header.VirtualSize = COFFSection->VirtualSize; NewYAMLSection.Alignment = ObjSection.getAlignment(); ArrayRef<uint8_t> sectionData; if (!ObjSection.isBSS()) Obj.getSectionContents(COFFSection, sectionData); NewYAMLSection.SectionData = yaml::BinaryRef(sectionData); std::vector<COFFYAML::Relocation> Relocations; for (const auto &Reloc : ObjSection.relocations()) { const object::coff_relocation *reloc = Obj.getCOFFRelocation(Reloc); COFFYAML::Relocation Rel; object::symbol_iterator Sym = Reloc.getSymbol(); ErrorOr<StringRef> SymbolNameOrErr = Sym->getName(); if (std::error_code EC = SymbolNameOrErr.getError()) report_fatal_error(EC.message()); Rel.SymbolName = *SymbolNameOrErr; Rel.VirtualAddress = reloc->VirtualAddress; Rel.Type = reloc->Type; Relocations.push_back(Rel); } NewYAMLSection.Relocations = Relocations; YAMLSections.push_back(NewYAMLSection); } } static void dumpFunctionDefinition(COFFYAML::Symbol *Sym, const object::coff_aux_function_definition *ObjFD) { COFF::AuxiliaryFunctionDefinition YAMLFD; YAMLFD.TagIndex = ObjFD->TagIndex; YAMLFD.TotalSize = ObjFD->TotalSize; YAMLFD.PointerToLinenumber = ObjFD->PointerToLinenumber; YAMLFD.PointerToNextFunction = ObjFD->PointerToNextFunction; Sym->FunctionDefinition = YAMLFD; } static void dumpbfAndEfLineInfo(COFFYAML::Symbol *Sym, const object::coff_aux_bf_and_ef_symbol *ObjBES) { COFF::AuxiliarybfAndefSymbol YAMLAAS; YAMLAAS.Linenumber = ObjBES->Linenumber; YAMLAAS.PointerToNextFunction = ObjBES->PointerToNextFunction; Sym->bfAndefSymbol = YAMLAAS; } static void dumpWeakExternal(COFFYAML::Symbol *Sym, const object::coff_aux_weak_external *ObjWE) { COFF::AuxiliaryWeakExternal YAMLWE; YAMLWE.TagIndex = ObjWE->TagIndex; YAMLWE.Characteristics = ObjWE->Characteristics; Sym->WeakExternal = YAMLWE; } static void dumpSectionDefinition(COFFYAML::Symbol *Sym, const object::coff_aux_section_definition *ObjSD, bool IsBigObj) { COFF::AuxiliarySectionDefinition YAMLASD; int32_t AuxNumber = ObjSD->getNumber(IsBigObj); YAMLASD.Length = ObjSD->Length; YAMLASD.NumberOfRelocations = ObjSD->NumberOfRelocations; YAMLASD.NumberOfLinenumbers = ObjSD->NumberOfLinenumbers; YAMLASD.CheckSum = ObjSD->CheckSum; YAMLASD.Number = AuxNumber; YAMLASD.Selection = ObjSD->Selection; Sym->SectionDefinition = YAMLASD; } static void dumpCLRTokenDefinition(COFFYAML::Symbol *Sym, const object::coff_aux_clr_token *ObjCLRToken) { COFF::AuxiliaryCLRToken YAMLCLRToken; YAMLCLRToken.AuxType = ObjCLRToken->AuxType; YAMLCLRToken.SymbolTableIndex = ObjCLRToken->SymbolTableIndex; Sym->CLRToken = YAMLCLRToken; } void COFFDumper::dumpSymbols(unsigned NumSymbols) { std::vector<COFFYAML::Symbol> &Symbols = YAMLObj.Symbols; for (const auto &S : Obj.symbols()) { object::COFFSymbolRef Symbol = Obj.getCOFFSymbol(S); COFFYAML::Symbol Sym; Obj.getSymbolName(Symbol, Sym.Name); Sym.SimpleType = COFF::SymbolBaseType(Symbol.getBaseType()); Sym.ComplexType = COFF::SymbolComplexType(Symbol.getComplexType()); Sym.Header.StorageClass = Symbol.getStorageClass(); Sym.Header.Value = Symbol.getValue(); Sym.Header.SectionNumber = Symbol.getSectionNumber(); Sym.Header.NumberOfAuxSymbols = Symbol.getNumberOfAuxSymbols(); if (Symbol.getNumberOfAuxSymbols() > 0) { ArrayRef<uint8_t> AuxData = Obj.getSymbolAuxData(Symbol); if (Symbol.isFunctionDefinition()) { // This symbol represents a function definition. assert(Symbol.getNumberOfAuxSymbols() == 1 && "Expected a single aux symbol to describe this function!"); const object::coff_aux_function_definition *ObjFD = reinterpret_cast<const object::coff_aux_function_definition *>( AuxData.data()); dumpFunctionDefinition(&Sym, ObjFD); } else if (Symbol.isFunctionLineInfo()) { // This symbol describes function line number information. assert(Symbol.getNumberOfAuxSymbols() == 1 && "Expected a single aux symbol to describe this function!"); const object::coff_aux_bf_and_ef_symbol *ObjBES = reinterpret_cast<const object::coff_aux_bf_and_ef_symbol *>( AuxData.data()); dumpbfAndEfLineInfo(&Sym, ObjBES); } else if (Symbol.isAnyUndefined()) { // This symbol represents a weak external definition. assert(Symbol.getNumberOfAuxSymbols() == 1 && "Expected a single aux symbol to describe this weak symbol!"); const object::coff_aux_weak_external *ObjWE = reinterpret_cast<const object::coff_aux_weak_external *>( AuxData.data()); dumpWeakExternal(&Sym, ObjWE); } else if (Symbol.isFileRecord()) { // This symbol represents a file record. Sym.File = StringRef(reinterpret_cast<const char *>(AuxData.data()), Symbol.getNumberOfAuxSymbols() * Obj.getSymbolTableEntrySize()) .rtrim(StringRef("\0", /*length=*/1)); } else if (Symbol.isSectionDefinition()) { // This symbol represents a section definition. assert(Symbol.getNumberOfAuxSymbols() == 1 && "Expected a single aux symbol to describe this section!"); const object::coff_aux_section_definition *ObjSD = reinterpret_cast<const object::coff_aux_section_definition *>( AuxData.data()); dumpSectionDefinition(&Sym, ObjSD, Symbol.isBigObj()); } else if (Symbol.isCLRToken()) { // This symbol represents a CLR token definition. assert(Symbol.getNumberOfAuxSymbols() == 1 && "Expected a single aux symbol to describe this CLR Token!"); const object::coff_aux_clr_token *ObjCLRToken = reinterpret_cast<const object::coff_aux_clr_token *>( AuxData.data()); dumpCLRTokenDefinition(&Sym, ObjCLRToken); } else { llvm_unreachable("Unhandled auxiliary symbol!"); } } Symbols.push_back(Sym); } } COFFYAML::Object &COFFDumper::getYAMLObj() { return YAMLObj; } std::error_code coff2yaml(raw_ostream &Out, const object::COFFObjectFile &Obj) { COFFDumper Dumper(Obj); yaml::Output Yout(Out); Yout << Dumper.getYAMLObj(); return std::error_code(); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/Error.h
//===- Error.h - system_error extensions for obj2yaml -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_OBJ2YAML_ERROR_H #define LLVM_TOOLS_OBJ2YAML_ERROR_H #include <system_error> namespace llvm { const std::error_category &obj2yaml_category(); enum class obj2yaml_error { success = 0, file_not_found, unrecognized_file_format, unsupported_obj_file_format }; inline std::error_code make_error_code(obj2yaml_error e) { return std::error_code(static_cast<int>(e), obj2yaml_category()); } } // namespace llvm namespace std { template <> struct is_error_code_enum<llvm::obj2yaml_error> : std::true_type {}; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/obj2yaml/elf2yaml.cpp
//===------ utils/elf2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Error.h" #include "obj2yaml.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ELFYAML.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/YAMLTraits.h" using namespace llvm; namespace { template <class ELFT> class ELFDumper { typedef object::Elf_Sym_Impl<ELFT> Elf_Sym; typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr; typedef typename object::ELFFile<ELFT>::Elf_Word Elf_Word; const object::ELFFile<ELFT> &Obj; std::error_code dumpSymbol(const Elf_Sym *Sym, bool IsDynamic, ELFYAML::Symbol &S); std::error_code dumpCommonSection(const Elf_Shdr *Shdr, ELFYAML::Section &S); std::error_code dumpCommonRelocationSection(const Elf_Shdr *Shdr, ELFYAML::RelocationSection &S); template <class RelT> std::error_code dumpRelocation(const Elf_Shdr *Shdr, const RelT *Rel, ELFYAML::Relocation &R); ErrorOr<ELFYAML::RelocationSection *> dumpRelSection(const Elf_Shdr *Shdr); ErrorOr<ELFYAML::RelocationSection *> dumpRelaSection(const Elf_Shdr *Shdr); ErrorOr<ELFYAML::RawContentSection *> dumpContentSection(const Elf_Shdr *Shdr); ErrorOr<ELFYAML::NoBitsSection *> dumpNoBitsSection(const Elf_Shdr *Shdr); ErrorOr<ELFYAML::Group *> dumpGroup(const Elf_Shdr *Shdr); ErrorOr<ELFYAML::MipsABIFlags *> dumpMipsABIFlags(const Elf_Shdr *Shdr); public: ELFDumper(const object::ELFFile<ELFT> &O); ErrorOr<ELFYAML::Object *> dump(); }; } template <class ELFT> ELFDumper<ELFT>::ELFDumper(const object::ELFFile<ELFT> &O) : Obj(O) {} template <class ELFT> ErrorOr<ELFYAML::Object *> ELFDumper<ELFT>::dump() { auto Y = make_unique<ELFYAML::Object>(); // Dump header Y->Header.Class = ELFYAML::ELF_ELFCLASS(Obj.getHeader()->getFileClass()); Y->Header.Data = ELFYAML::ELF_ELFDATA(Obj.getHeader()->getDataEncoding()); Y->Header.OSABI = Obj.getHeader()->e_ident[ELF::EI_OSABI]; Y->Header.Type = Obj.getHeader()->e_type; Y->Header.Machine = Obj.getHeader()->e_machine; Y->Header.Flags = Obj.getHeader()->e_flags; Y->Header.Entry = Obj.getHeader()->e_entry; // Dump sections for (const Elf_Shdr &Sec : Obj.sections()) { switch (Sec.sh_type) { case ELF::SHT_NULL: case ELF::SHT_SYMTAB: case ELF::SHT_DYNSYM: case ELF::SHT_STRTAB: // Do not dump these sections. break; case ELF::SHT_RELA: { ErrorOr<ELFYAML::RelocationSection *> S = dumpRelaSection(&Sec); if (std::error_code EC = S.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(S.get())); break; } case ELF::SHT_REL: { ErrorOr<ELFYAML::RelocationSection *> S = dumpRelSection(&Sec); if (std::error_code EC = S.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(S.get())); break; } case ELF::SHT_GROUP: { ErrorOr<ELFYAML::Group *> G = dumpGroup(&Sec); if (std::error_code EC = G.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(G.get())); break; } case ELF::SHT_MIPS_ABIFLAGS: { ErrorOr<ELFYAML::MipsABIFlags *> G = dumpMipsABIFlags(&Sec); if (std::error_code EC = G.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(G.get())); break; } case ELF::SHT_NOBITS: { ErrorOr<ELFYAML::NoBitsSection *> S = dumpNoBitsSection(&Sec); if (std::error_code EC = S.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(S.get())); break; } default: { ErrorOr<ELFYAML::RawContentSection *> S = dumpContentSection(&Sec); if (std::error_code EC = S.getError()) return EC; Y->Sections.push_back(std::unique_ptr<ELFYAML::Section>(S.get())); } } } // Dump symbols bool IsFirstSym = true; for (auto SI = Obj.symbol_begin(), SE = Obj.symbol_end(); SI != SE; ++SI) { if (IsFirstSym) { IsFirstSym = false; continue; } ELFYAML::Symbol S; if (std::error_code EC = ELFDumper<ELFT>::dumpSymbol(SI, false, S)) return EC; switch (SI->getBinding()) { case ELF::STB_LOCAL: Y->Symbols.Local.push_back(S); break; case ELF::STB_GLOBAL: Y->Symbols.Global.push_back(S); break; case ELF::STB_WEAK: Y->Symbols.Weak.push_back(S); break; default: llvm_unreachable("Unknown ELF symbol binding"); } } return Y.release(); } template <class ELFT> std::error_code ELFDumper<ELFT>::dumpSymbol(const Elf_Sym *Sym, bool IsDynamic, ELFYAML::Symbol &S) { S.Type = Sym->getType(); S.Value = Sym->st_value; S.Size = Sym->st_size; S.Other = Sym->st_other; ErrorOr<StringRef> NameOrErr = Obj.getSymbolName(Sym, IsDynamic); if (std::error_code EC = NameOrErr.getError()) return EC; S.Name = NameOrErr.get(); ErrorOr<const Elf_Shdr *> ShdrOrErr = Obj.getSection(&*Sym); if (std::error_code EC = ShdrOrErr.getError()) return EC; const Elf_Shdr *Shdr = *ShdrOrErr; if (!Shdr) return obj2yaml_error::success; NameOrErr = Obj.getSectionName(Shdr); if (std::error_code EC = NameOrErr.getError()) return EC; S.Section = NameOrErr.get(); return obj2yaml_error::success; } template <class ELFT> template <class RelT> std::error_code ELFDumper<ELFT>::dumpRelocation(const Elf_Shdr *Shdr, const RelT *Rel, ELFYAML::Relocation &R) { R.Type = Rel->getType(Obj.isMips64EL()); R.Offset = Rel->r_offset; R.Addend = 0; auto NamePair = Obj.getRelocationSymbol(Shdr, Rel); if (!NamePair.first) return obj2yaml_error::success; const Elf_Shdr *SymTab = NamePair.first; ErrorOr<const Elf_Shdr *> StrTabSec = Obj.getSection(SymTab->sh_link); if (std::error_code EC = StrTabSec.getError()) return EC; ErrorOr<StringRef> StrTabOrErr = Obj.getStringTable(*StrTabSec); if (std::error_code EC = StrTabOrErr.getError()) return EC; StringRef StrTab = *StrTabOrErr; ErrorOr<StringRef> NameOrErr = NamePair.second->getName(StrTab); if (std::error_code EC = NameOrErr.getError()) return EC; R.Symbol = NameOrErr.get(); return obj2yaml_error::success; } template <class ELFT> std::error_code ELFDumper<ELFT>::dumpCommonSection(const Elf_Shdr *Shdr, ELFYAML::Section &S) { S.Type = Shdr->sh_type; S.Flags = Shdr->sh_flags; S.Address = Shdr->sh_addr; S.AddressAlign = Shdr->sh_addralign; ErrorOr<StringRef> NameOrErr = Obj.getSectionName(Shdr); if (std::error_code EC = NameOrErr.getError()) return EC; S.Name = NameOrErr.get(); if (Shdr->sh_link != ELF::SHN_UNDEF) { ErrorOr<const Elf_Shdr *> LinkSection = Obj.getSection(Shdr->sh_link); if (std::error_code EC = LinkSection.getError()) return EC; NameOrErr = Obj.getSectionName(*LinkSection); if (std::error_code EC = NameOrErr.getError()) return EC; S.Link = NameOrErr.get(); } return obj2yaml_error::success; } template <class ELFT> std::error_code ELFDumper<ELFT>::dumpCommonRelocationSection(const Elf_Shdr *Shdr, ELFYAML::RelocationSection &S) { if (std::error_code EC = dumpCommonSection(Shdr, S)) return EC; ErrorOr<const Elf_Shdr *> InfoSection = Obj.getSection(Shdr->sh_info); if (std::error_code EC = InfoSection.getError()) return EC; ErrorOr<StringRef> NameOrErr = Obj.getSectionName(*InfoSection); if (std::error_code EC = NameOrErr.getError()) return EC; S.Info = NameOrErr.get(); return obj2yaml_error::success; } template <class ELFT> ErrorOr<ELFYAML::RelocationSection *> ELFDumper<ELFT>::dumpRelSection(const Elf_Shdr *Shdr) { assert(Shdr->sh_type == ELF::SHT_REL && "Section type is not SHT_REL"); auto S = make_unique<ELFYAML::RelocationSection>(); if (std::error_code EC = dumpCommonRelocationSection(Shdr, *S)) return EC; for (auto RI = Obj.rel_begin(Shdr), RE = Obj.rel_end(Shdr); RI != RE; ++RI) { ELFYAML::Relocation R; if (std::error_code EC = dumpRelocation(Shdr, &*RI, R)) return EC; S->Relocations.push_back(R); } return S.release(); } template <class ELFT> ErrorOr<ELFYAML::RelocationSection *> ELFDumper<ELFT>::dumpRelaSection(const Elf_Shdr *Shdr) { assert(Shdr->sh_type == ELF::SHT_RELA && "Section type is not SHT_RELA"); auto S = make_unique<ELFYAML::RelocationSection>(); if (std::error_code EC = dumpCommonRelocationSection(Shdr, *S)) return EC; for (auto RI = Obj.rela_begin(Shdr), RE = Obj.rela_end(Shdr); RI != RE; ++RI) { ELFYAML::Relocation R; if (std::error_code EC = dumpRelocation(Shdr, &*RI, R)) return EC; R.Addend = RI->r_addend; S->Relocations.push_back(R); } return S.release(); } template <class ELFT> ErrorOr<ELFYAML::RawContentSection *> ELFDumper<ELFT>::dumpContentSection(const Elf_Shdr *Shdr) { auto S = make_unique<ELFYAML::RawContentSection>(); if (std::error_code EC = dumpCommonSection(Shdr, *S)) return EC; ErrorOr<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(Shdr); if (std::error_code EC = ContentOrErr.getError()) return EC; S->Content = yaml::BinaryRef(ContentOrErr.get()); S->Size = S->Content.binary_size(); return S.release(); } template <class ELFT> ErrorOr<ELFYAML::NoBitsSection *> ELFDumper<ELFT>::dumpNoBitsSection(const Elf_Shdr *Shdr) { auto S = make_unique<ELFYAML::NoBitsSection>(); if (std::error_code EC = dumpCommonSection(Shdr, *S)) return EC; S->Size = Shdr->sh_size; return S.release(); } template <class ELFT> ErrorOr<ELFYAML::Group *> ELFDumper<ELFT>::dumpGroup(const Elf_Shdr *Shdr) { auto S = make_unique<ELFYAML::Group>(); if (std::error_code EC = dumpCommonSection(Shdr, *S)) return EC; // Get sh_info which is the signature. const Elf_Sym *symbol = Obj.getSymbol(Shdr->sh_info); ErrorOr<const Elf_Shdr *> Symtab = Obj.getSection(Shdr->sh_link); if (std::error_code EC = Symtab.getError()) return EC; ErrorOr<const Elf_Shdr *> StrTabSec = Obj.getSection((*Symtab)->sh_link); if (std::error_code EC = StrTabSec.getError()) return EC; ErrorOr<StringRef> StrTabOrErr = Obj.getStringTable(*StrTabSec); if (std::error_code EC = StrTabOrErr.getError()) return EC; StringRef StrTab = *StrTabOrErr; auto sectionContents = Obj.getSectionContents(Shdr); if (std::error_code ec = sectionContents.getError()) return ec; ErrorOr<StringRef> symbolName = symbol->getName(StrTab); if (std::error_code EC = symbolName.getError()) return EC; S->Info = *symbolName; const Elf_Word *groupMembers = reinterpret_cast<const Elf_Word *>(sectionContents->data()); const long count = (Shdr->sh_size) / sizeof(Elf_Word); ELFYAML::SectionOrType s; for (int i = 0; i < count; i++) { if (groupMembers[i] == llvm::ELF::GRP_COMDAT) { s.sectionNameOrType = "GRP_COMDAT"; } else { ErrorOr<const Elf_Shdr *> sHdr = Obj.getSection(groupMembers[i]); if (std::error_code EC = sHdr.getError()) return EC; ErrorOr<StringRef> sectionName = Obj.getSectionName(*sHdr); if (std::error_code ec = sectionName.getError()) return ec; s.sectionNameOrType = *sectionName; } S->Members.push_back(s); } return S.release(); } template <class ELFT> ErrorOr<ELFYAML::MipsABIFlags *> ELFDumper<ELFT>::dumpMipsABIFlags(const Elf_Shdr *Shdr) { assert(Shdr->sh_type == ELF::SHT_MIPS_ABIFLAGS && "Section type is not SHT_MIPS_ABIFLAGS"); auto S = make_unique<ELFYAML::MipsABIFlags>(); if (std::error_code EC = dumpCommonSection(Shdr, *S)) return EC; ErrorOr<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(Shdr); if (std::error_code EC = ContentOrErr.getError()) return EC; auto *Flags = reinterpret_cast<const object::Elf_Mips_ABIFlags<ELFT> *>( ContentOrErr.get().data()); S->Version = Flags->version; S->ISALevel = Flags->isa_level; S->ISARevision = Flags->isa_rev; S->GPRSize = Flags->gpr_size; S->CPR1Size = Flags->cpr1_size; S->CPR2Size = Flags->cpr2_size; S->FpABI = Flags->fp_abi; S->ISAExtension = Flags->isa_ext; S->ASEs = Flags->ases; S->Flags1 = Flags->flags1; S->Flags2 = Flags->flags2; return S.release(); } template <class ELFT> static std::error_code elf2yaml(raw_ostream &Out, const object::ELFFile<ELFT> &Obj) { ELFDumper<ELFT> Dumper(Obj); ErrorOr<ELFYAML::Object *> YAMLOrErr = Dumper.dump(); if (std::error_code EC = YAMLOrErr.getError()) return EC; std::unique_ptr<ELFYAML::Object> YAML(YAMLOrErr.get()); yaml::Output Yout(Out); Yout << *YAML; return std::error_code(); } std::error_code elf2yaml(raw_ostream &Out, const object::ObjectFile &Obj) { if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(&Obj)) return elf2yaml(Out, *ELFObj->getELFFile()); if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(&Obj)) return elf2yaml(Out, *ELFObj->getELFFile()); if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(&Obj)) return elf2yaml(Out, *ELFObj->getELFFile()); if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(&Obj)) return elf2yaml(Out, *ELFObj->getELFFile()); return obj2yaml_error::unsupported_obj_file_format; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-profdata/llvm-profdata.cpp
//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // llvm-profdata merges .profdata files. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/IR/LLVMContext.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/ProfileData/SampleProfReader.h" #include "llvm/ProfileData/SampleProfWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static void exitWithError(const Twine &Message, StringRef Whence = "") { errs() << "error: "; if (!Whence.empty()) errs() << Whence << ": "; errs() << Message << "\n"; ::exit(1); } namespace { enum ProfileKinds { instr, sample }; } static void mergeInstrProfile(const cl::list<std::string> &Inputs, StringRef OutputFilename) { if (OutputFilename.compare("-") == 0) exitWithError("Cannot write indexed profdata format to stdout."); std::error_code EC; raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None); if (EC) exitWithError(EC.message(), OutputFilename); InstrProfWriter Writer; for (const auto &Filename : Inputs) { auto ReaderOrErr = InstrProfReader::create(Filename); if (std::error_code ec = ReaderOrErr.getError()) exitWithError(ec.message(), Filename); auto Reader = std::move(ReaderOrErr.get()); for (const auto &I : *Reader) if (std::error_code EC = Writer.addFunctionCounts(I.Name, I.Hash, I.Counts)) errs() << Filename << ": " << I.Name << ": " << EC.message() << "\n"; if (Reader->hasError()) exitWithError(Reader->getError().message(), Filename); } Writer.write(Output); } static void mergeSampleProfile(const cl::list<std::string> &Inputs, StringRef OutputFilename, sampleprof::SampleProfileFormat OutputFormat) { using namespace sampleprof; auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat); if (std::error_code EC = WriterOrErr.getError()) exitWithError(EC.message(), OutputFilename); auto Writer = std::move(WriterOrErr.get()); StringMap<FunctionSamples> ProfileMap; for (const auto &Filename : Inputs) { auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext()); if (std::error_code EC = ReaderOrErr.getError()) exitWithError(EC.message(), Filename); auto Reader = std::move(ReaderOrErr.get()); if (std::error_code EC = Reader->read()) exitWithError(EC.message(), Filename); StringMap<FunctionSamples> &Profiles = Reader->getProfiles(); for (StringMap<FunctionSamples>::iterator I = Profiles.begin(), E = Profiles.end(); I != E; ++I) { StringRef FName = I->first(); FunctionSamples &Samples = I->second; ProfileMap[FName].merge(Samples); } } Writer->write(ProfileMap); } static int merge_main(int argc, const char *argv[]) { cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore, cl::desc("<filenames...>")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::Required, cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::opt<ProfileKinds> ProfileKind( cl::desc("Profile kind:"), cl::init(instr), cl::values(clEnumVal(instr, "Instrumentation profile (default)"), clEnumVal(sample, "Sample profile"), clEnumValEnd)); cl::opt<sampleprof::SampleProfileFormat> OutputFormat( cl::desc("Format of output profile (only meaningful with --sample)"), cl::init(sampleprof::SPF_Binary), cl::values(clEnumValN(sampleprof::SPF_Binary, "binary", "Binary encoding (default)"), clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"), clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"), clEnumValEnd)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n"); if (ProfileKind == instr) mergeInstrProfile(Inputs, OutputFilename); else mergeSampleProfile(Inputs, OutputFilename, OutputFormat); return 0; } static int showInstrProfile(std::string Filename, bool ShowCounts, bool ShowAllFunctions, std::string ShowFunction, raw_fd_ostream &OS) { auto ReaderOrErr = InstrProfReader::create(Filename); if (std::error_code EC = ReaderOrErr.getError()) exitWithError(EC.message(), Filename); auto Reader = std::move(ReaderOrErr.get()); uint64_t MaxFunctionCount = 0, MaxBlockCount = 0; size_t ShownFunctions = 0, TotalFunctions = 0; for (const auto &Func : *Reader) { bool Show = ShowAllFunctions || (!ShowFunction.empty() && Func.Name.find(ShowFunction) != Func.Name.npos); ++TotalFunctions; assert(Func.Counts.size() > 0 && "function missing entry counter"); if (Func.Counts[0] > MaxFunctionCount) MaxFunctionCount = Func.Counts[0]; if (Show) { if (!ShownFunctions) OS << "Counters:\n"; ++ShownFunctions; OS << " " << Func.Name << ":\n" << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n" << " Counters: " << Func.Counts.size() << "\n" << " Function count: " << Func.Counts[0] << "\n"; } if (Show && ShowCounts) OS << " Block counts: ["; for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) { if (Func.Counts[I] > MaxBlockCount) MaxBlockCount = Func.Counts[I]; if (Show && ShowCounts) OS << (I == 1 ? "" : ", ") << Func.Counts[I]; } if (Show && ShowCounts) OS << "]\n"; } if (Reader->hasError()) exitWithError(Reader->getError().message(), Filename); if (ShowAllFunctions || !ShowFunction.empty()) OS << "Functions shown: " << ShownFunctions << "\n"; OS << "Total functions: " << TotalFunctions << "\n"; OS << "Maximum function count: " << MaxFunctionCount << "\n"; OS << "Maximum internal block count: " << MaxBlockCount << "\n"; return 0; } static int showSampleProfile(std::string Filename, bool ShowCounts, bool ShowAllFunctions, std::string ShowFunction, raw_fd_ostream &OS) { using namespace sampleprof; auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext()); if (std::error_code EC = ReaderOrErr.getError()) exitWithError(EC.message(), Filename); auto Reader = std::move(ReaderOrErr.get()); Reader->read(); if (ShowAllFunctions || ShowFunction.empty()) Reader->dump(OS); else Reader->dumpFunctionProfile(ShowFunction, OS); return 0; } static int show_main(int argc, const char *argv[]) { cl::opt<std::string> Filename(cl::Positional, cl::Required, cl::desc("<profdata-file>")); cl::opt<bool> ShowCounts("counts", cl::init(false), cl::desc("Show counter values for shown functions")); cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), cl::desc("Details for every function")); cl::opt<std::string> ShowFunction("function", cl::desc("Details for matching functions")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::opt<ProfileKinds> ProfileKind( cl::desc("Profile kind:"), cl::init(instr), cl::values(clEnumVal(instr, "Instrumentation profile (default)"), clEnumVal(sample, "Sample profile"), clEnumValEnd)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); if (OutputFilename.empty()) OutputFilename = "-"; std::error_code EC; raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text); if (EC) exitWithError(EC.message(), OutputFilename); if (ShowAllFunctions && !ShowFunction.empty()) errs() << "warning: -function argument ignored: showing all functions\n"; if (ProfileKind == instr) return showInstrProfile(Filename, ShowCounts, ShowAllFunctions, ShowFunction, OS); else return showSampleProfile(Filename, ShowCounts, ShowAllFunctions, ShowFunction, OS); } int main(int argc, const char *argv[]) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. StringRef ProgName(sys::path::filename(argv[0])); if (argc > 1) { int (*func)(int, const char *[]) = nullptr; if (strcmp(argv[1], "merge") == 0) func = merge_main; else if (strcmp(argv[1], "show") == 0) func = show_main; if (func) { std::string Invocation(ProgName.str() + " " + argv[1]); argv[1] = Invocation.c_str(); return func(argc - 1, argv + 1); } if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0) { errs() << "OVERVIEW: LLVM profile data tools\n\n" << "USAGE: " << ProgName << " <command> [args...]\n" << "USAGE: " << ProgName << " <command> -help\n\n" << "Available commands: merge, show\n"; return 0; } } if (argc < 2) errs() << ProgName << ": No command specified!\n"; else errs() << ProgName << ": Unknown command!\n"; errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n"; return 1; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-profdata/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Core ProfileData Support ) add_llvm_tool(llvm-profdata llvm-profdata.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-profdata/LLVMBuild.txt
;===- ./tools/llvm-profdata/LLVMBuild.txt ----------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-profdata parent = Tools required_libraries = ProfileData Support
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like "dwarfdump". // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/RelocVisitor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <list> #include <string> #include <system_error> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"), cl::ZeroOrMore); static cl::opt<DIDumpType> DumpType("debug-dump", cl::init(DIDT_All), cl::desc("Dump of debug sections:"), cl::values( clEnumValN(DIDT_All, "all", "Dump all debug sections"), clEnumValN(DIDT_Abbrev, "abbrev", ".debug_abbrev"), clEnumValN(DIDT_AbbrevDwo, "abbrev.dwo", ".debug_abbrev.dwo"), clEnumValN(DIDT_AppleNames, "apple_names", ".apple_names"), clEnumValN(DIDT_AppleTypes, "apple_types", ".apple_types"), clEnumValN(DIDT_AppleNamespaces, "apple_namespaces", ".apple_namespaces"), clEnumValN(DIDT_AppleObjC, "apple_objc", ".apple_objc"), clEnumValN(DIDT_Aranges, "aranges", ".debug_aranges"), clEnumValN(DIDT_Info, "info", ".debug_info"), clEnumValN(DIDT_InfoDwo, "info.dwo", ".debug_info.dwo"), clEnumValN(DIDT_Types, "types", ".debug_types"), clEnumValN(DIDT_TypesDwo, "types.dwo", ".debug_types.dwo"), clEnumValN(DIDT_Line, "line", ".debug_line"), clEnumValN(DIDT_LineDwo, "line.dwo", ".debug_line.dwo"), clEnumValN(DIDT_Loc, "loc", ".debug_loc"), clEnumValN(DIDT_LocDwo, "loc.dwo", ".debug_loc.dwo"), clEnumValN(DIDT_Frames, "frames", ".debug_frame"), clEnumValN(DIDT_Ranges, "ranges", ".debug_ranges"), clEnumValN(DIDT_Pubnames, "pubnames", ".debug_pubnames"), clEnumValN(DIDT_Pubtypes, "pubtypes", ".debug_pubtypes"), clEnumValN(DIDT_GnuPubnames, "gnu_pubnames", ".debug_gnu_pubnames"), clEnumValN(DIDT_GnuPubtypes, "gnu_pubtypes", ".debug_gnu_pubtypes"), clEnumValN(DIDT_Str, "str", ".debug_str"), clEnumValN(DIDT_StrDwo, "str.dwo", ".debug_str.dwo"), clEnumValN(DIDT_StrOffsetsDwo, "str_offsets.dwo", ".debug_str_offsets.dwo"), clEnumValEnd)); static int ReturnValue = EXIT_SUCCESS; static bool error(StringRef Filename, std::error_code EC) { if (!EC) return false; errs() << Filename << ": " << EC.message() << "\n"; ReturnValue = EXIT_FAILURE; return true; } static void DumpInput(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); if (error(Filename, BuffOrErr.getError())) return; std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get()); ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = ObjectFile::createObjectFile(Buff->getMemBufferRef()); if (error(Filename, ObjOrErr.getError())) return; ObjectFile &Obj = *ObjOrErr.get(); std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); outs() << Filename << ":\tfile format " << Obj.getFileFormatName() << "\n\n"; // Dump the complete DWARF structure. DICtx->dump(outs(), DumpType); } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n"); // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput); return ReturnValue; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-dwarfdump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS DebugInfoDWARF Object Support ) add_llvm_tool(llvm-dwarfdump llvm-dwarfdump.cpp ) if(LLVM_USE_SANITIZE_COVERAGE) add_subdirectory(fuzzer) endif()
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-dwarfdump/LLVMBuild.txt
;===- ./tools/llvm-dwarfdump/LLVMBuild.txt ---------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-dwarfdump parent = Tools required_libraries = DebugInfoDWARF Object
0
repos/DirectXShaderCompiler/tools/llvm-dwarfdump
repos/DirectXShaderCompiler/tools/llvm-dwarfdump/fuzzer/llvm-dwarfdump-fuzzer.cpp
//===-- llvm-dwarfdump-fuzzer.cpp - Fuzz the llvm-dwarfdump tool ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a function that runs llvm-dwarfdump /// on a single input. This function is then linked into the Fuzzer library. /// //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/MemoryBuffer.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace llvm; using namespace object; extern "C" void LLVMFuzzerTestOneInput(uint8_t *data, size_t size) { std::unique_ptr<MemoryBuffer> Buff = MemoryBuffer::getMemBuffer( StringRef((const char *)data, size), "", false); ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = ObjectFile::createObjectFile(Buff->getMemBufferRef()); if (!ObjOrErr) return; ObjectFile &Obj = *ObjOrErr.get(); std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); DICtx->dump(nulls(), DIDT_All); }
0
repos/DirectXShaderCompiler/tools/llvm-dwarfdump
repos/DirectXShaderCompiler/tools/llvm-dwarfdump/fuzzer/CMakeLists.txt
set(LLVM_LINK_COMPONENTS DebugInfoDWARF Object Support ) add_llvm_executable(llvm-dwarfdump-fuzzer EXCLUDE_FROM_ALL llvm-dwarfdump-fuzzer.cpp ) target_link_libraries(llvm-dwarfdump-fuzzer LLVMFuzzer )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/llvm-readobj.cpp
//===- llvm-readobj.cpp - Dump contents of an Object File -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a tool similar to readelf, except it works on multiple object file // formats. The main purpose of this tool is to provide detailed output suitable // for FileCheck. // // Flags should be similar to readelf where supported, but the output format // does not need to be identical. The point is to not make users learn yet // another set of flags. // // Output should be specialized for each format where appropriate. // //===----------------------------------------------------------------------===// #include "llvm-readobj.h" #include "Error.h" #include "ObjDumper.h" #include "StreamWriter.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include <string> #include <system_error> using namespace llvm; using namespace llvm::object; namespace opts { cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"), cl::ZeroOrMore); // -file-headers, -h cl::opt<bool> FileHeaders("file-headers", cl::desc("Display file headers ")); cl::alias FileHeadersShort("h", cl::desc("Alias for --file-headers"), cl::aliasopt(FileHeaders)); // -sections, -s cl::opt<bool> Sections("sections", cl::desc("Display all sections.")); cl::alias SectionsShort("s", cl::desc("Alias for --sections"), cl::aliasopt(Sections)); // -section-relocations, -sr cl::opt<bool> SectionRelocations("section-relocations", cl::desc("Display relocations for each section shown.")); cl::alias SectionRelocationsShort("sr", cl::desc("Alias for --section-relocations"), cl::aliasopt(SectionRelocations)); // -section-symbols, -st cl::opt<bool> SectionSymbols("section-symbols", cl::desc("Display symbols for each section shown.")); cl::alias SectionSymbolsShort("st", cl::desc("Alias for --section-symbols"), cl::aliasopt(SectionSymbols)); // -section-data, -sd cl::opt<bool> SectionData("section-data", cl::desc("Display section data for each section shown.")); cl::alias SectionDataShort("sd", cl::desc("Alias for --section-data"), cl::aliasopt(SectionData)); // -relocations, -r cl::opt<bool> Relocations("relocations", cl::desc("Display the relocation entries in the file")); cl::alias RelocationsShort("r", cl::desc("Alias for --relocations"), cl::aliasopt(Relocations)); // -dyn-relocations cl::opt<bool> DynRelocs("dyn-relocations", cl::desc("Display the dynamic relocation entries in the file")); // -symbols, -t cl::opt<bool> Symbols("symbols", cl::desc("Display the symbol table")); cl::alias SymbolsShort("t", cl::desc("Alias for --symbols"), cl::aliasopt(Symbols)); // -dyn-symbols, -dt cl::opt<bool> DynamicSymbols("dyn-symbols", cl::desc("Display the dynamic symbol table")); cl::alias DynamicSymbolsShort("dt", cl::desc("Alias for --dyn-symbols"), cl::aliasopt(DynamicSymbols)); // -unwind, -u cl::opt<bool> UnwindInfo("unwind", cl::desc("Display unwind information")); cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind"), cl::aliasopt(UnwindInfo)); // -dynamic-table cl::opt<bool> DynamicTable("dynamic-table", cl::desc("Display the ELF .dynamic section table")); // -needed-libs cl::opt<bool> NeededLibraries("needed-libs", cl::desc("Display the needed libraries")); // -program-headers cl::opt<bool> ProgramHeaders("program-headers", cl::desc("Display ELF program headers")); // -hash-table cl::opt<bool> HashTable("hash-table", cl::desc("Display ELF hash table")); // -expand-relocs cl::opt<bool> ExpandRelocs("expand-relocs", cl::desc("Expand each shown relocation to multiple lines")); // -codeview cl::opt<bool> CodeView("codeview", cl::desc("Display CodeView debug information")); // -codeview-subsection-bytes cl::opt<bool> CodeViewSubsectionBytes( "codeview-subsection-bytes", cl::desc("Dump raw contents of codeview debug sections and records")); // -arm-attributes, -a cl::opt<bool> ARMAttributes("arm-attributes", cl::desc("Display the ARM attributes section")); cl::alias ARMAttributesShort("-a", cl::desc("Alias for --arm-attributes"), cl::aliasopt(ARMAttributes)); // -mips-plt-got cl::opt<bool> MipsPLTGOT("mips-plt-got", cl::desc("Display the MIPS GOT and PLT GOT sections")); // -mips-abi-flags cl::opt<bool> MipsABIFlags("mips-abi-flags", cl::desc("Display the MIPS.abiflags section")); // -mips-reginfo cl::opt<bool> MipsReginfo("mips-reginfo", cl::desc("Display the MIPS .reginfo section")); // -coff-imports cl::opt<bool> COFFImports("coff-imports", cl::desc("Display the PE/COFF import table")); // -coff-exports cl::opt<bool> COFFExports("coff-exports", cl::desc("Display the PE/COFF export table")); // -coff-directives cl::opt<bool> COFFDirectives("coff-directives", cl::desc("Display the PE/COFF .drectve section")); // -coff-basereloc cl::opt<bool> COFFBaseRelocs("coff-basereloc", cl::desc("Display the PE/COFF .reloc section")); // -stackmap cl::opt<bool> PrintStackMap("stackmap", cl::desc("Display contents of stackmap section")); } // namespace opts static int ReturnValue = EXIT_SUCCESS; namespace llvm { bool error(std::error_code EC) { if (!EC) return false; ReturnValue = EXIT_FAILURE; outs() << "\nError reading file: " << EC.message() << ".\n"; outs().flush(); return true; } bool relocAddressLess(RelocationRef a, RelocationRef b) { return a.getOffset() < b.getOffset(); } } // namespace llvm static void reportError(StringRef Input, std::error_code EC) { if (Input == "-") Input = "<stdin>"; errs() << Input << ": " << EC.message() << "\n"; errs().flush(); ReturnValue = EXIT_FAILURE; } static void reportError(StringRef Input, StringRef Message) { if (Input == "-") Input = "<stdin>"; errs() << Input << ": " << Message << "\n"; ReturnValue = EXIT_FAILURE; } static bool isMipsArch(unsigned Arch) { switch (Arch) { case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::mips64: case llvm::Triple::mips64el: return true; default: return false; } } /// @brief Creates an format-specific object file dumper. static std::error_code createDumper(const ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result) { if (!Obj) return readobj_error::unsupported_file_format; if (Obj->isCOFF()) return createCOFFDumper(Obj, Writer, Result); if (Obj->isELF()) return createELFDumper(Obj, Writer, Result); if (Obj->isMachO()) return createMachODumper(Obj, Writer, Result); return readobj_error::unsupported_obj_file_format; } static StringRef getLoadName(const ObjectFile *Obj) { if (auto *ELF = dyn_cast<ELF32LEObjectFile>(Obj)) return ELF->getLoadName(); if (auto *ELF = dyn_cast<ELF64LEObjectFile>(Obj)) return ELF->getLoadName(); if (auto *ELF = dyn_cast<ELF32BEObjectFile>(Obj)) return ELF->getLoadName(); if (auto *ELF = dyn_cast<ELF64BEObjectFile>(Obj)) return ELF->getLoadName(); llvm_unreachable("Not ELF"); } /// @brief Dumps the specified object file. static void dumpObject(const ObjectFile *Obj) { StreamWriter Writer(outs()); std::unique_ptr<ObjDumper> Dumper; if (std::error_code EC = createDumper(Obj, Writer, Dumper)) { reportError(Obj->getFileName(), EC); return; } outs() << '\n'; outs() << "File: " << Obj->getFileName() << "\n"; outs() << "Format: " << Obj->getFileFormatName() << "\n"; outs() << "Arch: " << Triple::getArchTypeName((llvm::Triple::ArchType)Obj->getArch()) << "\n"; outs() << "AddressSize: " << (8*Obj->getBytesInAddress()) << "bit\n"; if (Obj->isELF()) outs() << "LoadName: " << getLoadName(Obj) << "\n"; if (opts::FileHeaders) Dumper->printFileHeaders(); if (opts::Sections) Dumper->printSections(); if (opts::Relocations) Dumper->printRelocations(); if (opts::DynRelocs) Dumper->printDynamicRelocations(); if (opts::Symbols) Dumper->printSymbols(); if (opts::DynamicSymbols) Dumper->printDynamicSymbols(); if (opts::UnwindInfo) Dumper->printUnwindInfo(); if (opts::DynamicTable) Dumper->printDynamicTable(); if (opts::NeededLibraries) Dumper->printNeededLibraries(); if (opts::ProgramHeaders) Dumper->printProgramHeaders(); if (opts::HashTable) Dumper->printHashTable(); if (Obj->getArch() == llvm::Triple::arm && Obj->isELF()) if (opts::ARMAttributes) Dumper->printAttributes(); if (isMipsArch(Obj->getArch()) && Obj->isELF()) { if (opts::MipsPLTGOT) Dumper->printMipsPLTGOT(); if (opts::MipsABIFlags) Dumper->printMipsABIFlags(); if (opts::MipsReginfo) Dumper->printMipsReginfo(); } if (opts::COFFImports) Dumper->printCOFFImports(); if (opts::COFFExports) Dumper->printCOFFExports(); if (opts::COFFDirectives) Dumper->printCOFFDirectives(); if (opts::COFFBaseRelocs) Dumper->printCOFFBaseReloc(); if (opts::PrintStackMap) Dumper->printStackMap(); } /// @brief Dumps each object file in \a Arc; static void dumpArchive(const Archive *Arc) { for (Archive::child_iterator ArcI = Arc->child_begin(), ArcE = Arc->child_end(); ArcI != ArcE; ++ArcI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcI->getAsBinary(); if (std::error_code EC = ChildOrErr.getError()) { // Ignore non-object files. if (EC != object_error::invalid_file_type) reportError(Arc->getFileName(), EC.message()); continue; } if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get())) dumpObject(Obj); else reportError(Arc->getFileName(), readobj_error::unrecognized_file_format); } } /// @brief Dumps each object file in \a MachO Universal Binary; static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) { for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { ErrorOr<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); if (ObjOrErr) dumpObject(&*ObjOrErr.get()); else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) dumpArchive(&*AOrErr.get()); else reportError(UBinary->getFileName(), ObjOrErr.getError().message()); } } /// @brief Opens \a File and dumps it. static void dumpInput(StringRef File) { // If file isn't stdin, check that it exists. if (File != "-" && !sys::fs::exists(File)) { reportError(File, readobj_error::file_not_found); return; } // Attempt to open the binary. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File); if (std::error_code EC = BinaryOrErr.getError()) { reportError(File, EC); return; } Binary &Binary = *BinaryOrErr.get().getBinary(); if (Archive *Arc = dyn_cast<Archive>(&Binary)) dumpArchive(Arc); else if (MachOUniversalBinary *UBinary = dyn_cast<MachOUniversalBinary>(&Binary)) dumpMachOUniversalBinary(UBinary); else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) dumpObject(Obj); else reportError(File, readobj_error::unrecognized_file_format); } int __cdecl main(int argc, const char *argv[]) { // HLSL Change - __cdecl sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n"); // Default to stdin if no filename is specified. if (opts::InputFilenames.size() == 0) opts::InputFilenames.push_back("-"); std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(), dumpInput); return ReturnValue; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ARMEHABIPrinter.h
//===--- ARMEHABIPrinter.h - ARM EHABI Unwind Information Printer ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_ARMEHABIPRINTER_H #define LLVM_TOOLS_LLVM_READOBJ_ARMEHABIPRINTER_H #include "Error.h" #include "StreamWriter.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Object/ELF.h" #include "llvm/Object/ELFTypes.h" #include "llvm/Support/ARMEHABI.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Format.h" #include "llvm/Support/type_traits.h" namespace llvm { namespace ARM { namespace EHABI { class OpcodeDecoder { StreamWriter &SW; raw_ostream &OS; struct RingEntry { uint8_t Mask; uint8_t Value; void (OpcodeDecoder::*Routine)(const uint8_t *Opcodes, unsigned &OI); }; static const RingEntry Ring[]; void Decode_00xxxxxx(const uint8_t *Opcodes, unsigned &OI); void Decode_01xxxxxx(const uint8_t *Opcodes, unsigned &OI); void Decode_1000iiii_iiiiiiii(const uint8_t *Opcodes, unsigned &OI); void Decode_10011101(const uint8_t *Opcodes, unsigned &OI); void Decode_10011111(const uint8_t *Opcodes, unsigned &OI); void Decode_1001nnnn(const uint8_t *Opcodes, unsigned &OI); void Decode_10100nnn(const uint8_t *Opcodes, unsigned &OI); void Decode_10101nnn(const uint8_t *Opcodes, unsigned &OI); void Decode_10110000(const uint8_t *Opcodes, unsigned &OI); void Decode_10110001_0000iiii(const uint8_t *Opcodes, unsigned &OI); void Decode_10110010_uleb128(const uint8_t *Opcodes, unsigned &OI); void Decode_10110011_sssscccc(const uint8_t *Opcodes, unsigned &OI); void Decode_101101nn(const uint8_t *Opcodes, unsigned &OI); void Decode_10111nnn(const uint8_t *Opcodes, unsigned &OI); void Decode_11000110_sssscccc(const uint8_t *Opcodes, unsigned &OI); void Decode_11000111_0000iiii(const uint8_t *Opcodes, unsigned &OI); void Decode_11001000_sssscccc(const uint8_t *Opcodes, unsigned &OI); void Decode_11001001_sssscccc(const uint8_t *Opcodes, unsigned &OI); void Decode_11001yyy(const uint8_t *Opcodes, unsigned &OI); void Decode_11000nnn(const uint8_t *Opcodes, unsigned &OI); void Decode_11010nnn(const uint8_t *Opcodes, unsigned &OI); void Decode_11xxxyyy(const uint8_t *Opcodes, unsigned &OI); void PrintGPR(uint16_t GPRMask); void PrintRegisters(uint32_t Mask, StringRef Prefix); public: OpcodeDecoder(StreamWriter &SW) : SW(SW), OS(SW.getOStream()) {} void Decode(const uint8_t *Opcodes, off_t Offset, size_t Length); }; const OpcodeDecoder::RingEntry OpcodeDecoder::Ring[] = { { 0xc0, 0x00, &OpcodeDecoder::Decode_00xxxxxx }, { 0xc0, 0x40, &OpcodeDecoder::Decode_01xxxxxx }, { 0xf0, 0x80, &OpcodeDecoder::Decode_1000iiii_iiiiiiii }, { 0xff, 0x9d, &OpcodeDecoder::Decode_10011101 }, { 0xff, 0x9f, &OpcodeDecoder::Decode_10011111 }, { 0xf0, 0x90, &OpcodeDecoder::Decode_1001nnnn }, { 0xf8, 0xa0, &OpcodeDecoder::Decode_10100nnn }, { 0xf8, 0xa8, &OpcodeDecoder::Decode_10101nnn }, { 0xff, 0xb0, &OpcodeDecoder::Decode_10110000 }, { 0xff, 0xb1, &OpcodeDecoder::Decode_10110001_0000iiii }, { 0xff, 0xb2, &OpcodeDecoder::Decode_10110010_uleb128 }, { 0xff, 0xb3, &OpcodeDecoder::Decode_10110011_sssscccc }, { 0xfc, 0xb4, &OpcodeDecoder::Decode_101101nn }, { 0xf8, 0xb8, &OpcodeDecoder::Decode_10111nnn }, { 0xff, 0xc6, &OpcodeDecoder::Decode_11000110_sssscccc }, { 0xff, 0xc7, &OpcodeDecoder::Decode_11000111_0000iiii }, { 0xff, 0xc8, &OpcodeDecoder::Decode_11001000_sssscccc }, { 0xff, 0xc9, &OpcodeDecoder::Decode_11001001_sssscccc }, { 0xc8, 0xc8, &OpcodeDecoder::Decode_11001yyy }, { 0xf8, 0xc0, &OpcodeDecoder::Decode_11000nnn }, { 0xf8, 0xd0, &OpcodeDecoder::Decode_11010nnn }, { 0xc0, 0xc0, &OpcodeDecoder::Decode_11xxxyyy }, }; void OpcodeDecoder::Decode_00xxxxxx(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; vsp = vsp + %u\n", Opcode, ((Opcode & 0x3f) << 2) + 4); } void OpcodeDecoder::Decode_01xxxxxx(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; vsp = vsp - %u\n", Opcode, ((Opcode & 0x3f) << 2) + 4); } void OpcodeDecoder::Decode_1000iiii_iiiiiiii(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; uint16_t GPRMask = (Opcode1 << 4) | ((Opcode0 & 0x0f) << 12); SW.startLine() << format("0x%02X 0x%02X ; %s", Opcode0, Opcode1, GPRMask ? "pop " : "refuse to unwind"); if (GPRMask) PrintGPR(GPRMask); OS << '\n'; } void OpcodeDecoder::Decode_10011101(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; reserved (ARM MOVrr)\n", Opcode); } void OpcodeDecoder::Decode_10011111(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; reserved (WiMMX MOVrr)\n", Opcode); } void OpcodeDecoder::Decode_1001nnnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; vsp = r%u\n", Opcode, (Opcode & 0x0f)); } void OpcodeDecoder::Decode_10100nnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; pop ", Opcode); PrintGPR((((1 << ((Opcode & 0x7) + 1)) - 1) << 4)); OS << '\n'; } void OpcodeDecoder::Decode_10101nnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; pop ", Opcode); PrintGPR((((1 << ((Opcode & 0x7) + 1)) - 1) << 4) | (1 << 14)); OS << '\n'; } void OpcodeDecoder::Decode_10110000(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; finish\n", Opcode); } void OpcodeDecoder::Decode_10110001_0000iiii(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; %s", Opcode0, Opcode1, ((Opcode1 & 0xf0) || Opcode1 == 0x00) ? "spare" : "pop "); if (((Opcode1 & 0xf0) == 0x00) && Opcode1) PrintGPR((Opcode1 & 0x0f)); OS << '\n'; } void OpcodeDecoder::Decode_10110010_uleb128(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ", Opcode); SmallVector<uint8_t, 4> ULEB; do { ULEB.push_back(Opcodes[OI ^ 3]); } while (Opcodes[OI++ ^ 3] & 0x80); for (unsigned BI = 0, BE = ULEB.size(); BI != BE; ++BI) OS << format("0x%02X ", ULEB[BI]); uint64_t Value = 0; for (unsigned BI = 0, BE = ULEB.size(); BI != BE; ++BI) Value = Value | ((ULEB[BI] & 0x7f) << (7 * BI)); OS << format("; vsp = vsp + %" PRIu64 "\n", 0x204 + (Value << 2)); } void OpcodeDecoder::Decode_10110011_sssscccc(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; pop ", Opcode0, Opcode1); uint8_t Start = ((Opcode1 & 0xf0) >> 4); uint8_t Count = ((Opcode1 & 0x0f) >> 0); PrintRegisters((((1 << (Count + 1)) - 1) << Start), "d"); OS << '\n'; } void OpcodeDecoder::Decode_101101nn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; spare\n", Opcode); } void OpcodeDecoder::Decode_10111nnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; pop ", Opcode); PrintRegisters((((1 << ((Opcode & 0x07) + 1)) - 1) << 8), "d"); OS << '\n'; } void OpcodeDecoder::Decode_11000110_sssscccc(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; pop ", Opcode0, Opcode1); uint8_t Start = ((Opcode1 & 0xf0) >> 4); uint8_t Count = ((Opcode1 & 0x0f) >> 0); PrintRegisters((((1 << (Count + 1)) - 1) << Start), "wR"); OS << '\n'; } void OpcodeDecoder::Decode_11000111_0000iiii(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; %s", Opcode0, Opcode1, ((Opcode1 & 0xf0) || Opcode1 == 0x00) ? "spare" : "pop "); if ((Opcode1 & 0xf0) == 0x00 && Opcode1) PrintRegisters(Opcode1 & 0x0f, "wCGR"); OS << '\n'; } void OpcodeDecoder::Decode_11001000_sssscccc(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; pop ", Opcode0, Opcode1); uint8_t Start = 16 + ((Opcode1 & 0xf0) >> 4); uint8_t Count = ((Opcode1 & 0x0f) >> 0); PrintRegisters((((1 << (Count + 1)) - 1) << Start), "d"); OS << '\n'; } void OpcodeDecoder::Decode_11001001_sssscccc(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode0 = Opcodes[OI++ ^ 3]; uint8_t Opcode1 = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X 0x%02X ; pop ", Opcode0, Opcode1); uint8_t Start = ((Opcode1 & 0xf0) >> 4); uint8_t Count = ((Opcode1 & 0x0f) >> 0); PrintRegisters((((1 << (Count + 1)) - 1) << Start), "d"); OS << '\n'; } void OpcodeDecoder::Decode_11001yyy(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; spare\n", Opcode); } void OpcodeDecoder::Decode_11000nnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; pop ", Opcode); PrintRegisters((((1 << ((Opcode & 0x07) + 1)) - 1) << 10), "wR"); OS << '\n'; } void OpcodeDecoder::Decode_11010nnn(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; pop ", Opcode); PrintRegisters((((1 << ((Opcode & 0x07) + 1)) - 1) << 8), "d"); OS << '\n'; } void OpcodeDecoder::Decode_11xxxyyy(const uint8_t *Opcodes, unsigned &OI) { uint8_t Opcode = Opcodes[OI++ ^ 3]; SW.startLine() << format("0x%02X ; spare\n", Opcode); } void OpcodeDecoder::PrintGPR(uint16_t GPRMask) { static const char *GPRRegisterNames[16] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "fp", "ip", "sp", "lr", "pc" }; OS << '{'; bool Comma = false; for (unsigned RI = 0, RE = 17; RI < RE; ++RI) { if (GPRMask & (1 << RI)) { if (Comma) OS << ", "; OS << GPRRegisterNames[RI]; Comma = true; } } OS << '}'; } void OpcodeDecoder::PrintRegisters(uint32_t VFPMask, StringRef Prefix) { OS << '{'; bool Comma = false; for (unsigned RI = 0, RE = 32; RI < RE; ++RI) { if (VFPMask & (1 << RI)) { if (Comma) OS << ", "; OS << Prefix << RI; Comma = true; } } OS << '}'; } void OpcodeDecoder::Decode(const uint8_t *Opcodes, off_t Offset, size_t Length) { for (unsigned OCI = Offset; OCI < Length + Offset; ) { bool Decoded = false; for (unsigned REI = 0, REE = array_lengthof(Ring); REI != REE && !Decoded; ++REI) { if ((Opcodes[OCI ^ 3] & Ring[REI].Mask) == Ring[REI].Value) { (this->*Ring[REI].Routine)(Opcodes, OCI); Decoded = true; break; } } if (!Decoded) SW.startLine() << format("0x%02X ; reserved\n", Opcodes[OCI++ ^ 3]); } } template <typename ET> class PrinterContext { StreamWriter &SW; const object::ELFFile<ET> *ELF; typedef typename object::ELFFile<ET>::Elf_Sym Elf_Sym; typedef typename object::ELFFile<ET>::Elf_Shdr Elf_Shdr; typedef typename object::ELFFile<ET>::Elf_Rel_Iter Elf_Rel_iterator; static const size_t IndexTableEntrySize; static uint64_t PREL31(uint32_t Address, uint32_t Place) { uint64_t Location = Address & 0x7fffffff; if (Location & 0x04000000) Location |= (uint64_t) ~0x7fffffff; return Location + Place; } ErrorOr<StringRef> FunctionAtAddress(unsigned Section, uint64_t Address) const; const Elf_Shdr *FindExceptionTable(unsigned IndexTableIndex, off_t IndexTableOffset) const; void PrintIndexTable(unsigned SectionIndex, const Elf_Shdr *IT) const; void PrintExceptionTable(const Elf_Shdr *IT, const Elf_Shdr *EHT, uint64_t TableEntryOffset) const; void PrintOpcodes(const uint8_t *Entry, size_t Length, off_t Offset) const; public: PrinterContext(StreamWriter &Writer, const object::ELFFile<ET> *File) : SW(Writer), ELF(File) {} void PrintUnwindInformation() const; }; template <typename ET> const size_t PrinterContext<ET>::IndexTableEntrySize = 8; template <typename ET> ErrorOr<StringRef> PrinterContext<ET>::FunctionAtAddress(unsigned Section, uint64_t Address) const { for (const Elf_Sym &Sym : ELF->symbols()) if (Sym.st_shndx == Section && Sym.st_value == Address && Sym.getType() == ELF::STT_FUNC) return ELF->getSymbolName(&Sym, false); return readobj_error::unknown_symbol; } template <typename ET> const typename object::ELFFile<ET>::Elf_Shdr * PrinterContext<ET>::FindExceptionTable(unsigned IndexSectionIndex, off_t IndexTableOffset) const { /// Iterate through the sections, searching for the relocation section /// associated with the unwind index table section specified by /// IndexSectionIndex. Iterate the associated section searching for the /// relocation associated with the index table entry specified by /// IndexTableOffset. The symbol is the section symbol for the exception /// handling table. Use this symbol to recover the actual exception handling /// table. for (const Elf_Shdr &Sec : ELF->sections()) { if (Sec.sh_type == ELF::SHT_REL && Sec.sh_info == IndexSectionIndex) { for (Elf_Rel_iterator RI = ELF->rel_begin(&Sec), RE = ELF->rel_end(&Sec); RI != RE; ++RI) { if (RI->r_offset == static_cast<unsigned>(IndexTableOffset)) { typename object::ELFFile<ET>::Elf_Rela RelA; RelA.r_offset = RI->r_offset; RelA.r_info = RI->r_info; RelA.r_addend = 0; std::pair<const Elf_Shdr *, const Elf_Sym *> Symbol = ELF->getRelocationSymbol(&Sec, &RelA); ErrorOr<const Elf_Shdr *> Ret = ELF->getSection(Symbol.second); if (std::error_code EC = Ret.getError()) report_fatal_error(EC.message()); return *Ret; } } } } return nullptr; } template <typename ET> void PrinterContext<ET>::PrintExceptionTable(const Elf_Shdr *IT, const Elf_Shdr *EHT, uint64_t TableEntryOffset) const { ErrorOr<ArrayRef<uint8_t> > Contents = ELF->getSectionContents(EHT); if (!Contents) return; /// ARM EHABI Section 6.2 - The generic model /// /// An exception-handling table entry for the generic model is laid out as: /// /// 3 3 /// 1 0 0 /// +-+------------------------------+ /// |0| personality routine offset | /// +-+------------------------------+ /// | personality routine data ... | /// /// /// ARM EHABI Section 6.3 - The ARM-defined compact model /// /// An exception-handling table entry for the compact model looks like: /// /// 3 3 2 2 2 2 /// 1 0 8 7 4 3 0 /// +-+---+----+-----------------------+ /// |1| 0 | Ix | data for pers routine | /// +-+---+----+-----------------------+ /// | more personality routine data | const support::ulittle32_t Word = *reinterpret_cast<const support::ulittle32_t *>(Contents->data() + TableEntryOffset); if (Word & 0x80000000) { SW.printString("Model", StringRef("Compact")); unsigned PersonalityIndex = (Word & 0x0f000000) >> 24; SW.printNumber("PersonalityIndex", PersonalityIndex); switch (PersonalityIndex) { case AEABI_UNWIND_CPP_PR0: PrintOpcodes(Contents->data() + TableEntryOffset, 3, 1); break; case AEABI_UNWIND_CPP_PR1: case AEABI_UNWIND_CPP_PR2: unsigned AdditionalWords = (Word & 0x00ff0000) >> 16; PrintOpcodes(Contents->data() + TableEntryOffset, 2 + 4 * AdditionalWords, 2); break; } } else { SW.printString("Model", StringRef("Generic")); uint64_t Address = PREL31(Word, EHT->sh_addr); SW.printHex("PersonalityRoutineAddress", Address); if (ErrorOr<StringRef> Name = FunctionAtAddress(EHT->sh_link, Address)) SW.printString("PersonalityRoutineName", *Name); } } template <typename ET> void PrinterContext<ET>::PrintOpcodes(const uint8_t *Entry, size_t Length, off_t Offset) const { ListScope OCC(SW, "Opcodes"); OpcodeDecoder(OCC.W).Decode(Entry, Offset, Length); } template <typename ET> void PrinterContext<ET>::PrintIndexTable(unsigned SectionIndex, const Elf_Shdr *IT) const { ErrorOr<ArrayRef<uint8_t> > Contents = ELF->getSectionContents(IT); if (!Contents) return; /// ARM EHABI Section 5 - Index Table Entries /// * The first word contains a PREL31 offset to the start of a function with /// bit 31 clear /// * The second word contains one of: /// - The PREL31 offset of the start of the table entry for the function, /// with bit 31 clear /// - The exception-handling table entry itself with bit 31 set /// - The special bit pattern EXIDX_CANTUNWIND, indicating that associated /// frames cannot be unwound const support::ulittle32_t *Data = reinterpret_cast<const support::ulittle32_t *>(Contents->data()); const unsigned Entries = IT->sh_size / IndexTableEntrySize; ListScope E(SW, "Entries"); for (unsigned Entry = 0; Entry < Entries; ++Entry) { DictScope E(SW, "Entry"); const support::ulittle32_t Word0 = Data[Entry * (IndexTableEntrySize / sizeof(*Data)) + 0]; const support::ulittle32_t Word1 = Data[Entry * (IndexTableEntrySize / sizeof(*Data)) + 1]; if (Word0 & 0x80000000) { errs() << "corrupt unwind data in section " << SectionIndex << "\n"; continue; } const uint64_t Offset = PREL31(Word0, IT->sh_addr); SW.printHex("FunctionAddress", Offset); if (ErrorOr<StringRef> Name = FunctionAtAddress(IT->sh_link, Offset)) SW.printString("FunctionName", *Name); if (Word1 == EXIDX_CANTUNWIND) { SW.printString("Model", StringRef("CantUnwind")); continue; } if (Word1 & 0x80000000) { SW.printString("Model", StringRef("Compact (Inline)")); unsigned PersonalityIndex = (Word1 & 0x0f000000) >> 24; SW.printNumber("PersonalityIndex", PersonalityIndex); PrintOpcodes(Contents->data() + Entry * IndexTableEntrySize + 4, 3, 1); } else { const Elf_Shdr *EHT = FindExceptionTable(SectionIndex, Entry * IndexTableEntrySize + 4); if (ErrorOr<StringRef> Name = ELF->getSectionName(EHT)) SW.printString("ExceptionHandlingTable", *Name); uint64_t TableEntryOffset = PREL31(Word1, IT->sh_addr); SW.printHex("TableEntryOffset", TableEntryOffset); PrintExceptionTable(IT, EHT, TableEntryOffset); } } } template <typename ET> void PrinterContext<ET>::PrintUnwindInformation() const { DictScope UI(SW, "UnwindInformation"); int SectionIndex = 0; for (const Elf_Shdr &Sec : ELF->sections()) { if (Sec.sh_type == ELF::SHT_ARM_EXIDX) { DictScope UIT(SW, "UnwindIndexTable"); SW.printNumber("SectionIndex", SectionIndex); if (ErrorOr<StringRef> SectionName = ELF->getSectionName(&Sec)) SW.printString("SectionName", *SectionName); SW.printHex("SectionOffset", Sec.sh_offset); PrintIndexTable(SectionIndex, &Sec); } ++SectionIndex; } } } } } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/StreamWriter.cpp
#include "StreamWriter.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" #include <cctype> using namespace llvm::support; namespace llvm { raw_ostream &operator<<(raw_ostream &OS, const HexNumber& Value) { uint64_t N = Value.Value; // Zero is a special case. if (N == 0) return OS << "0x0"; char NumberBuffer[20]; char *EndPtr = NumberBuffer + sizeof(NumberBuffer); char *CurPtr = EndPtr; while (N) { uintptr_t X = N % 16; *--CurPtr = (X < 10 ? '0' + X : 'A' + X - 10); N /= 16; } OS << "0x"; return OS.write(CurPtr, EndPtr - CurPtr); } void StreamWriter::printBinaryImpl(StringRef Label, StringRef Str, ArrayRef<uint8_t> Data, bool Block) { if (Data.size() > 16) Block = true; if (Block) { startLine() << Label; if (Str.size() > 0) OS << ": " << Str; OS << " (\n"; for (size_t addr = 0, end = Data.size(); addr < end; addr += 16) { startLine() << format(" %04" PRIX64 ": ", uint64_t(addr)); // Dump line of hex. for (size_t i = 0; i < 16; ++i) { if (i != 0 && i % 4 == 0) OS << ' '; if (addr + i < end) OS << hexdigit((Data[addr + i] >> 4) & 0xF, false) << hexdigit(Data[addr + i] & 0xF, false); else OS << " "; } // Print ascii. OS << " |"; for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { if (std::isprint(Data[addr + i] & 0xFF)) OS << Data[addr + i]; else OS << "."; } OS << "|\n"; } startLine() << ")\n"; } else { startLine() << Label << ":"; if (Str.size() > 0) OS << " " << Str; OS << " ("; for (size_t i = 0; i < Data.size(); ++i) { if (i > 0) OS << " "; OS << format("%02X", static_cast<int>(Data[i])); } OS << ")\n"; } } } // namespace llvm
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ObjDumper.h
//===-- ObjDumper.h -------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_OBJDUMPER_H #define LLVM_TOOLS_LLVM_READOBJ_OBJDUMPER_H #include <memory> #include <system_error> namespace llvm { namespace object { class ObjectFile; } class StreamWriter; class ObjDumper { public: ObjDumper(StreamWriter& Writer); virtual ~ObjDumper(); virtual void printFileHeaders() = 0; virtual void printSections() = 0; virtual void printRelocations() = 0; virtual void printSymbols() = 0; virtual void printDynamicSymbols() = 0; virtual void printUnwindInfo() = 0; // Only implemented for ELF at this time. virtual void printDynamicRelocations() { } virtual void printDynamicTable() { } virtual void printNeededLibraries() { } virtual void printProgramHeaders() { } virtual void printHashTable() { } // Only implemented for ARM ELF at this time. virtual void printAttributes() { } // Only implemented for MIPS ELF at this time. virtual void printMipsPLTGOT() { } virtual void printMipsABIFlags() { } virtual void printMipsReginfo() { } // Only implemented for PE/COFF. virtual void printCOFFImports() { } virtual void printCOFFExports() { } virtual void printCOFFDirectives() { } virtual void printCOFFBaseReloc() { } virtual void printStackMap() const = 0; protected: StreamWriter& W; }; std::error_code createCOFFDumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result); std::error_code createELFDumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result); std::error_code createMachODumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result); } // namespace llvm #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ARMAttributeParser.cpp
//===--- ARMAttributeParser.cpp - ARM Attribute Information Printer -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ARMAttributeParser.h" #include "StreamWriter.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/LEB128.h" using namespace llvm; using namespace llvm::ARMBuildAttrs; static const EnumEntry<unsigned> TagNames[] = { { "Tag_File", ARMBuildAttrs::File }, { "Tag_Section", ARMBuildAttrs::Section }, { "Tag_Symbol", ARMBuildAttrs::Symbol }, }; namespace llvm { #define ATTRIBUTE_HANDLER(Attr_) \ { ARMBuildAttrs::Attr_, &ARMAttributeParser::Attr_ } const ARMAttributeParser::DisplayHandler ARMAttributeParser::DisplayRoutines[] = { { ARMBuildAttrs::CPU_raw_name, &ARMAttributeParser::StringAttribute, }, { ARMBuildAttrs::CPU_name, &ARMAttributeParser::StringAttribute }, ATTRIBUTE_HANDLER(CPU_arch), ATTRIBUTE_HANDLER(CPU_arch_profile), ATTRIBUTE_HANDLER(ARM_ISA_use), ATTRIBUTE_HANDLER(THUMB_ISA_use), ATTRIBUTE_HANDLER(FP_arch), ATTRIBUTE_HANDLER(WMMX_arch), ATTRIBUTE_HANDLER(Advanced_SIMD_arch), ATTRIBUTE_HANDLER(PCS_config), ATTRIBUTE_HANDLER(ABI_PCS_R9_use), ATTRIBUTE_HANDLER(ABI_PCS_RW_data), ATTRIBUTE_HANDLER(ABI_PCS_RO_data), ATTRIBUTE_HANDLER(ABI_PCS_GOT_use), ATTRIBUTE_HANDLER(ABI_PCS_wchar_t), ATTRIBUTE_HANDLER(ABI_FP_rounding), ATTRIBUTE_HANDLER(ABI_FP_denormal), ATTRIBUTE_HANDLER(ABI_FP_exceptions), ATTRIBUTE_HANDLER(ABI_FP_user_exceptions), ATTRIBUTE_HANDLER(ABI_FP_number_model), ATTRIBUTE_HANDLER(ABI_align_needed), ATTRIBUTE_HANDLER(ABI_align_preserved), ATTRIBUTE_HANDLER(ABI_enum_size), ATTRIBUTE_HANDLER(ABI_HardFP_use), ATTRIBUTE_HANDLER(ABI_VFP_args), ATTRIBUTE_HANDLER(ABI_WMMX_args), ATTRIBUTE_HANDLER(ABI_optimization_goals), ATTRIBUTE_HANDLER(ABI_FP_optimization_goals), ATTRIBUTE_HANDLER(compatibility), ATTRIBUTE_HANDLER(CPU_unaligned_access), ATTRIBUTE_HANDLER(FP_HP_extension), ATTRIBUTE_HANDLER(ABI_FP_16bit_format), ATTRIBUTE_HANDLER(MPextension_use), ATTRIBUTE_HANDLER(DIV_use), ATTRIBUTE_HANDLER(T2EE_use), ATTRIBUTE_HANDLER(Virtualization_use), ATTRIBUTE_HANDLER(nodefaults) }; #undef ATTRIBUTE_HANDLER uint64_t ARMAttributeParser::ParseInteger(const uint8_t *Data, uint32_t &Offset) { unsigned Length; uint64_t Value = decodeULEB128(Data + Offset, &Length); Offset = Offset + Length; return Value; } StringRef ARMAttributeParser::ParseString(const uint8_t *Data, uint32_t &Offset) { const char *String = reinterpret_cast<const char*>(Data + Offset); size_t Length = std::strlen(String); Offset = Offset + Length + 1; return StringRef(String, Length); } void ARMAttributeParser::IntegerAttribute(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { SW.printNumber(ARMBuildAttrs::AttrTypeAsString(Tag), ParseInteger(Data, Offset)); } void ARMAttributeParser::StringAttribute(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { StringRef TagName = ARMBuildAttrs::AttrTypeAsString(Tag, /*TagPrefix*/false); DictScope AS(SW, "Attribute"); SW.printNumber("Tag", Tag); if (!TagName.empty()) SW.printString("TagName", TagName); SW.printString("Value", ParseString(Data, Offset)); } void ARMAttributeParser::PrintAttribute(unsigned Tag, unsigned Value, StringRef ValueDesc) { StringRef TagName = ARMBuildAttrs::AttrTypeAsString(Tag, /*TagPrefix*/false); DictScope AS(SW, "Attribute"); SW.printNumber("Tag", Tag); SW.printNumber("Value", Value); if (!TagName.empty()) SW.printString("TagName", TagName); if (!ValueDesc.empty()) SW.printString("Description", ValueDesc); } void ARMAttributeParser::CPU_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Pre-v4", "ARM v4", "ARM v4T", "ARM v5T", "ARM v5TE", "ARM v5TEJ", "ARM v6", "ARM v6KZ", "ARM v6T2", "ARM v6K", "ARM v7", "ARM v6-M", "ARM v6S-M", "ARM v7E-M", "ARM v8" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::CPU_arch_profile(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { uint64_t Encoded = ParseInteger(Data, Offset); StringRef Profile; switch (Encoded) { default: Profile = "Unknown"; break; case 'A': Profile = "Application"; break; case 'R': Profile = "Real-time"; break; case 'M': Profile = "Microcontroller"; break; case 'S': Profile = "Classic"; break; case 0: Profile = "None"; break; } PrintAttribute(Tag, Encoded, Profile); } void ARMAttributeParser::ARM_ISA_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::THUMB_ISA_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Thumb-1", "Thumb-2" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::FP_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "VFPv1", "VFPv2", "VFPv3", "VFPv3-D16", "VFPv4", "VFPv4-D16", "ARMv8-a FP", "ARMv8-a FP-D16" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::WMMX_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "WMMXv1", "WMMXv2" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::Advanced_SIMD_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "NEONv1", "NEONv2+FMA", "ARMv8-a NEON" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::PCS_config(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "None", "Bare Platform", "Linux Application", "Linux DSO", "Palm OS 2004", "Reserved (Palm OS)", "Symbian OS 2004", "Reserved (Symbian OS)" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_R9_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "v6", "Static Base", "TLS", "Unused" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_RW_data(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Absolute", "PC-relative", "SB-relative", "Not Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_RO_data(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Absolute", "PC-relative", "Not Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_GOT_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Direct", "GOT-Indirect" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_wchar_t(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Unknown", "2-byte", "Unknown", "4-byte" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_rounding(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "IEEE-754", "Runtime" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_denormal(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Unsupported", "IEEE-754", "Sign Only" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_exceptions(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "IEEE-754" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_user_exceptions(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "IEEE-754" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_number_model(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Finite Only", "RTABI", "IEEE-754" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_align_needed(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "8-byte alignment", "4-byte alignment", "Reserved" }; uint64_t Value = ParseInteger(Data, Offset); std::string Description; if (Value < array_lengthof(Strings)) Description = std::string(Strings[Value]); else if (Value <= 12) Description = std::string("8-byte alignment, ") + utostr(1 << Value) + std::string("-byte extended alignment"); else Description = "Invalid"; PrintAttribute(Tag, Value, Description); } void ARMAttributeParser::ABI_align_preserved(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Required", "8-byte data alignment", "8-byte data and code alignment", "Reserved" }; uint64_t Value = ParseInteger(Data, Offset); std::string Description; if (Value < array_lengthof(Strings)) Description = std::string(Strings[Value]); else if (Value <= 12) Description = std::string("8-byte stack alignment, ") + utostr(1 << Value) + std::string("-byte data alignment"); else Description = "Invalid"; PrintAttribute(Tag, Value, Description); } void ARMAttributeParser::ABI_enum_size(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Packed", "Int32", "External Int32" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_HardFP_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Tag_FP_arch", "Single-Precision", "Reserved", "Tag_FP_arch (deprecated)" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_VFP_args(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "AAPCS", "AAPCS VFP", "Custom", "Not Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_WMMX_args(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "AAPCS", "iWMMX", "Custom" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_optimization_goals(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "None", "Speed", "Aggressive Speed", "Size", "Aggressive Size", "Debugging", "Best Debugging" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_optimization_goals(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "None", "Speed", "Aggressive Speed", "Size", "Aggressive Size", "Accuracy", "Best Accuracy" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::compatibility(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { uint64_t Integer = ParseInteger(Data, Offset); StringRef String = ParseString(Data, Offset); DictScope AS(SW, "Attribute"); SW.printNumber("Tag", Tag); SW.startLine() << "Value: " << Integer << ", " << String << '\n'; SW.printString("TagName", AttrTypeAsString(Tag, /*TagPrefix*/false)); switch (Integer) { case 0: SW.printString("Description", StringRef("No Specific Requirements")); break; case 1: SW.printString("Description", StringRef("AEABI Conformant")); break; default: SW.printString("Description", StringRef("AEABI Non-Conformant")); break; } } void ARMAttributeParser::CPU_unaligned_access(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "v6-style" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::FP_HP_extension(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "If Available", "Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_16bit_format(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "IEEE-754", "VFPv3" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::MPextension_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::DIV_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "If Available", "Not Permitted", "Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::T2EE_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "Permitted" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::Virtualization_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { static const char *Strings[] = { "Not Permitted", "TrustZone", "Virtualization Extensions", "TrustZone + Virtualization Extensions" }; uint64_t Value = ParseInteger(Data, Offset); StringRef ValueDesc = (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::nodefaults(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { uint64_t Value = ParseInteger(Data, Offset); PrintAttribute(Tag, Value, "Unspecified Tags UNDEFINED"); } void ARMAttributeParser::ParseIndexList(const uint8_t *Data, uint32_t &Offset, SmallVectorImpl<uint8_t> &IndexList) { for (;;) { unsigned Length; uint64_t Value = decodeULEB128(Data + Offset, &Length); Offset = Offset + Length; if (Value == 0) break; IndexList.push_back(Value); } } void ARMAttributeParser::ParseAttributeList(const uint8_t *Data, uint32_t &Offset, uint32_t Length) { while (Offset < Length) { unsigned Length; uint64_t Tag = decodeULEB128(Data + Offset, &Length); Offset += Length; bool Handled = false; for (unsigned AHI = 0, AHE = array_lengthof(DisplayRoutines); AHI != AHE && !Handled; ++AHI) { if (DisplayRoutines[AHI].Attribute == Tag) { (this->*DisplayRoutines[AHI].Routine)(ARMBuildAttrs::AttrType(Tag), Data, Offset); Handled = true; break; } } if (!Handled) { if (Tag < 32) { errs() << "unhandled AEABI Tag " << Tag << " (" << ARMBuildAttrs::AttrTypeAsString(Tag) << ")\n"; continue; } if (Tag % 2 == 0) IntegerAttribute(ARMBuildAttrs::AttrType(Tag), Data, Offset); else StringAttribute(ARMBuildAttrs::AttrType(Tag), Data, Offset); } } } void ARMAttributeParser::ParseSubsection(const uint8_t *Data, uint32_t Length) { uint32_t Offset = sizeof(uint32_t); /* SectionLength */ SW.printNumber("SectionLength", Length); const char *VendorName = reinterpret_cast<const char*>(Data + Offset); size_t VendorNameLength = std::strlen(VendorName); SW.printString("Vendor", StringRef(VendorName, VendorNameLength)); Offset = Offset + VendorNameLength + 1; if (StringRef(VendorName, VendorNameLength).lower() != "aeabi") return; while (Offset < Length) { /// Tag_File | Tag_Section | Tag_Symbol uleb128:byte-size uint8_t Tag = Data[Offset]; SW.printEnum("Tag", Tag, makeArrayRef(TagNames)); Offset = Offset + sizeof(Tag); uint32_t Size = *reinterpret_cast<const support::ulittle32_t*>(Data + Offset); SW.printNumber("Size", Size); Offset = Offset + sizeof(Size); if (Size > Length) { errs() << "subsection length greater than section length\n"; return; } StringRef ScopeName, IndexName; SmallVector<uint8_t, 8> Indicies; switch (Tag) { case ARMBuildAttrs::File: ScopeName = "FileAttributes"; break; case ARMBuildAttrs::Section: ScopeName = "SectionAttributes"; IndexName = "Sections"; ParseIndexList(Data, Offset, Indicies); break; case ARMBuildAttrs::Symbol: ScopeName = "SymbolAttributes"; IndexName = "Symbols"; ParseIndexList(Data, Offset, Indicies); break; default: errs() << "unrecognised tag: 0x" << utohexstr(Tag) << '\n'; return; } DictScope ASS(SW, ScopeName); if (!Indicies.empty()) SW.printList(IndexName, Indicies); ParseAttributeList(Data, Offset, Length); } } void ARMAttributeParser::Parse(ArrayRef<uint8_t> Section) { size_t Offset = 1; unsigned SectionNumber = 0; while (Offset < Section.size()) { uint32_t SectionLength = *reinterpret_cast<const support::ulittle32_t*>(Section.data() + Offset); SW.startLine() << "Section " << ++SectionNumber << " {\n"; SW.indent(); ParseSubsection(Section.data() + Offset, SectionLength); Offset = Offset + SectionLength; SW.unindent(); SW.startLine() << "}\n"; } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/Error.cpp
//===- Error.cpp - system_error extensions for llvm-readobj -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines a new error_category for the llvm-readobj tool. // //===----------------------------------------------------------------------===// #include "Error.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class _readobj_error_category : public std::error_category { public: const char* name() const LLVM_NOEXCEPT override; std::string message(int ev) const override; }; } // namespace const char *_readobj_error_category::name() const LLVM_NOEXCEPT { return "llvm.readobj"; } std::string _readobj_error_category::message(int EV) const { switch (static_cast<readobj_error>(EV)) { case readobj_error::success: return "Success"; case readobj_error::file_not_found: return "No such file."; case readobj_error::unsupported_file_format: return "The file was not recognized as a valid object file."; case readobj_error::unrecognized_file_format: return "Unrecognized file type."; case readobj_error::unsupported_obj_file_format: return "Unsupported object file format."; case readobj_error::unknown_symbol: return "Unknown symbol."; } llvm_unreachable("An enumerator of readobj_error does not have a message " "defined."); } namespace llvm { const std::error_category &readobj_category() { static _readobj_error_category o; return o; } } // namespace llvm
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/Win64EHDumper.cpp
//===- Win64EHDumper.cpp - Win64 EH Printer ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Win64EHDumper.h" #include "llvm-readobj.h" #include "llvm/Object/COFF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace llvm::object; using namespace llvm::Win64EH; static const EnumEntry<unsigned> UnwindFlags[] = { { "ExceptionHandler", UNW_ExceptionHandler }, { "TerminateHandler", UNW_TerminateHandler }, { "ChainInfo" , UNW_ChainInfo } }; static const EnumEntry<unsigned> UnwindOpInfo[] = { { "RAX", 0 }, { "RCX", 1 }, { "RDX", 2 }, { "RBX", 3 }, { "RSP", 4 }, { "RBP", 5 }, { "RSI", 6 }, { "RDI", 7 }, { "R8", 8 }, { "R9", 9 }, { "R10", 10 }, { "R11", 11 }, { "R12", 12 }, { "R13", 13 }, { "R14", 14 }, { "R15", 15 } }; static uint64_t getOffsetOfLSDA(const UnwindInfo& UI) { return static_cast<const char*>(UI.getLanguageSpecificData()) - reinterpret_cast<const char*>(&UI); } static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UC) { if (UC.size() < 3) return 0; return UC[1].FrameOffset + (static_cast<uint32_t>(UC[2].FrameOffset) << 16); } // Returns the name of the unwind code. static StringRef getUnwindCodeTypeName(uint8_t Code) { switch (Code) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: return "PUSH_NONVOL"; case UOP_AllocLarge: return "ALLOC_LARGE"; case UOP_AllocSmall: return "ALLOC_SMALL"; case UOP_SetFPReg: return "SET_FPREG"; case UOP_SaveNonVol: return "SAVE_NONVOL"; case UOP_SaveNonVolBig: return "SAVE_NONVOL_FAR"; case UOP_SaveXMM128: return "SAVE_XMM128"; case UOP_SaveXMM128Big: return "SAVE_XMM128_FAR"; case UOP_PushMachFrame: return "PUSH_MACHFRAME"; } } // Returns the name of a referenced register. static StringRef getUnwindRegisterName(uint8_t Reg) { switch (Reg) { default: llvm_unreachable("Invalid register"); case 0: return "RAX"; case 1: return "RCX"; case 2: return "RDX"; case 3: return "RBX"; case 4: return "RSP"; case 5: return "RBP"; case 6: return "RSI"; case 7: return "RDI"; case 8: return "R8"; case 9: return "R9"; case 10: return "R10"; case 11: return "R11"; case 12: return "R12"; case 13: return "R13"; case 14: return "R14"; case 15: return "R15"; } } // Calculates the number of array slots required for the unwind code. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) { switch (UnwindCode.getUnwindOp()) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: case UOP_AllocSmall: case UOP_SetFPReg: case UOP_PushMachFrame: return 1; case UOP_SaveNonVol: case UOP_SaveXMM128: return 2; case UOP_SaveNonVolBig: case UOP_SaveXMM128Big: return 3; case UOP_AllocLarge: return (UnwindCode.getOpInfo() == 0) ? 2 : 3; } } static std::string formatSymbol(const Dumper::Context &Ctx, const coff_section *Section, uint64_t Offset, uint32_t Displacement) { std::string Buffer; raw_string_ostream OS(Buffer); SymbolRef Symbol; if (!Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) { if (ErrorOr<StringRef> Name = Symbol.getName()) { OS << *Name; if (Displacement > 0) OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset); else OS << format(" (0x%" PRIX64 ")", Offset); return OS.str(); } } OS << format(" (0x%" PRIX64 ")", Offset); return OS.str(); } static std::error_code resolveRelocation(const Dumper::Context &Ctx, const coff_section *Section, uint64_t Offset, const coff_section *&ResolvedSection, uint64_t &ResolvedAddress) { SymbolRef Symbol; if (std::error_code EC = Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) return EC; ErrorOr<uint64_t> ResolvedAddressOrErr = Symbol.getAddress(); if (std::error_code EC = ResolvedAddressOrErr.getError()) return EC; ResolvedAddress = *ResolvedAddressOrErr; section_iterator SI = Ctx.COFF.section_begin(); if (std::error_code EC = Symbol.getSection(SI)) return EC; ResolvedSection = Ctx.COFF.getCOFFSection(*SI); return std::error_code(); } namespace llvm { namespace Win64EH { void Dumper::printRuntimeFunctionEntry(const Context &Ctx, const coff_section *Section, uint64_t Offset, const RuntimeFunction &RF) { SW.printString("StartAddress", formatSymbol(Ctx, Section, Offset + 0, RF.StartAddress)); SW.printString("EndAddress", formatSymbol(Ctx, Section, Offset + 4, RF.EndAddress)); SW.printString("UnwindInfoAddress", formatSymbol(Ctx, Section, Offset + 8, RF.UnwindInfoOffset)); } // Prints one unwind code. Because an unwind code can occupy up to 3 slots in // the unwind codes array, this function requires that the correct number of // slots is provided. void Dumper::printUnwindCode(const UnwindInfo& UI, ArrayRef<UnwindCode> UC) { assert(UC.size() >= getNumUsedSlots(UC[0])); SW.startLine() << format("0x%02X: ", unsigned(UC[0].u.CodeOffset)) << getUnwindCodeTypeName(UC[0].getUnwindOp()); switch (UC[0].getUnwindOp()) { case UOP_PushNonVol: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()); break; case UOP_AllocLarge: OS << " size=" << ((UC[0].getOpInfo() == 0) ? UC[1].FrameOffset * 8 : getLargeSlotValue(UC)); break; case UOP_AllocSmall: OS << " size=" << (UC[0].getOpInfo() + 1) * 8; break; case UOP_SetFPReg: if (UI.getFrameRegister() == 0) OS << " reg=<invalid>"; else OS << " reg=" << getUnwindRegisterName(UI.getFrameRegister()) << format(", offset=0x%X", UI.getFrameOffset() * 16); break; case UOP_SaveNonVol: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()) << format(", offset=0x%X", UC[1].FrameOffset * 8); break; case UOP_SaveNonVolBig: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()) << format(", offset=0x%X", getLargeSlotValue(UC)); break; case UOP_SaveXMM128: OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo()) << format(", offset=0x%X", UC[1].FrameOffset * 16); break; case UOP_SaveXMM128Big: OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo()) << format(", offset=0x%X", getLargeSlotValue(UC)); break; case UOP_PushMachFrame: OS << " errcode=" << (UC[0].getOpInfo() == 0 ? "no" : "yes"); break; } OS << "\n"; } void Dumper::printUnwindInfo(const Context &Ctx, const coff_section *Section, off_t Offset, const UnwindInfo &UI) { DictScope UIS(SW, "UnwindInfo"); SW.printNumber("Version", UI.getVersion()); SW.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags)); SW.printNumber("PrologSize", UI.PrologSize); if (UI.getFrameRegister()) { SW.printEnum("FrameRegister", UI.getFrameRegister(), makeArrayRef(UnwindOpInfo)); SW.printHex("FrameOffset", UI.getFrameOffset()); } else { SW.printString("FrameRegister", StringRef("-")); SW.printString("FrameOffset", StringRef("-")); } SW.printNumber("UnwindCodeCount", UI.NumCodes); { ListScope UCS(SW, "UnwindCodes"); ArrayRef<UnwindCode> UC(&UI.UnwindCodes[0], UI.NumCodes); for (const UnwindCode *UCI = UC.begin(), *UCE = UC.end(); UCI < UCE; ++UCI) { unsigned UsedSlots = getNumUsedSlots(*UCI); if (UsedSlots > UC.size()) { errs() << "corrupt unwind data"; return; } printUnwindCode(UI, ArrayRef<UnwindCode>(UCI, UCE)); UCI = UCI + UsedSlots - 1; } } uint64_t LSDAOffset = Offset + getOffsetOfLSDA(UI); if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) { SW.printString("Handler", formatSymbol(Ctx, Section, LSDAOffset, UI.getLanguageSpecificHandlerOffset())); } else if (UI.getFlags() & UNW_ChainInfo) { if (const RuntimeFunction *Chained = UI.getChainedFunctionEntry()) { DictScope CS(SW, "Chained"); printRuntimeFunctionEntry(Ctx, Section, LSDAOffset, *Chained); } } } void Dumper::printRuntimeFunction(const Context &Ctx, const coff_section *Section, uint64_t SectionOffset, const RuntimeFunction &RF) { DictScope RFS(SW, "RuntimeFunction"); printRuntimeFunctionEntry(Ctx, Section, SectionOffset, RF); const coff_section *XData; uint64_t Offset; if (error(resolveRelocation(Ctx, Section, SectionOffset + 8, XData, Offset))) return; ArrayRef<uint8_t> Contents; if (error(Ctx.COFF.getSectionContents(XData, Contents)) || Contents.empty()) return; Offset = Offset + RF.UnwindInfoOffset; if (Offset > Contents.size()) return; const auto UI = reinterpret_cast<const UnwindInfo*>(Contents.data() + Offset); printUnwindInfo(Ctx, XData, Offset, *UI); } void Dumper::printData(const Context &Ctx) { for (const auto &Section : Ctx.COFF.sections()) { StringRef Name; if (error(Section.getName(Name))) continue; if (Name != ".pdata" && !Name.startswith(".pdata$")) continue; const coff_section *PData = Ctx.COFF.getCOFFSection(Section); ArrayRef<uint8_t> Contents; if (error(Ctx.COFF.getSectionContents(PData, Contents)) || Contents.empty()) continue; const RuntimeFunction *Entries = reinterpret_cast<const RuntimeFunction *>(Contents.data()); const size_t Count = Contents.size() / sizeof(RuntimeFunction); ArrayRef<RuntimeFunction> RuntimeFunctions(Entries, Count); size_t Index = 0; for (const auto &RF : RuntimeFunctions) { printRuntimeFunction(Ctx, Ctx.COFF.getCOFFSection(Section), Index * sizeof(RuntimeFunction), RF); ++Index; } } } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/MachODumper.cpp
//===-- MachODump.cpp - Object file dumping utility for llvm --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MachO-specific dumper for llvm-readobj. // //===----------------------------------------------------------------------===// #include "llvm-readobj.h" #include "Error.h" #include "ObjDumper.h" #include "StackMapPrinter.h" #include "StreamWriter.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Casting.h" using namespace llvm; using namespace object; namespace { class MachODumper : public ObjDumper { public: MachODumper(const MachOObjectFile *Obj, StreamWriter& Writer) : ObjDumper(Writer) , Obj(Obj) { } void printFileHeaders() override; void printSections() override; void printRelocations() override; void printSymbols() override; void printDynamicSymbols() override; void printUnwindInfo() override; void printStackMap() const override; private: template<class MachHeader> void printFileHeaders(const MachHeader &Header); void printSymbol(const SymbolRef &Symbol); void printRelocation(const RelocationRef &Reloc); void printRelocation(const MachOObjectFile *Obj, const RelocationRef &Reloc); void printSections(const MachOObjectFile *Obj); const MachOObjectFile *Obj; }; } // namespace namespace llvm { std::error_code createMachODumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result) { const MachOObjectFile *MachOObj = dyn_cast<MachOObjectFile>(Obj); if (!MachOObj) return readobj_error::unsupported_obj_file_format; Result.reset(new MachODumper(MachOObj, Writer)); return readobj_error::success; } } // namespace llvm static const EnumEntry<uint32_t> MachOMagics[] = { { "Magic", MachO::MH_MAGIC }, { "Cigam", MachO::MH_CIGAM }, { "Magic64", MachO::MH_MAGIC_64 }, { "Cigam64", MachO::MH_CIGAM_64 }, { "FatMagic", MachO::FAT_MAGIC }, { "FatCigam", MachO::FAT_CIGAM }, }; static const EnumEntry<uint32_t> MachOHeaderFileTypes[] = { { "Relocatable", MachO::MH_OBJECT }, { "Executable", MachO::MH_EXECUTE }, { "FixedVMLibrary", MachO::MH_FVMLIB }, { "Core", MachO::MH_CORE }, { "PreloadedExecutable", MachO::MH_PRELOAD }, { "DynamicLibrary", MachO::MH_DYLIB }, { "DynamicLinker", MachO::MH_DYLINKER }, { "Bundle", MachO::MH_BUNDLE }, { "DynamicLibraryStub", MachO::MH_DYLIB_STUB }, { "DWARFSymbol", MachO::MH_DSYM }, { "KextBundle", MachO::MH_KEXT_BUNDLE }, }; static const EnumEntry<uint32_t> MachOHeaderCpuTypes[] = { { "Any" , static_cast<uint32_t>(MachO::CPU_TYPE_ANY) }, { "X86" , MachO::CPU_TYPE_X86 }, { "X86-64" , MachO::CPU_TYPE_X86_64 }, { "Mc98000" , MachO::CPU_TYPE_MC98000 }, { "Arm" , MachO::CPU_TYPE_ARM }, { "Arm64" , MachO::CPU_TYPE_ARM64 }, { "Sparc" , MachO::CPU_TYPE_SPARC }, { "PowerPC" , MachO::CPU_TYPE_POWERPC }, { "PowerPC64" , MachO::CPU_TYPE_POWERPC64 }, }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesX86[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_I386_ALL), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_386), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_486), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_486SX), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_586), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTPRO), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTII_M3), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTII_M5), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_CELERON), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_CELERON_MOBILE), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3_M), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3_XEON), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_M), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_4), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_4_M), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ITANIUM), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ITANIUM_2), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_XEON), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_XEON_MP), }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesX64[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_64_ALL), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_ARCH1), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_64_H), }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesARM[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_ALL), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V4T), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V6), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V5), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V5TEJ), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_XSCALE), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7S), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7K), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V6M), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7M), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7EM), }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesARM64[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM64_ALL), }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesSPARC[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_SPARC_ALL), }; static const EnumEntry<uint32_t> MachOHeaderCpuSubtypesPPC[] = { LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_ALL), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_601), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_602), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603e), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603ev), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_604), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_604e), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_620), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_750), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_7400), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_7450), LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_970), }; static const EnumEntry<uint32_t> MachOHeaderFlags[] = { LLVM_READOBJ_ENUM_ENT(MachO, MH_NOUNDEFS), LLVM_READOBJ_ENUM_ENT(MachO, MH_INCRLINK), LLVM_READOBJ_ENUM_ENT(MachO, MH_DYLDLINK), LLVM_READOBJ_ENUM_ENT(MachO, MH_BINDATLOAD), LLVM_READOBJ_ENUM_ENT(MachO, MH_PREBOUND), LLVM_READOBJ_ENUM_ENT(MachO, MH_SPLIT_SEGS), LLVM_READOBJ_ENUM_ENT(MachO, MH_LAZY_INIT), LLVM_READOBJ_ENUM_ENT(MachO, MH_TWOLEVEL), LLVM_READOBJ_ENUM_ENT(MachO, MH_FORCE_FLAT), LLVM_READOBJ_ENUM_ENT(MachO, MH_NOMULTIDEFS), LLVM_READOBJ_ENUM_ENT(MachO, MH_NOFIXPREBINDING), LLVM_READOBJ_ENUM_ENT(MachO, MH_PREBINDABLE), LLVM_READOBJ_ENUM_ENT(MachO, MH_ALLMODSBOUND), LLVM_READOBJ_ENUM_ENT(MachO, MH_SUBSECTIONS_VIA_SYMBOLS), LLVM_READOBJ_ENUM_ENT(MachO, MH_CANONICAL), LLVM_READOBJ_ENUM_ENT(MachO, MH_WEAK_DEFINES), LLVM_READOBJ_ENUM_ENT(MachO, MH_BINDS_TO_WEAK), LLVM_READOBJ_ENUM_ENT(MachO, MH_ALLOW_STACK_EXECUTION), LLVM_READOBJ_ENUM_ENT(MachO, MH_ROOT_SAFE), LLVM_READOBJ_ENUM_ENT(MachO, MH_SETUID_SAFE), LLVM_READOBJ_ENUM_ENT(MachO, MH_NO_REEXPORTED_DYLIBS), LLVM_READOBJ_ENUM_ENT(MachO, MH_PIE), LLVM_READOBJ_ENUM_ENT(MachO, MH_DEAD_STRIPPABLE_DYLIB), LLVM_READOBJ_ENUM_ENT(MachO, MH_HAS_TLV_DESCRIPTORS), LLVM_READOBJ_ENUM_ENT(MachO, MH_NO_HEAP_EXECUTION), LLVM_READOBJ_ENUM_ENT(MachO, MH_APP_EXTENSION_SAFE), }; static const EnumEntry<unsigned> MachOSectionAttributes[] = { { "LocReloc" , 1 << 0 /*S_ATTR_LOC_RELOC */ }, { "ExtReloc" , 1 << 1 /*S_ATTR_EXT_RELOC */ }, { "SomeInstructions" , 1 << 2 /*S_ATTR_SOME_INSTRUCTIONS */ }, { "Debug" , 1 << 17 /*S_ATTR_DEBUG */ }, { "SelfModifyingCode", 1 << 18 /*S_ATTR_SELF_MODIFYING_CODE*/ }, { "LiveSupport" , 1 << 19 /*S_ATTR_LIVE_SUPPORT */ }, { "NoDeadStrip" , 1 << 20 /*S_ATTR_NO_DEAD_STRIP */ }, { "StripStaticSyms" , 1 << 21 /*S_ATTR_STRIP_STATIC_SYMS */ }, { "NoTOC" , 1 << 22 /*S_ATTR_NO_TOC */ }, { "PureInstructions" , 1 << 23 /*S_ATTR_PURE_INSTRUCTIONS */ }, }; static const EnumEntry<unsigned> MachOSymbolRefTypes[] = { { "UndefinedNonLazy", 0 }, { "ReferenceFlagUndefinedLazy", 1 }, { "ReferenceFlagDefined", 2 }, { "ReferenceFlagPrivateDefined", 3 }, { "ReferenceFlagPrivateUndefinedNonLazy", 4 }, { "ReferenceFlagPrivateUndefinedLazy", 5 } }; static const EnumEntry<unsigned> MachOSymbolFlags[] = { { "ReferencedDynamically", 0x10 }, { "NoDeadStrip", 0x20 }, { "WeakRef", 0x40 }, { "WeakDef", 0x80 } }; static const EnumEntry<unsigned> MachOSymbolTypes[] = { { "Undef", 0x0 }, { "Abs", 0x2 }, { "Indirect", 0xA }, { "PreboundUndef", 0xC }, { "Section", 0xE } }; namespace { struct MachOSection { ArrayRef<char> Name; ArrayRef<char> SegmentName; uint64_t Address; uint64_t Size; uint32_t Offset; uint32_t Alignment; uint32_t RelocationTableOffset; uint32_t NumRelocationTableEntries; uint32_t Flags; uint32_t Reserved1; uint32_t Reserved2; }; struct MachOSymbol { uint32_t StringIndex; uint8_t Type; uint8_t SectionIndex; uint16_t Flags; uint64_t Value; }; } static void getSection(const MachOObjectFile *Obj, DataRefImpl Sec, MachOSection &Section) { if (!Obj->is64Bit()) { MachO::section Sect = Obj->getSection(Sec); Section.Address = Sect.addr; Section.Size = Sect.size; Section.Offset = Sect.offset; Section.Alignment = Sect.align; Section.RelocationTableOffset = Sect.reloff; Section.NumRelocationTableEntries = Sect.nreloc; Section.Flags = Sect.flags; Section.Reserved1 = Sect.reserved1; Section.Reserved2 = Sect.reserved2; return; } MachO::section_64 Sect = Obj->getSection64(Sec); Section.Address = Sect.addr; Section.Size = Sect.size; Section.Offset = Sect.offset; Section.Alignment = Sect.align; Section.RelocationTableOffset = Sect.reloff; Section.NumRelocationTableEntries = Sect.nreloc; Section.Flags = Sect.flags; Section.Reserved1 = Sect.reserved1; Section.Reserved2 = Sect.reserved2; } static void getSymbol(const MachOObjectFile *Obj, DataRefImpl DRI, MachOSymbol &Symbol) { if (!Obj->is64Bit()) { MachO::nlist Entry = Obj->getSymbolTableEntry(DRI); Symbol.StringIndex = Entry.n_strx; Symbol.Type = Entry.n_type; Symbol.SectionIndex = Entry.n_sect; Symbol.Flags = Entry.n_desc; Symbol.Value = Entry.n_value; return; } MachO::nlist_64 Entry = Obj->getSymbol64TableEntry(DRI); Symbol.StringIndex = Entry.n_strx; Symbol.Type = Entry.n_type; Symbol.SectionIndex = Entry.n_sect; Symbol.Flags = Entry.n_desc; Symbol.Value = Entry.n_value; } void MachODumper::printFileHeaders() { DictScope H(W, "MachHeader"); if (!Obj->is64Bit()) { printFileHeaders(Obj->getHeader()); } else { printFileHeaders(Obj->getHeader64()); W.printHex("Reserved", Obj->getHeader64().reserved); } } template<class MachHeader> void MachODumper::printFileHeaders(const MachHeader &Header) { W.printEnum("Magic", Header.magic, makeArrayRef(MachOMagics)); W.printEnum("CpuType", Header.cputype, makeArrayRef(MachOHeaderCpuTypes)); uint32_t subtype = Header.cpusubtype & ~MachO::CPU_SUBTYPE_MASK; switch (Header.cputype) { case MachO::CPU_TYPE_X86: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesX86)); break; case MachO::CPU_TYPE_X86_64: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesX64)); break; case MachO::CPU_TYPE_ARM: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesARM)); break; case MachO::CPU_TYPE_POWERPC: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesPPC)); break; case MachO::CPU_TYPE_SPARC: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesSPARC)); break; case MachO::CPU_TYPE_ARM64: W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesARM64)); break; case MachO::CPU_TYPE_POWERPC64: default: W.printHex("CpuSubtype", subtype); } W.printEnum("FileType", Header.filetype, makeArrayRef(MachOHeaderFileTypes)); W.printNumber("NumOfLoadCommands", Header.ncmds); W.printNumber("SizeOfLoadCommands", Header.sizeofcmds); W.printFlags("Flags", Header.flags, makeArrayRef(MachOHeaderFlags)); } void MachODumper::printSections() { return printSections(Obj); } void MachODumper::printSections(const MachOObjectFile *Obj) { ListScope Group(W, "Sections"); int SectionIndex = -1; for (const SectionRef &Section : Obj->sections()) { ++SectionIndex; MachOSection MOSection; getSection(Obj, Section.getRawDataRefImpl(), MOSection); DataRefImpl DR = Section.getRawDataRefImpl(); StringRef Name; if (error(Section.getName(Name))) Name = ""; ArrayRef<char> RawName = Obj->getSectionRawName(DR); StringRef SegmentName = Obj->getSectionFinalSegmentName(DR); ArrayRef<char> RawSegmentName = Obj->getSectionRawFinalSegmentName(DR); DictScope SectionD(W, "Section"); W.printNumber("Index", SectionIndex); W.printBinary("Name", Name, RawName); W.printBinary("Segment", SegmentName, RawSegmentName); W.printHex("Address", MOSection.Address); W.printHex("Size", MOSection.Size); W.printNumber("Offset", MOSection.Offset); W.printNumber("Alignment", MOSection.Alignment); W.printHex("RelocationOffset", MOSection.RelocationTableOffset); W.printNumber("RelocationCount", MOSection.NumRelocationTableEntries); W.printEnum("Type", MOSection.Flags & 0xFF, makeArrayRef(MachOSectionAttributes)); W.printFlags("Attributes", MOSection.Flags >> 8, makeArrayRef(MachOSectionAttributes)); W.printHex("Reserved1", MOSection.Reserved1); W.printHex("Reserved2", MOSection.Reserved2); if (opts::SectionRelocations) { ListScope D(W, "Relocations"); for (const RelocationRef &Reloc : Section.relocations()) printRelocation(Reloc); } if (opts::SectionSymbols) { ListScope D(W, "Symbols"); for (const SymbolRef &Symbol : Obj->symbols()) { if (!Section.containsSymbol(Symbol)) continue; printSymbol(Symbol); } } if (opts::SectionData) { bool IsBSS = Section.isBSS(); if (!IsBSS) { StringRef Data; if (error(Section.getContents(Data))) break; W.printBinaryBlock("SectionData", Data); } } } } void MachODumper::printRelocations() { ListScope D(W, "Relocations"); std::error_code EC; for (const SectionRef &Section : Obj->sections()) { StringRef Name; if (error(Section.getName(Name))) continue; bool PrintedGroup = false; for (const RelocationRef &Reloc : Section.relocations()) { if (!PrintedGroup) { W.startLine() << "Section " << Name << " {\n"; W.indent(); PrintedGroup = true; } printRelocation(Reloc); } if (PrintedGroup) { W.unindent(); W.startLine() << "}\n"; } } } void MachODumper::printRelocation(const RelocationRef &Reloc) { return printRelocation(Obj, Reloc); } void MachODumper::printRelocation(const MachOObjectFile *Obj, const RelocationRef &Reloc) { uint64_t Offset = Reloc.getOffset(); SmallString<32> RelocName; Reloc.getTypeName(RelocName); DataRefImpl DR = Reloc.getRawDataRefImpl(); MachO::any_relocation_info RE = Obj->getRelocation(DR); bool IsScattered = Obj->isRelocationScattered(RE); bool IsExtern = !IsScattered && Obj->getPlainRelocationExternal(RE); StringRef TargetName; if (IsExtern) { symbol_iterator Symbol = Reloc.getSymbol(); if (Symbol != Obj->symbol_end()) { ErrorOr<StringRef> TargetNameOrErr = Symbol->getName(); if (error(TargetNameOrErr.getError())) return; TargetName = *TargetNameOrErr; } } else if (!IsScattered) { section_iterator SecI = Obj->getRelocationSection(DR); if (SecI != Obj->section_end()) { if (error(SecI->getName(TargetName))) return; } } if (TargetName.empty()) TargetName = "-"; if (opts::ExpandRelocs) { DictScope Group(W, "Relocation"); W.printHex("Offset", Offset); W.printNumber("PCRel", Obj->getAnyRelocationPCRel(RE)); W.printNumber("Length", Obj->getAnyRelocationLength(RE)); W.printNumber("Type", RelocName, Obj->getAnyRelocationType(RE)); if (IsScattered) { W.printHex("Value", Obj->getScatteredRelocationValue(RE)); } else { const char *Kind = IsExtern ? "Symbol" : "Section"; W.printNumber(Kind, TargetName, Obj->getPlainRelocationSymbolNum(RE)); } } else { SmallString<32> SymbolNameOrOffset("0x"); if (IsScattered) { // Scattered relocations don't really have an associated symbol for some // reason, even if one exists in the symtab at the correct address. SymbolNameOrOffset += utohexstr(Obj->getScatteredRelocationValue(RE)); } else { SymbolNameOrOffset = TargetName; } raw_ostream& OS = W.startLine(); OS << W.hex(Offset) << " " << Obj->getAnyRelocationPCRel(RE) << " " << Obj->getAnyRelocationLength(RE); if (IsScattered) OS << " n/a"; else OS << " " << Obj->getPlainRelocationExternal(RE); OS << " " << RelocName << " " << IsScattered << " " << SymbolNameOrOffset << "\n"; } } void MachODumper::printSymbols() { ListScope Group(W, "Symbols"); for (const SymbolRef &Symbol : Obj->symbols()) { printSymbol(Symbol); } } void MachODumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); } void MachODumper::printSymbol(const SymbolRef &Symbol) { StringRef SymbolName; if (ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName()) SymbolName = *SymbolNameOrErr; MachOSymbol MOSymbol; getSymbol(Obj, Symbol.getRawDataRefImpl(), MOSymbol); StringRef SectionName = ""; section_iterator SecI(Obj->section_begin()); if (!error(Symbol.getSection(SecI)) && SecI != Obj->section_end()) error(SecI->getName(SectionName)); DictScope D(W, "Symbol"); W.printNumber("Name", SymbolName, MOSymbol.StringIndex); if (MOSymbol.Type & MachO::N_STAB) { W.printHex("Type", "SymDebugTable", MOSymbol.Type); } else { if (MOSymbol.Type & MachO::N_PEXT) W.startLine() << "PrivateExtern\n"; if (MOSymbol.Type & MachO::N_EXT) W.startLine() << "Extern\n"; W.printEnum("Type", uint8_t(MOSymbol.Type & MachO::N_TYPE), makeArrayRef(MachOSymbolTypes)); } W.printHex("Section", SectionName, MOSymbol.SectionIndex); W.printEnum("RefType", static_cast<uint16_t>(MOSymbol.Flags & 0xF), makeArrayRef(MachOSymbolRefTypes)); W.printFlags("Flags", static_cast<uint16_t>(MOSymbol.Flags & ~0xF), makeArrayRef(MachOSymbolFlags)); W.printHex("Value", MOSymbol.Value); } void MachODumper::printUnwindInfo() { W.startLine() << "UnwindInfo not implemented.\n"; } void MachODumper::printStackMap() const { object::SectionRef StackMapSection; for (auto Sec : Obj->sections()) { StringRef Name; Sec.getName(Name); if (Name == "__llvm_stackmaps") { StackMapSection = Sec; break; } } if (StackMapSection == object::SectionRef()) return; StringRef StackMapContents; StackMapSection.getContents(StackMapContents); ArrayRef<uint8_t> StackMapContentsArray( reinterpret_cast<const uint8_t*>(StackMapContents.data()), StackMapContents.size()); if (Obj->isLittleEndian()) prettyPrintStackMap( llvm::outs(), StackMapV1Parser<support::little>(StackMapContentsArray)); else prettyPrintStackMap(llvm::outs(), StackMapV1Parser<support::big>(StackMapContentsArray)); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/Win64EHDumper.h
//===- Win64EHDumper.h - Win64 EH Printing ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_WIN64EHDUMPER_H #define LLVM_TOOLS_LLVM_READOBJ_WIN64EHDUMPER_H #include "StreamWriter.h" #include "llvm/Support/Win64EH.h" namespace llvm { namespace object { class COFFObjectFile; class SymbolRef; struct coff_section; } namespace Win64EH { class Dumper { StreamWriter &SW; raw_ostream &OS; public: typedef std::error_code (*SymbolResolver)(const object::coff_section *, uint64_t, object::SymbolRef &, void *); struct Context { const object::COFFObjectFile &COFF; SymbolResolver ResolveSymbol; void *UserData; Context(const object::COFFObjectFile &COFF, SymbolResolver Resolver, void *UserData) : COFF(COFF), ResolveSymbol(Resolver), UserData(UserData) {} }; private: void printRuntimeFunctionEntry(const Context &Ctx, const object::coff_section *Section, uint64_t SectionOffset, const RuntimeFunction &RF); void printUnwindCode(const UnwindInfo& UI, ArrayRef<UnwindCode> UC); void printUnwindInfo(const Context &Ctx, const object::coff_section *Section, off_t Offset, const UnwindInfo &UI); void printRuntimeFunction(const Context &Ctx, const object::coff_section *Section, uint64_t SectionOffset, const RuntimeFunction &RF); public: Dumper(StreamWriter &SW) : SW(SW), OS(SW.getOStream()) {} void printData(const Context &Ctx); }; } } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/llvm-readobj.h
//===-- llvm-readobj.h ----------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_LLVM_READOBJ_H #define LLVM_TOOLS_LLVM_READOBJ_LLVM_READOBJ_H #include "llvm/Support/CommandLine.h" #include <string> namespace llvm { namespace object { class RelocationRef; } // Various helper functions. bool error(std::error_code ec); bool relocAddressLess(object::RelocationRef A, object::RelocationRef B); } // namespace llvm namespace opts { extern llvm::cl::list<std::string> InputFilenames; extern llvm::cl::opt<bool> FileHeaders; extern llvm::cl::opt<bool> Sections; extern llvm::cl::opt<bool> SectionRelocations; extern llvm::cl::opt<bool> SectionSymbols; extern llvm::cl::opt<bool> SectionData; extern llvm::cl::opt<bool> Relocations; extern llvm::cl::opt<bool> Symbols; extern llvm::cl::opt<bool> DynamicSymbols; extern llvm::cl::opt<bool> UnwindInfo; extern llvm::cl::opt<bool> ExpandRelocs; extern llvm::cl::opt<bool> CodeView; extern llvm::cl::opt<bool> CodeViewSubsectionBytes; extern llvm::cl::opt<bool> ARMAttributes; extern llvm::cl::opt<bool> MipsPLTGOT; } // namespace opts #define LLVM_READOBJ_ENUM_ENT(ns, enum) \ { #enum, ns::enum } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/COFFDumper.cpp
//===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the COFF-specific dumper for llvm-readobj. /// //===----------------------------------------------------------------------===// #include "llvm-readobj.h" #include "ARMWinEHPrinter.h" #include "Error.h" #include "ObjDumper.h" #include "StackMapPrinter.h" #include "StreamWriter.h" #include "Win64EHDumper.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Object/COFF.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/COFF.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/Format.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/Win64EH.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <system_error> #include <time.h> using namespace llvm; using namespace llvm::object; using namespace llvm::Win64EH; namespace { class COFFDumper : public ObjDumper { public: COFFDumper(const llvm::object::COFFObjectFile *Obj, StreamWriter& Writer) : ObjDumper(Writer) , Obj(Obj) { } void printFileHeaders() override; void printSections() override; void printRelocations() override; void printSymbols() override; void printDynamicSymbols() override; void printUnwindInfo() override; void printCOFFImports() override; void printCOFFExports() override; void printCOFFDirectives() override; void printCOFFBaseReloc() override; void printStackMap() const override; private: void printSymbol(const SymbolRef &Sym); void printRelocation(const SectionRef &Section, const RelocationRef &Reloc); void printDataDirectory(uint32_t Index, const std::string &FieldName); void printDOSHeader(const dos_header *DH); template <class PEHeader> void printPEHeader(const PEHeader *Hdr); void printBaseOfDataField(const pe32_header *Hdr); void printBaseOfDataField(const pe32plus_header *Hdr); void printCodeViewDebugInfo(const SectionRef &Section); void printCodeViewSymbolsSubsection(StringRef Subsection, const SectionRef &Section, uint32_t Offset); void cacheRelocations(); std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset, SymbolRef &Sym); std::error_code resolveSymbolName(const coff_section *Section, uint64_t Offset, StringRef &Name); void printImportedSymbols(iterator_range<imported_symbol_iterator> Range); void printDelayImportedSymbols( const DelayImportDirectoryEntryRef &I, iterator_range<imported_symbol_iterator> Range); typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy; const llvm::object::COFFObjectFile *Obj; bool RelocCached = false; RelocMapTy RelocMap; StringRef CVFileIndexToStringOffsetTable; StringRef CVStringTable; }; } // namespace namespace llvm { std::error_code createCOFFDumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result) { const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj); if (!COFFObj) return readobj_error::unsupported_obj_file_format; Result.reset(new COFFDumper(COFFObj, Writer)); return readobj_error::success; } } // namespace llvm // Given a a section and an offset into this section the function returns the // symbol used for the relocation at the offset. std::error_code COFFDumper::resolveSymbol(const coff_section *Section, uint64_t Offset, SymbolRef &Sym) { cacheRelocations(); const auto &Relocations = RelocMap[Section]; for (const auto &Relocation : Relocations) { uint64_t RelocationOffset = Relocation.getOffset(); if (RelocationOffset == Offset) { Sym = *Relocation.getSymbol(); return readobj_error::success; } } return readobj_error::unknown_symbol; } // Given a section and an offset into this section the function returns the name // of the symbol used for the relocation at the offset. std::error_code COFFDumper::resolveSymbolName(const coff_section *Section, uint64_t Offset, StringRef &Name) { SymbolRef Symbol; if (std::error_code EC = resolveSymbol(Section, Offset, Symbol)) return EC; ErrorOr<StringRef> NameOrErr = Symbol.getName(); if (std::error_code EC = NameOrErr.getError()) return EC; Name = *NameOrErr; return std::error_code(); } static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2) }; static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI ) }; static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ), }; static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE), }; static const EnumEntry<COFF::SectionCharacteristics> ImageSectionCharacteristics[] = { LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ), LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE ) }; static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = { { "Null" , COFF::IMAGE_SYM_TYPE_NULL }, { "Void" , COFF::IMAGE_SYM_TYPE_VOID }, { "Char" , COFF::IMAGE_SYM_TYPE_CHAR }, { "Short" , COFF::IMAGE_SYM_TYPE_SHORT }, { "Int" , COFF::IMAGE_SYM_TYPE_INT }, { "Long" , COFF::IMAGE_SYM_TYPE_LONG }, { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT }, { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE }, { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT }, { "Union" , COFF::IMAGE_SYM_TYPE_UNION }, { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM }, { "MOE" , COFF::IMAGE_SYM_TYPE_MOE }, { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE }, { "Word" , COFF::IMAGE_SYM_TYPE_WORD }, { "UInt" , COFF::IMAGE_SYM_TYPE_UINT }, { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD } }; static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = { { "Null" , COFF::IMAGE_SYM_DTYPE_NULL }, { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER }, { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION }, { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY } }; static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = { { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION }, { "Null" , COFF::IMAGE_SYM_CLASS_NULL }, { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC }, { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL }, { "Static" , COFF::IMAGE_SYM_CLASS_STATIC }, { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER }, { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF }, { "Label" , COFF::IMAGE_SYM_CLASS_LABEL }, { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL }, { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT }, { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT }, { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG }, { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION }, { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG }, { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION }, { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC }, { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG }, { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM }, { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM }, { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD }, { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK }, { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION }, { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT }, { "File" , COFF::IMAGE_SYM_CLASS_FILE }, { "Section" , COFF::IMAGE_SYM_CLASS_SECTION }, { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL }, { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN } }; static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = { { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES }, { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY }, { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE }, { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH }, { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE }, { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST }, { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST } }; static const EnumEntry<COFF::WeakExternalCharacteristics> WeakExternalCharacteristics[] = { { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY }, { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY }, { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS } }; template <typename T> static std::error_code getSymbolAuxData(const COFFObjectFile *Obj, COFFSymbolRef Symbol, uint8_t AuxSymbolIdx, const T *&Aux) { ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol); AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize()); Aux = reinterpret_cast<const T*>(AuxData.data()); return readobj_error::success; } void COFFDumper::cacheRelocations() { if (RelocCached) return; RelocCached = true; for (const SectionRef &S : Obj->sections()) { const coff_section *Section = Obj->getCOFFSection(S); for (const RelocationRef &Reloc : S.relocations()) RelocMap[Section].push_back(Reloc); // Sort relocations by address. std::sort(RelocMap[Section].begin(), RelocMap[Section].end(), relocAddressLess); } } void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) { const data_directory *Data; if (Obj->getDataDirectory(Index, Data)) return; W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress); W.printHex(FieldName + "Size", Data->Size); } void COFFDumper::printFileHeaders() { time_t TDS = Obj->getTimeDateStamp(); char FormattedTime[20] = { }; strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS)); { DictScope D(W, "ImageFileHeader"); W.printEnum ("Machine", Obj->getMachine(), makeArrayRef(ImageFileMachineType)); W.printNumber("SectionCount", Obj->getNumberOfSections()); W.printHex ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp()); W.printHex ("PointerToSymbolTable", Obj->getPointerToSymbolTable()); W.printNumber("SymbolCount", Obj->getNumberOfSymbols()); W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader()); W.printFlags ("Characteristics", Obj->getCharacteristics(), makeArrayRef(ImageFileCharacteristics)); } // Print PE header. This header does not exist if this is an object file and // not an executable. const pe32_header *PEHeader = nullptr; if (error(Obj->getPE32Header(PEHeader))) return; if (PEHeader) printPEHeader<pe32_header>(PEHeader); const pe32plus_header *PEPlusHeader = nullptr; if (error(Obj->getPE32PlusHeader(PEPlusHeader))) return; if (PEPlusHeader) printPEHeader<pe32plus_header>(PEPlusHeader); if (const dos_header *DH = Obj->getDOSHeader()) printDOSHeader(DH); } void COFFDumper::printDOSHeader(const dos_header *DH) { DictScope D(W, "DOSHeader"); W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic))); W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage); W.printNumber("FileSizeInPages", DH->FileSizeInPages); W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems); W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs); W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs); W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs); W.printNumber("InitialRelativeSS", DH->InitialRelativeSS); W.printNumber("InitialSP", DH->InitialSP); W.printNumber("Checksum", DH->Checksum); W.printNumber("InitialIP", DH->InitialIP); W.printNumber("InitialRelativeCS", DH->InitialRelativeCS); W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable); W.printNumber("OverlayNumber", DH->OverlayNumber); W.printNumber("OEMid", DH->OEMid); W.printNumber("OEMinfo", DH->OEMinfo); W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader); } template <class PEHeader> void COFFDumper::printPEHeader(const PEHeader *Hdr) { DictScope D(W, "ImageOptionalHeader"); W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion); W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion); W.printNumber("SizeOfCode", Hdr->SizeOfCode); W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData); W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData); W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint); W.printHex ("BaseOfCode", Hdr->BaseOfCode); printBaseOfDataField(Hdr); W.printHex ("ImageBase", Hdr->ImageBase); W.printNumber("SectionAlignment", Hdr->SectionAlignment); W.printNumber("FileAlignment", Hdr->FileAlignment); W.printNumber("MajorOperatingSystemVersion", Hdr->MajorOperatingSystemVersion); W.printNumber("MinorOperatingSystemVersion", Hdr->MinorOperatingSystemVersion); W.printNumber("MajorImageVersion", Hdr->MajorImageVersion); W.printNumber("MinorImageVersion", Hdr->MinorImageVersion); W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion); W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion); W.printNumber("SizeOfImage", Hdr->SizeOfImage); W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders); W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem)); W.printFlags ("Characteristics", Hdr->DLLCharacteristics, makeArrayRef(PEDLLCharacteristics)); W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve); W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit); W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve); W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit); W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize); if (Hdr->NumberOfRvaAndSize > 0) { DictScope D(W, "DataDirectory"); static const char * const directory[] = { "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable", "CertificateTable", "BaseRelocationTable", "Debug", "Architecture", "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT", "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved" }; for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) { printDataDirectory(i, directory[i]); } } } void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) { W.printHex("BaseOfData", Hdr->BaseOfData); } void COFFDumper::printBaseOfDataField(const pe32plus_header *) {} void COFFDumper::printCodeViewDebugInfo(const SectionRef &Section) { StringRef Data; if (error(Section.getContents(Data))) return; SmallVector<StringRef, 10> FunctionNames; StringMap<StringRef> FunctionLineTables; ListScope D(W, "CodeViewDebugInfo"); { // FIXME: Add more offset correctness checks. DataExtractor DE(Data, true, 4); uint32_t Offset = 0, Magic = DE.getU32(&Offset); W.printHex("Magic", Magic); if (Magic != COFF::DEBUG_SECTION_MAGIC) { error(object_error::parse_failed); return; } bool Finished = false; while (DE.isValidOffset(Offset) && !Finished) { // The section consists of a number of subsection in the following format: // |Type|PayloadSize|Payload...| uint32_t SubSectionType = DE.getU32(&Offset), PayloadSize = DE.getU32(&Offset); ListScope S(W, "Subsection"); W.printHex("Type", SubSectionType); W.printHex("PayloadSize", PayloadSize); if (PayloadSize > Data.size() - Offset) { error(object_error::parse_failed); return; } StringRef Contents = Data.substr(Offset, PayloadSize); if (opts::CodeViewSubsectionBytes) { // Print the raw contents to simplify debugging if anything goes wrong // afterwards. W.printBinaryBlock("Contents", Contents); } switch (SubSectionType) { case COFF::DEBUG_SYMBOL_SUBSECTION: if (opts::SectionSymbols) printCodeViewSymbolsSubsection(Contents, Section, Offset); break; case COFF::DEBUG_LINE_TABLE_SUBSECTION: { // Holds a PC to file:line table. Some data to parse this subsection is // stored in the other subsections, so just check sanity and store the // pointers for deferred processing. if (PayloadSize < 12) { // There should be at least three words to store two function // relocations and size of the code. error(object_error::parse_failed); return; } StringRef FunctionName; if (error(resolveSymbolName(Obj->getCOFFSection(Section), Offset, FunctionName))) return; W.printString("FunctionName", FunctionName); if (FunctionLineTables.count(FunctionName) != 0) { // Saw debug info for this function already? error(object_error::parse_failed); return; } FunctionLineTables[FunctionName] = Contents; FunctionNames.push_back(FunctionName); break; } case COFF::DEBUG_STRING_TABLE_SUBSECTION: if (PayloadSize == 0 || CVStringTable.data() != nullptr || Contents.back() != '\0') { // Empty or duplicate or non-null-terminated subsection. error(object_error::parse_failed); return; } CVStringTable = Contents; break; case COFF::DEBUG_INDEX_SUBSECTION: // Holds the translation table from file indices // to offsets in the string table. if (PayloadSize == 0 || CVFileIndexToStringOffsetTable.data() != nullptr) { // Empty or duplicate subsection. error(object_error::parse_failed); return; } CVFileIndexToStringOffsetTable = Contents; break; } Offset += PayloadSize; // Align the reading pointer by 4. Offset += (-Offset) % 4; } } // Dump the line tables now that we've read all the subsections and know all // the required information. for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) { StringRef Name = FunctionNames[I]; ListScope S(W, "FunctionLineTable"); W.printString("FunctionName", Name); DataExtractor DE(FunctionLineTables[Name], true, 4); uint32_t Offset = 6; // Skip relocations. uint16_t Flags = DE.getU16(&Offset); W.printHex("Flags", Flags); bool HasColumnInformation = Flags & COFF::DEBUG_LINE_TABLES_HAVE_COLUMN_RECORDS; uint32_t FunctionSize = DE.getU32(&Offset); W.printHex("CodeSize", FunctionSize); while (DE.isValidOffset(Offset)) { // For each range of lines with the same filename, we have a segment // in the line table. The filename string is accessed using double // indirection to the string table subsection using the index subsection. uint32_t OffsetInIndex = DE.getU32(&Offset), SegmentLength = DE.getU32(&Offset), FullSegmentSize = DE.getU32(&Offset); if (FullSegmentSize != 12 + 8 * SegmentLength + (HasColumnInformation ? 4 * SegmentLength : 0)) { error(object_error::parse_failed); return; } uint32_t FilenameOffset; { DataExtractor SDE(CVFileIndexToStringOffsetTable, true, 4); uint32_t OffsetInSDE = OffsetInIndex; if (!SDE.isValidOffset(OffsetInSDE)) { error(object_error::parse_failed); return; } FilenameOffset = SDE.getU32(&OffsetInSDE); } if (FilenameOffset == 0 || FilenameOffset + 1 >= CVStringTable.size() || CVStringTable.data()[FilenameOffset - 1] != '\0') { // Each string in an F3 subsection should be preceded by a null // character. error(object_error::parse_failed); return; } StringRef Filename(CVStringTable.data() + FilenameOffset); ListScope S(W, "FilenameSegment"); W.printString("Filename", Filename); for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset); ++J) { // Then go the (PC, LineNumber) pairs. The line number is stored in the // least significant 31 bits of the respective word in the table. uint32_t PC = DE.getU32(&Offset), LineNumber = DE.getU32(&Offset) & 0x7fffffff; if (PC >= FunctionSize) { error(object_error::parse_failed); return; } char Buffer[32]; format("+0x%X", PC).snprint(Buffer, 32); W.printNumber(Buffer, LineNumber); } if (HasColumnInformation) { for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset); ++J) { uint16_t ColStart = DE.getU16(&Offset); W.printNumber("ColStart", ColStart); uint16_t ColEnd = DE.getU16(&Offset); W.printNumber("ColEnd", ColEnd); } } } } } void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection, const SectionRef &Section, uint32_t OffsetInSection) { if (Subsection.size() == 0) { error(object_error::parse_failed); return; } DataExtractor DE(Subsection, true, 4); uint32_t Offset = 0; // Function-level subsections have "procedure start" and "procedure end" // commands that should come in pairs and surround relevant info. bool InFunctionScope = false; while (DE.isValidOffset(Offset)) { // Read subsection segments one by one. uint16_t Size = DE.getU16(&Offset); // The section size includes the size of the type identifier. if (Size < 2 || !DE.isValidOffsetForDataOfSize(Offset, Size)) { error(object_error::parse_failed); return; } Size -= 2; uint16_t Type = DE.getU16(&Offset); switch (Type) { case COFF::DEBUG_SYMBOL_TYPE_PROC_START: { DictScope S(W, "ProcStart"); if (InFunctionScope || Size < 36) { error(object_error::parse_failed); return; } InFunctionScope = true; // We're currently interested in a limited subset of fields in this // segment, just ignore the rest of the fields for now. uint8_t Unused[12]; DE.getU8(&Offset, Unused, 12); uint32_t CodeSize = DE.getU32(&Offset); DE.getU8(&Offset, Unused, 12); StringRef SectionName; if (error(resolveSymbolName(Obj->getCOFFSection(Section), OffsetInSection + Offset, SectionName))) return; Offset += 4; DE.getU8(&Offset, Unused, 3); StringRef DisplayName = DE.getCStr(&Offset); if (!DE.isValidOffset(Offset)) { error(object_error::parse_failed); return; } W.printString("DisplayName", DisplayName); W.printString("Section", SectionName); W.printHex("CodeSize", CodeSize); break; } case COFF::DEBUG_SYMBOL_TYPE_PROC_END: { W.startLine() << "ProcEnd\n"; if (!InFunctionScope || Size > 0) { error(object_error::parse_failed); return; } InFunctionScope = false; break; } default: { if (opts::CodeViewSubsectionBytes) { ListScope S(W, "Record"); W.printHex("Size", Size); W.printHex("Type", Type); StringRef Contents = DE.getData().substr(Offset, Size); W.printBinaryBlock("Contents", Contents); } Offset += Size; break; } } } if (InFunctionScope) error(object_error::parse_failed); } void COFFDumper::printSections() { ListScope SectionsD(W, "Sections"); int SectionNumber = 0; for (const SectionRef &Sec : Obj->sections()) { ++SectionNumber; const coff_section *Section = Obj->getCOFFSection(Sec); StringRef Name; if (error(Sec.getName(Name))) Name = ""; DictScope D(W, "Section"); W.printNumber("Number", SectionNumber); W.printBinary("Name", Name, Section->Name); W.printHex ("VirtualSize", Section->VirtualSize); W.printHex ("VirtualAddress", Section->VirtualAddress); W.printNumber("RawDataSize", Section->SizeOfRawData); W.printHex ("PointerToRawData", Section->PointerToRawData); W.printHex ("PointerToRelocations", Section->PointerToRelocations); W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers); W.printNumber("RelocationCount", Section->NumberOfRelocations); W.printNumber("LineNumberCount", Section->NumberOfLinenumbers); W.printFlags ("Characteristics", Section->Characteristics, makeArrayRef(ImageSectionCharacteristics), COFF::SectionCharacteristics(0x00F00000)); if (opts::SectionRelocations) { ListScope D(W, "Relocations"); for (const RelocationRef &Reloc : Sec.relocations()) printRelocation(Sec, Reloc); } if (opts::SectionSymbols) { ListScope D(W, "Symbols"); for (const SymbolRef &Symbol : Obj->symbols()) { if (!Sec.containsSymbol(Symbol)) continue; printSymbol(Symbol); } } if (Name == ".debug$S" && opts::CodeView) printCodeViewDebugInfo(Sec); if (opts::SectionData && !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) { StringRef Data; if (error(Sec.getContents(Data))) break; W.printBinaryBlock("SectionData", Data); } } } void COFFDumper::printRelocations() { ListScope D(W, "Relocations"); int SectionNumber = 0; for (const SectionRef &Section : Obj->sections()) { ++SectionNumber; StringRef Name; if (error(Section.getName(Name))) continue; bool PrintedGroup = false; for (const RelocationRef &Reloc : Section.relocations()) { if (!PrintedGroup) { W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n"; W.indent(); PrintedGroup = true; } printRelocation(Section, Reloc); } if (PrintedGroup) { W.unindent(); W.startLine() << "}\n"; } } } void COFFDumper::printRelocation(const SectionRef &Section, const RelocationRef &Reloc) { uint64_t Offset = Reloc.getOffset(); uint64_t RelocType = Reloc.getType(); SmallString<32> RelocName; StringRef SymbolName; Reloc.getTypeName(RelocName); symbol_iterator Symbol = Reloc.getSymbol(); if (Symbol != Obj->symbol_end()) { ErrorOr<StringRef> SymbolNameOrErr = Symbol->getName(); if (error(SymbolNameOrErr.getError())) return; SymbolName = *SymbolNameOrErr; } if (opts::ExpandRelocs) { DictScope Group(W, "Relocation"); W.printHex("Offset", Offset); W.printNumber("Type", RelocName, RelocType); W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName); } else { raw_ostream& OS = W.startLine(); OS << W.hex(Offset) << " " << RelocName << " " << (SymbolName.empty() ? "-" : SymbolName) << "\n"; } } void COFFDumper::printSymbols() { ListScope Group(W, "Symbols"); for (const SymbolRef &Symbol : Obj->symbols()) printSymbol(Symbol); } void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); } static ErrorOr<StringRef> getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber, const coff_section *Section) { if (Section) { StringRef SectionName; if (std::error_code EC = Obj->getSectionName(Section, SectionName)) return EC; return SectionName; } if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG) return StringRef("IMAGE_SYM_DEBUG"); if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE) return StringRef("IMAGE_SYM_ABSOLUTE"); if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED) return StringRef("IMAGE_SYM_UNDEFINED"); return StringRef(""); } void COFFDumper::printSymbol(const SymbolRef &Sym) { DictScope D(W, "Symbol"); COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym); const coff_section *Section; if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) { W.startLine() << "Invalid section number: " << EC.message() << "\n"; W.flush(); return; } StringRef SymbolName; if (Obj->getSymbolName(Symbol, SymbolName)) SymbolName = ""; StringRef SectionName = ""; ErrorOr<StringRef> Res = getSectionName(Obj, Symbol.getSectionNumber(), Section); if (Res) SectionName = *Res; W.printString("Name", SymbolName); W.printNumber("Value", Symbol.getValue()); W.printNumber("Section", SectionName, Symbol.getSectionNumber()); W.printEnum ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType)); W.printEnum ("ComplexType", Symbol.getComplexType(), makeArrayRef(ImageSymDType)); W.printEnum ("StorageClass", Symbol.getStorageClass(), makeArrayRef(ImageSymClass)); W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols()); for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) { if (Symbol.isFunctionDefinition()) { const coff_aux_function_definition *Aux; if (error(getSymbolAuxData(Obj, Symbol, I, Aux))) break; DictScope AS(W, "AuxFunctionDef"); W.printNumber("TagIndex", Aux->TagIndex); W.printNumber("TotalSize", Aux->TotalSize); W.printHex("PointerToLineNumber", Aux->PointerToLinenumber); W.printHex("PointerToNextFunction", Aux->PointerToNextFunction); } else if (Symbol.isAnyUndefined()) { const coff_aux_weak_external *Aux; if (error(getSymbolAuxData(Obj, Symbol, I, Aux))) break; ErrorOr<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex); StringRef LinkedName; std::error_code EC = Linked.getError(); if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) { LinkedName = ""; error(EC); } DictScope AS(W, "AuxWeakExternal"); W.printNumber("Linked", LinkedName, Aux->TagIndex); W.printEnum ("Search", Aux->Characteristics, makeArrayRef(WeakExternalCharacteristics)); } else if (Symbol.isFileRecord()) { const char *FileName; if (error(getSymbolAuxData(Obj, Symbol, I, FileName))) break; DictScope AS(W, "AuxFileRecord"); StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() * Obj->getSymbolTableEntrySize()); W.printString("FileName", Name.rtrim(StringRef("\0", 1))); break; } else if (Symbol.isSectionDefinition()) { const coff_aux_section_definition *Aux; if (error(getSymbolAuxData(Obj, Symbol, I, Aux))) break; int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj()); DictScope AS(W, "AuxSectionDef"); W.printNumber("Length", Aux->Length); W.printNumber("RelocationCount", Aux->NumberOfRelocations); W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers); W.printHex("Checksum", Aux->CheckSum); W.printNumber("Number", AuxNumber); W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect)); if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) { const coff_section *Assoc; StringRef AssocName = ""; std::error_code EC = Obj->getSection(AuxNumber, Assoc); ErrorOr<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc); if (Res) AssocName = *Res; if (!EC) EC = Res.getError(); if (EC) { AssocName = ""; error(EC); } W.printNumber("AssocSection", AssocName, AuxNumber); } } else if (Symbol.isCLRToken()) { const coff_aux_clr_token *Aux; if (error(getSymbolAuxData(Obj, Symbol, I, Aux))) break; ErrorOr<COFFSymbolRef> ReferredSym = Obj->getSymbol(Aux->SymbolTableIndex); StringRef ReferredName; std::error_code EC = ReferredSym.getError(); if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) { ReferredName = ""; error(EC); } DictScope AS(W, "AuxCLRToken"); W.printNumber("AuxType", Aux->AuxType); W.printNumber("Reserved", Aux->Reserved); W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex); } else { W.startLine() << "<unhandled auxiliary record>\n"; } } } void COFFDumper::printUnwindInfo() { ListScope D(W, "UnwindInformation"); switch (Obj->getMachine()) { case COFF::IMAGE_FILE_MACHINE_AMD64: { Win64EH::Dumper Dumper(W); Win64EH::Dumper::SymbolResolver Resolver = [](const object::coff_section *Section, uint64_t Offset, SymbolRef &Symbol, void *user_data) -> std::error_code { COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data); return Dumper->resolveSymbol(Section, Offset, Symbol); }; Win64EH::Dumper::Context Ctx(*Obj, Resolver, this); Dumper.printData(Ctx); break; } case COFF::IMAGE_FILE_MACHINE_ARMNT: { ARM::WinEH::Decoder Decoder(W); Decoder.dumpProcedureData(*Obj); break; } default: W.printEnum("unsupported Image Machine", Obj->getMachine(), makeArrayRef(ImageFileMachineType)); break; } } void COFFDumper::printImportedSymbols( iterator_range<imported_symbol_iterator> Range) { for (const ImportedSymbolRef &I : Range) { StringRef Sym; if (error(I.getSymbolName(Sym))) return; uint16_t Ordinal; if (error(I.getOrdinal(Ordinal))) return; W.printNumber("Symbol", Sym, Ordinal); } } void COFFDumper::printDelayImportedSymbols( const DelayImportDirectoryEntryRef &I, iterator_range<imported_symbol_iterator> Range) { int Index = 0; for (const ImportedSymbolRef &S : Range) { DictScope Import(W, "Import"); StringRef Sym; if (error(S.getSymbolName(Sym))) return; uint16_t Ordinal; if (error(S.getOrdinal(Ordinal))) return; W.printNumber("Symbol", Sym, Ordinal); uint64_t Addr; if (error(I.getImportAddress(Index++, Addr))) return; W.printHex("Address", Addr); } } void COFFDumper::printCOFFImports() { // Regular imports for (const ImportDirectoryEntryRef &I : Obj->import_directories()) { DictScope Import(W, "Import"); StringRef Name; if (error(I.getName(Name))) return; W.printString("Name", Name); uint32_t Addr; if (error(I.getImportLookupTableRVA(Addr))) return; W.printHex("ImportLookupTableRVA", Addr); if (error(I.getImportAddressTableRVA(Addr))) return; W.printHex("ImportAddressTableRVA", Addr); printImportedSymbols(I.imported_symbols()); } // Delay imports for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) { DictScope Import(W, "DelayImport"); StringRef Name; if (error(I.getName(Name))) return; W.printString("Name", Name); const delay_import_directory_table_entry *Table; if (error(I.getDelayImportTable(Table))) return; W.printHex("Attributes", Table->Attributes); W.printHex("ModuleHandle", Table->ModuleHandle); W.printHex("ImportAddressTable", Table->DelayImportAddressTable); W.printHex("ImportNameTable", Table->DelayImportNameTable); W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable); W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable); printDelayImportedSymbols(I, I.imported_symbols()); } } void COFFDumper::printCOFFExports() { for (const ExportDirectoryEntryRef &E : Obj->export_directories()) { DictScope Export(W, "Export"); StringRef Name; uint32_t Ordinal, RVA; if (error(E.getSymbolName(Name))) continue; if (error(E.getOrdinal(Ordinal))) continue; if (error(E.getExportRVA(RVA))) continue; W.printNumber("Ordinal", Ordinal); W.printString("Name", Name); W.printHex("RVA", RVA); } } void COFFDumper::printCOFFDirectives() { for (const SectionRef &Section : Obj->sections()) { StringRef Contents; StringRef Name; if (error(Section.getName(Name))) continue; if (Name != ".drectve") continue; if (error(Section.getContents(Contents))) return; W.printString("Directive(s)", Contents); } } static StringRef getBaseRelocTypeName(uint8_t Type) { switch (Type) { case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE"; case COFF::IMAGE_REL_BASED_HIGH: return "HIGH"; case COFF::IMAGE_REL_BASED_LOW: return "LOW"; case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW"; case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ"; case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)"; case COFF::IMAGE_REL_BASED_DIR64: return "DIR64"; default: return "unknown (" + llvm::utostr(Type) + ")"; } } void COFFDumper::printCOFFBaseReloc() { ListScope D(W, "BaseReloc"); for (const BaseRelocRef &I : Obj->base_relocs()) { uint8_t Type; uint32_t RVA; if (error(I.getRVA(RVA))) continue; if (error(I.getType(Type))) continue; DictScope Import(W, "Entry"); W.printString("Type", getBaseRelocTypeName(Type)); W.printHex("Address", RVA); } } void COFFDumper::printStackMap() const { object::SectionRef StackMapSection; for (auto Sec : Obj->sections()) { StringRef Name; Sec.getName(Name); if (Name == ".llvm_stackmaps") { StackMapSection = Sec; break; } } if (StackMapSection == object::SectionRef()) return; StringRef StackMapContents; StackMapSection.getContents(StackMapContents); ArrayRef<uint8_t> StackMapContentsArray( reinterpret_cast<const uint8_t*>(StackMapContents.data()), StackMapContents.size()); if (Obj->isLittleEndian()) prettyPrintStackMap( llvm::outs(), StackMapV1Parser<support::little>(StackMapContentsArray)); else prettyPrintStackMap(llvm::outs(), StackMapV1Parser<support::big>(StackMapContentsArray)); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Object Support ) add_llvm_tool(llvm-readobj ARMAttributeParser.cpp ARMWinEHPrinter.cpp COFFDumper.cpp ELFDumper.cpp Error.cpp llvm-readobj.cpp MachODumper.cpp ObjDumper.cpp StreamWriter.cpp Win64EHDumper.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ELFDumper.cpp
//===-- ELFDumper.cpp - ELF-specific dumper ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements the ELF-specific dumper for llvm-readobj. /// //===----------------------------------------------------------------------===// #include "llvm-readobj.h" #include "ARMAttributeParser.h" #include "ARMEHABIPrinter.h" #include "Error.h" #include "ObjDumper.h" #include "StackMapPrinter.h" #include "StreamWriter.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Support/ARMBuildAttributes.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Format.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MipsABIFlags.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; using namespace ELF; #define LLVM_READOBJ_ENUM_CASE(ns, enum) \ case ns::enum: return #enum; namespace { template<typename ELFT> class ELFDumper : public ObjDumper { public: ELFDumper(const ELFFile<ELFT> *Obj, StreamWriter &Writer) : ObjDumper(Writer), Obj(Obj) {} void printFileHeaders() override; void printSections() override; void printRelocations() override; void printDynamicRelocations() override; void printSymbols() override; void printDynamicSymbols() override; void printUnwindInfo() override; void printDynamicTable() override; void printNeededLibraries() override; void printProgramHeaders() override; void printHashTable() override; void printAttributes() override; void printMipsPLTGOT() override; void printMipsABIFlags() override; void printMipsReginfo() override; void printStackMap() const override; private: typedef ELFFile<ELFT> ELFO; typedef typename ELFO::Elf_Shdr Elf_Shdr; typedef typename ELFO::Elf_Sym Elf_Sym; void printSymbol(const Elf_Sym *Symbol, bool IsDynamic); void printRelocations(const Elf_Shdr *Sec); void printRelocation(const Elf_Shdr *Sec, typename ELFO::Elf_Rela Rel); const ELFO *Obj; }; template <class T> T errorOrDefault(ErrorOr<T> Val, T Default = T()) { if (!Val) { error(Val.getError()); return Default; } return *Val; } } // namespace namespace llvm { template <class ELFT> static std::error_code createELFDumper(const ELFFile<ELFT> *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result) { Result.reset(new ELFDumper<ELFT>(Obj, Writer)); return readobj_error::success; } std::error_code createELFDumper(const object::ObjectFile *Obj, StreamWriter &Writer, std::unique_ptr<ObjDumper> &Result) { // Little-endian 32-bit if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj)) return createELFDumper(ELFObj->getELFFile(), Writer, Result); // Big-endian 32-bit if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj)) return createELFDumper(ELFObj->getELFFile(), Writer, Result); // Little-endian 64-bit if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj)) return createELFDumper(ELFObj->getELFFile(), Writer, Result); // Big-endian 64-bit if (const ELF64BEObjectFile *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj)) return createELFDumper(ELFObj->getELFFile(), Writer, Result); return readobj_error::unsupported_obj_file_format; } } // namespace llvm template <typename ELFO> static std::string getFullSymbolName(const ELFO &Obj, const typename ELFO::Elf_Sym *Symbol, bool IsDynamic) { StringRef SymbolName = errorOrDefault(Obj.getSymbolName(Symbol, IsDynamic)); if (!IsDynamic) return SymbolName; std::string FullSymbolName(SymbolName); bool IsDefault; ErrorOr<StringRef> Version = Obj.getSymbolVersion(nullptr, &*Symbol, IsDefault); if (Version) { FullSymbolName += (IsDefault ? "@@" : "@"); FullSymbolName += *Version; } else error(Version.getError()); return FullSymbolName; } template <typename ELFO> static void getSectionNameIndex(const ELFO &Obj, const typename ELFO::Elf_Sym *Symbol, StringRef &SectionName, unsigned &SectionIndex) { SectionIndex = Symbol->st_shndx; if (Symbol->isUndefined()) SectionName = "Undefined"; else if (Symbol->isProcessorSpecific()) SectionName = "Processor Specific"; else if (Symbol->isOSSpecific()) SectionName = "Operating System Specific"; else if (Symbol->isAbsolute()) SectionName = "Absolute"; else if (Symbol->isCommon()) SectionName = "Common"; else if (Symbol->isReserved() && SectionIndex != SHN_XINDEX) SectionName = "Reserved"; else { if (SectionIndex == SHN_XINDEX) SectionIndex = Obj.getExtendedSymbolTableIndex(&*Symbol); ErrorOr<const typename ELFO::Elf_Shdr *> Sec = Obj.getSection(SectionIndex); if (!error(Sec.getError())) SectionName = errorOrDefault(Obj.getSectionName(*Sec)); } } template <class ELFT> static const typename ELFFile<ELFT>::Elf_Shdr * findSectionByAddress(const ELFFile<ELFT> *Obj, uint64_t Addr) { for (const auto &Shdr : Obj->sections()) if (Shdr.sh_addr == Addr) return &Shdr; return nullptr; } template <class ELFT> static const typename ELFFile<ELFT>::Elf_Shdr * findSectionByName(const ELFFile<ELFT> &Obj, StringRef Name) { for (const auto &Shdr : Obj.sections()) { if (Name == errorOrDefault(Obj.getSectionName(&Shdr))) return &Shdr; } return nullptr; } static const EnumEntry<unsigned> ElfClass[] = { { "None", ELF::ELFCLASSNONE }, { "32-bit", ELF::ELFCLASS32 }, { "64-bit", ELF::ELFCLASS64 }, }; static const EnumEntry<unsigned> ElfDataEncoding[] = { { "None", ELF::ELFDATANONE }, { "LittleEndian", ELF::ELFDATA2LSB }, { "BigEndian", ELF::ELFDATA2MSB }, }; static const EnumEntry<unsigned> ElfObjectFileType[] = { { "None", ELF::ET_NONE }, { "Relocatable", ELF::ET_REL }, { "Executable", ELF::ET_EXEC }, { "SharedObject", ELF::ET_DYN }, { "Core", ELF::ET_CORE }, }; static const EnumEntry<unsigned> ElfOSABI[] = { { "SystemV", ELF::ELFOSABI_NONE }, { "HPUX", ELF::ELFOSABI_HPUX }, { "NetBSD", ELF::ELFOSABI_NETBSD }, { "GNU/Linux", ELF::ELFOSABI_LINUX }, { "GNU/Hurd", ELF::ELFOSABI_HURD }, { "Solaris", ELF::ELFOSABI_SOLARIS }, { "AIX", ELF::ELFOSABI_AIX }, { "IRIX", ELF::ELFOSABI_IRIX }, { "FreeBSD", ELF::ELFOSABI_FREEBSD }, { "TRU64", ELF::ELFOSABI_TRU64 }, { "Modesto", ELF::ELFOSABI_MODESTO }, { "OpenBSD", ELF::ELFOSABI_OPENBSD }, { "OpenVMS", ELF::ELFOSABI_OPENVMS }, { "NSK", ELF::ELFOSABI_NSK }, { "AROS", ELF::ELFOSABI_AROS }, { "FenixOS", ELF::ELFOSABI_FENIXOS }, { "CloudABI", ELF::ELFOSABI_CLOUDABI }, { "C6000_ELFABI", ELF::ELFOSABI_C6000_ELFABI }, { "C6000_LINUX" , ELF::ELFOSABI_C6000_LINUX }, { "ARM", ELF::ELFOSABI_ARM }, { "Standalone" , ELF::ELFOSABI_STANDALONE } }; static const EnumEntry<unsigned> ElfMachineType[] = { LLVM_READOBJ_ENUM_ENT(ELF, EM_NONE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_M32 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SPARC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_386 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68K ), LLVM_READOBJ_ENUM_ENT(ELF, EM_88K ), LLVM_READOBJ_ENUM_ENT(ELF, EM_IAMCU ), LLVM_READOBJ_ENUM_ENT(ELF, EM_860 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MIPS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_S370 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MIPS_RS3_LE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PARISC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_VPP500 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SPARC32PLUS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_960 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PPC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PPC64 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_S390 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SPU ), LLVM_READOBJ_ENUM_ENT(ELF, EM_V800 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_FR20 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_RH32 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_RCE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ARM ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ALPHA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SH ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SPARCV9 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TRICORE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ARC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_H8_300 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_H8_300H ), LLVM_READOBJ_ENUM_ENT(ELF, EM_H8S ), LLVM_READOBJ_ENUM_ENT(ELF, EM_H8_500 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_IA_64 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MIPS_X ), LLVM_READOBJ_ENUM_ENT(ELF, EM_COLDFIRE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68HC12 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MMA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PCP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_NCPU ), LLVM_READOBJ_ENUM_ENT(ELF, EM_NDR1 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_STARCORE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ME16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ST100 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TINYJ ), LLVM_READOBJ_ENUM_ENT(ELF, EM_X86_64 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PDSP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PDP10 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PDP11 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_FX66 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ST9PLUS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ST7 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68HC16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68HC11 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68HC08 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_68HC05 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SVX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ST19 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_VAX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CRIS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_JAVELIN ), LLVM_READOBJ_ENUM_ENT(ELF, EM_FIREPATH ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ZSP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MMIX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_HUANY ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PRISM ), LLVM_READOBJ_ENUM_ENT(ELF, EM_AVR ), LLVM_READOBJ_ENUM_ENT(ELF, EM_FR30 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_D10V ), LLVM_READOBJ_ENUM_ENT(ELF, EM_D30V ), LLVM_READOBJ_ENUM_ENT(ELF, EM_V850 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_M32R ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MN10300 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MN10200 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_PJ ), LLVM_READOBJ_ENUM_ENT(ELF, EM_OPENRISC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ARC_COMPACT ), LLVM_READOBJ_ENUM_ENT(ELF, EM_XTENSA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_VIDEOCORE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TMM_GPP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_NS32K ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TPC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SNP1K ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ST200 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_IP2K ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MAX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CR ), LLVM_READOBJ_ENUM_ENT(ELF, EM_F2MC16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MSP430 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_BLACKFIN ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SE_C33 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SEP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ARCA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_UNICORE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_EXCESS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_DXP ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ALTERA_NIOS2 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CRX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_XGATE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_C166 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_M16C ), LLVM_READOBJ_ENUM_ENT(ELF, EM_DSPIC30F ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CE ), LLVM_READOBJ_ENUM_ENT(ELF, EM_M32C ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TSK3000 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_RS08 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SHARC ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ECOG2 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SCORE7 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_DSP24 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_VIDEOCORE3 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_LATTICEMICO32), LLVM_READOBJ_ENUM_ENT(ELF, EM_SE_C17 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TI_C6000 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TI_C2000 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TI_C5500 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MMDSP_PLUS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CYPRESS_M8C ), LLVM_READOBJ_ENUM_ENT(ELF, EM_R32C ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TRIMEDIA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_HEXAGON ), LLVM_READOBJ_ENUM_ENT(ELF, EM_8051 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_STXP7X ), LLVM_READOBJ_ENUM_ENT(ELF, EM_NDS32 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ECOG1 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ECOG1X ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MAXQ30 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_XIMO16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MANIK ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CRAYNV2 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_RX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_METAG ), LLVM_READOBJ_ENUM_ENT(ELF, EM_MCST_ELBRUS ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ECOG16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CR16 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ETPU ), LLVM_READOBJ_ENUM_ENT(ELF, EM_SLE9X ), LLVM_READOBJ_ENUM_ENT(ELF, EM_L10M ), LLVM_READOBJ_ENUM_ENT(ELF, EM_K10M ), LLVM_READOBJ_ENUM_ENT(ELF, EM_AARCH64 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_AVR32 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_STM8 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TILE64 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TILEPRO ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CUDA ), LLVM_READOBJ_ENUM_ENT(ELF, EM_TILEGX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_CLOUDSHIELD ), LLVM_READOBJ_ENUM_ENT(ELF, EM_COREA_1ST ), LLVM_READOBJ_ENUM_ENT(ELF, EM_COREA_2ND ), LLVM_READOBJ_ENUM_ENT(ELF, EM_ARC_COMPACT2 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_OPEN8 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_RL78 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_VIDEOCORE5 ), LLVM_READOBJ_ENUM_ENT(ELF, EM_78KOR ), LLVM_READOBJ_ENUM_ENT(ELF, EM_56800EX ), LLVM_READOBJ_ENUM_ENT(ELF, EM_AMDGPU ) }; static const EnumEntry<unsigned> ElfSymbolBindings[] = { { "Local", ELF::STB_LOCAL }, { "Global", ELF::STB_GLOBAL }, { "Weak", ELF::STB_WEAK }, { "Unique", ELF::STB_GNU_UNIQUE } }; static const EnumEntry<unsigned> ElfSymbolTypes[] = { { "None", ELF::STT_NOTYPE }, { "Object", ELF::STT_OBJECT }, { "Function", ELF::STT_FUNC }, { "Section", ELF::STT_SECTION }, { "File", ELF::STT_FILE }, { "Common", ELF::STT_COMMON }, { "TLS", ELF::STT_TLS }, { "GNU_IFunc", ELF::STT_GNU_IFUNC } }; static const char *getElfSectionType(unsigned Arch, unsigned Type) { switch (Arch) { case ELF::EM_ARM: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, SHT_ARM_EXIDX); LLVM_READOBJ_ENUM_CASE(ELF, SHT_ARM_PREEMPTMAP); LLVM_READOBJ_ENUM_CASE(ELF, SHT_ARM_ATTRIBUTES); LLVM_READOBJ_ENUM_CASE(ELF, SHT_ARM_DEBUGOVERLAY); LLVM_READOBJ_ENUM_CASE(ELF, SHT_ARM_OVERLAYSECTION); } case ELF::EM_HEXAGON: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, SHT_HEX_ORDERED); } case ELF::EM_X86_64: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, SHT_X86_64_UNWIND); } case ELF::EM_MIPS: case ELF::EM_MIPS_RS3_LE: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, SHT_MIPS_REGINFO); LLVM_READOBJ_ENUM_CASE(ELF, SHT_MIPS_OPTIONS); LLVM_READOBJ_ENUM_CASE(ELF, SHT_MIPS_ABIFLAGS); } } switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, SHT_NULL ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_PROGBITS ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_SYMTAB ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_STRTAB ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_RELA ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_HASH ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_DYNAMIC ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_NOTE ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_NOBITS ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_REL ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_SHLIB ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_DYNSYM ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_INIT_ARRAY ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_FINI_ARRAY ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_PREINIT_ARRAY ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GROUP ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_SYMTAB_SHNDX ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GNU_ATTRIBUTES ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GNU_HASH ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GNU_verdef ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GNU_verneed ); LLVM_READOBJ_ENUM_CASE(ELF, SHT_GNU_versym ); default: return ""; } } static const EnumEntry<unsigned> ElfSectionFlags[] = { LLVM_READOBJ_ENUM_ENT(ELF, SHF_WRITE ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_ALLOC ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_EXCLUDE ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_EXECINSTR ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_MERGE ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_STRINGS ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_INFO_LINK ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_LINK_ORDER ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_OS_NONCONFORMING), LLVM_READOBJ_ENUM_ENT(ELF, SHF_GROUP ), LLVM_READOBJ_ENUM_ENT(ELF, SHF_TLS ), LLVM_READOBJ_ENUM_ENT(ELF, XCORE_SHF_CP_SECTION), LLVM_READOBJ_ENUM_ENT(ELF, XCORE_SHF_DP_SECTION), LLVM_READOBJ_ENUM_ENT(ELF, SHF_MIPS_NOSTRIP ) }; static const char *getElfSegmentType(unsigned Arch, unsigned Type) { // Check potentially overlapped processor-specific // program header type. switch (Arch) { case ELF::EM_ARM: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); } case ELF::EM_MIPS: case ELF::EM_MIPS_RS3_LE: switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO); LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC); LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS); LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS); } } switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL ); LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD ); LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC); LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP ); LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE ); LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB ); LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR ); LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS ); LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME); LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND); LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK); LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO); default: return ""; } } static const EnumEntry<unsigned> ElfSegmentFlags[] = { LLVM_READOBJ_ENUM_ENT(ELF, PF_X), LLVM_READOBJ_ENUM_ENT(ELF, PF_W), LLVM_READOBJ_ENUM_ENT(ELF, PF_R) }; static const EnumEntry<unsigned> ElfHeaderMipsFlags[] = { LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_NOREORDER), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_PIC), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_CPIC), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ABI2), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_32BITMODE), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_FP64), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_NAN2008), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ABI_O32), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ABI_O64), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ABI_EABI32), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ABI_EABI64), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_3900), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_4010), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_4100), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_4650), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_4120), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_4111), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_SB1), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_OCTEON), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_XLR), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_OCTEON2), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_OCTEON3), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_5400), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_5900), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_5500), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_9000), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_LS2E), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_LS2F), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MACH_LS3A), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_MICROMIPS), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_ASE_M16), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_ASE_MDMX), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_1), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_2), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_3), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_4), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_5), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_32), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_64), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_32R2), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_64R2), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_32R6), LLVM_READOBJ_ENUM_ENT(ELF, EF_MIPS_ARCH_64R6) }; template<class ELFT> void ELFDumper<ELFT>::printFileHeaders() { const typename ELFO::Elf_Ehdr *Header = Obj->getHeader(); { DictScope D(W, "ElfHeader"); { DictScope D(W, "Ident"); W.printBinary("Magic", makeArrayRef(Header->e_ident).slice(ELF::EI_MAG0, 4)); W.printEnum ("Class", Header->e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass)); W.printEnum ("DataEncoding", Header->e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding)); W.printNumber("FileVersion", Header->e_ident[ELF::EI_VERSION]); // Handle architecture specific OS/ABI values. if (Header->e_machine == ELF::EM_AMDGPU && Header->e_ident[ELF::EI_OSABI] == ELF::ELFOSABI_AMDGPU_HSA) W.printHex("OS/ABI", "AMDGPU_HSA", ELF::ELFOSABI_AMDGPU_HSA); else W.printEnum ("OS/ABI", Header->e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI)); W.printNumber("ABIVersion", Header->e_ident[ELF::EI_ABIVERSION]); W.printBinary("Unused", makeArrayRef(Header->e_ident).slice(ELF::EI_PAD)); } W.printEnum ("Type", Header->e_type, makeArrayRef(ElfObjectFileType)); W.printEnum ("Machine", Header->e_machine, makeArrayRef(ElfMachineType)); W.printNumber("Version", Header->e_version); W.printHex ("Entry", Header->e_entry); W.printHex ("ProgramHeaderOffset", Header->e_phoff); W.printHex ("SectionHeaderOffset", Header->e_shoff); if (Header->e_machine == EM_MIPS) W.printFlags("Flags", Header->e_flags, makeArrayRef(ElfHeaderMipsFlags), unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI), unsigned(ELF::EF_MIPS_MACH)); else W.printFlags("Flags", Header->e_flags); W.printNumber("HeaderSize", Header->e_ehsize); W.printNumber("ProgramHeaderEntrySize", Header->e_phentsize); W.printNumber("ProgramHeaderCount", Header->e_phnum); W.printNumber("SectionHeaderEntrySize", Header->e_shentsize); W.printNumber("SectionHeaderCount", Header->e_shnum); W.printNumber("StringTableSectionIndex", Header->e_shstrndx); } } template<class ELFT> void ELFDumper<ELFT>::printSections() { ListScope SectionsD(W, "Sections"); int SectionIndex = -1; for (const typename ELFO::Elf_Shdr &Sec : Obj->sections()) { ++SectionIndex; StringRef Name = errorOrDefault(Obj->getSectionName(&Sec)); DictScope SectionD(W, "Section"); W.printNumber("Index", SectionIndex); W.printNumber("Name", Name, Sec.sh_name); W.printHex("Type", getElfSectionType(Obj->getHeader()->e_machine, Sec.sh_type), Sec.sh_type); W.printFlags("Flags", Sec.sh_flags, makeArrayRef(ElfSectionFlags)); W.printHex("Address", Sec.sh_addr); W.printHex("Offset", Sec.sh_offset); W.printNumber("Size", Sec.sh_size); W.printNumber("Link", Sec.sh_link); W.printNumber("Info", Sec.sh_info); W.printNumber("AddressAlignment", Sec.sh_addralign); W.printNumber("EntrySize", Sec.sh_entsize); if (opts::SectionRelocations) { ListScope D(W, "Relocations"); printRelocations(&Sec); } if (opts::SectionSymbols) { ListScope D(W, "Symbols"); for (const typename ELFO::Elf_Sym &Sym : Obj->symbols()) { ErrorOr<const Elf_Shdr *> SymSec = Obj->getSection(&Sym); if (!SymSec) continue; if (*SymSec == &Sec) printSymbol(&Sym, false); } } if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) { ArrayRef<uint8_t> Data = errorOrDefault(Obj->getSectionContents(&Sec)); W.printBinaryBlock("SectionData", StringRef((const char *)Data.data(), Data.size())); } } } template<class ELFT> void ELFDumper<ELFT>::printRelocations() { ListScope D(W, "Relocations"); int SectionNumber = -1; for (const typename ELFO::Elf_Shdr &Sec : Obj->sections()) { ++SectionNumber; if (Sec.sh_type != ELF::SHT_REL && Sec.sh_type != ELF::SHT_RELA) continue; StringRef Name = errorOrDefault(Obj->getSectionName(&Sec)); W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n"; W.indent(); printRelocations(&Sec); W.unindent(); W.startLine() << "}\n"; } } template<class ELFT> void ELFDumper<ELFT>::printDynamicRelocations() { W.startLine() << "Dynamic Relocations {\n"; W.indent(); for (typename ELFO::Elf_Rela_Iter RelI = Obj->dyn_rela_begin(), RelE = Obj->dyn_rela_end(); RelI != RelE; ++RelI) { SmallString<32> RelocName; Obj->getRelocationTypeName(RelI->getType(Obj->isMips64EL()), RelocName); StringRef SymbolName; uint32_t SymIndex = RelI->getSymbol(Obj->isMips64EL()); const typename ELFO::Elf_Sym *Sym = Obj->dynamic_symbol_begin() + SymIndex; SymbolName = errorOrDefault(Obj->getSymbolName(Sym, true)); if (opts::ExpandRelocs) { DictScope Group(W, "Relocation"); W.printHex("Offset", RelI->r_offset); W.printNumber("Type", RelocName, (int)RelI->getType(Obj->isMips64EL())); W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-"); W.printHex("Addend", RelI->r_addend); } else { raw_ostream& OS = W.startLine(); OS << W.hex(RelI->r_offset) << " " << RelocName << " " << (SymbolName.size() > 0 ? SymbolName : "-") << " " << W.hex(RelI->r_addend) << "\n"; } } W.unindent(); W.startLine() << "}\n"; } template <class ELFT> void ELFDumper<ELFT>::printRelocations(const Elf_Shdr *Sec) { switch (Sec->sh_type) { case ELF::SHT_REL: for (typename ELFO::Elf_Rel_Iter RI = Obj->rel_begin(Sec), RE = Obj->rel_end(Sec); RI != RE; ++RI) { typename ELFO::Elf_Rela Rela; Rela.r_offset = RI->r_offset; Rela.r_info = RI->r_info; Rela.r_addend = 0; printRelocation(Sec, Rela); } break; case ELF::SHT_RELA: for (typename ELFO::Elf_Rela_Iter RI = Obj->rela_begin(Sec), RE = Obj->rela_end(Sec); RI != RE; ++RI) { printRelocation(Sec, *RI); } break; } } template <class ELFT> void ELFDumper<ELFT>::printRelocation(const Elf_Shdr *Sec, typename ELFO::Elf_Rela Rel) { SmallString<32> RelocName; Obj->getRelocationTypeName(Rel.getType(Obj->isMips64EL()), RelocName); StringRef TargetName; std::pair<const Elf_Shdr *, const Elf_Sym *> Sym = Obj->getRelocationSymbol(Sec, &Rel); if (Sym.second && Sym.second->getType() == ELF::STT_SECTION) { ErrorOr<const Elf_Shdr *> Sec = Obj->getSection(Sym.second); if (!error(Sec.getError())) { ErrorOr<StringRef> SecName = Obj->getSectionName(*Sec); if (SecName) TargetName = SecName.get(); } } else if (Sym.first) { const Elf_Shdr *SymTable = Sym.first; ErrorOr<const Elf_Shdr *> StrTableSec = Obj->getSection(SymTable->sh_link); if (!error(StrTableSec.getError())) { ErrorOr<StringRef> StrTableOrErr = Obj->getStringTable(*StrTableSec); if (!error(StrTableOrErr.getError())) TargetName = errorOrDefault(Sym.second->getName(*StrTableOrErr)); } } if (opts::ExpandRelocs) { DictScope Group(W, "Relocation"); W.printHex("Offset", Rel.r_offset); W.printNumber("Type", RelocName, (int)Rel.getType(Obj->isMips64EL())); W.printNumber("Symbol", TargetName.size() > 0 ? TargetName : "-", Rel.getSymbol(Obj->isMips64EL())); W.printHex("Addend", Rel.r_addend); } else { raw_ostream& OS = W.startLine(); OS << W.hex(Rel.r_offset) << " " << RelocName << " " << (TargetName.size() > 0 ? TargetName : "-") << " " << W.hex(Rel.r_addend) << "\n"; } } template<class ELFT> void ELFDumper<ELFT>::printSymbols() { ListScope Group(W, "Symbols"); for (const typename ELFO::Elf_Sym &Sym : Obj->symbols()) printSymbol(&Sym, false); } template<class ELFT> void ELFDumper<ELFT>::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); for (const typename ELFO::Elf_Sym &Sym : Obj->dynamic_symbols()) printSymbol(&Sym, true); } template <class ELFT> void ELFDumper<ELFT>::printSymbol(const typename ELFO::Elf_Sym *Symbol, bool IsDynamic) { unsigned SectionIndex = 0; StringRef SectionName; getSectionNameIndex(*Obj, Symbol, SectionName, SectionIndex); std::string FullSymbolName = getFullSymbolName(*Obj, Symbol, IsDynamic); DictScope D(W, "Symbol"); W.printNumber("Name", FullSymbolName, Symbol->st_name); W.printHex ("Value", Symbol->st_value); W.printNumber("Size", Symbol->st_size); W.printEnum ("Binding", Symbol->getBinding(), makeArrayRef(ElfSymbolBindings)); W.printEnum ("Type", Symbol->getType(), makeArrayRef(ElfSymbolTypes)); W.printNumber("Other", Symbol->st_other); W.printHex("Section", SectionName, SectionIndex); } #define LLVM_READOBJ_TYPE_CASE(name) \ case DT_##name: return #name static const char *getTypeString(uint64_t Type) { switch (Type) { LLVM_READOBJ_TYPE_CASE(BIND_NOW); LLVM_READOBJ_TYPE_CASE(DEBUG); LLVM_READOBJ_TYPE_CASE(FINI); LLVM_READOBJ_TYPE_CASE(FINI_ARRAY); LLVM_READOBJ_TYPE_CASE(FINI_ARRAYSZ); LLVM_READOBJ_TYPE_CASE(FLAGS); LLVM_READOBJ_TYPE_CASE(FLAGS_1); LLVM_READOBJ_TYPE_CASE(HASH); LLVM_READOBJ_TYPE_CASE(INIT); LLVM_READOBJ_TYPE_CASE(INIT_ARRAY); LLVM_READOBJ_TYPE_CASE(INIT_ARRAYSZ); LLVM_READOBJ_TYPE_CASE(PREINIT_ARRAY); LLVM_READOBJ_TYPE_CASE(PREINIT_ARRAYSZ); LLVM_READOBJ_TYPE_CASE(JMPREL); LLVM_READOBJ_TYPE_CASE(NEEDED); LLVM_READOBJ_TYPE_CASE(NULL); LLVM_READOBJ_TYPE_CASE(PLTGOT); LLVM_READOBJ_TYPE_CASE(PLTREL); LLVM_READOBJ_TYPE_CASE(PLTRELSZ); LLVM_READOBJ_TYPE_CASE(REL); LLVM_READOBJ_TYPE_CASE(RELA); LLVM_READOBJ_TYPE_CASE(RELENT); LLVM_READOBJ_TYPE_CASE(RELSZ); LLVM_READOBJ_TYPE_CASE(RELAENT); LLVM_READOBJ_TYPE_CASE(RELASZ); LLVM_READOBJ_TYPE_CASE(RPATH); LLVM_READOBJ_TYPE_CASE(RUNPATH); LLVM_READOBJ_TYPE_CASE(SONAME); LLVM_READOBJ_TYPE_CASE(STRSZ); LLVM_READOBJ_TYPE_CASE(STRTAB); LLVM_READOBJ_TYPE_CASE(SYMBOLIC); LLVM_READOBJ_TYPE_CASE(SYMENT); LLVM_READOBJ_TYPE_CASE(SYMTAB); LLVM_READOBJ_TYPE_CASE(TEXTREL); LLVM_READOBJ_TYPE_CASE(VERNEED); LLVM_READOBJ_TYPE_CASE(VERNEEDNUM); LLVM_READOBJ_TYPE_CASE(VERSYM); LLVM_READOBJ_TYPE_CASE(RELCOUNT); LLVM_READOBJ_TYPE_CASE(GNU_HASH); LLVM_READOBJ_TYPE_CASE(MIPS_RLD_VERSION); LLVM_READOBJ_TYPE_CASE(MIPS_FLAGS); LLVM_READOBJ_TYPE_CASE(MIPS_BASE_ADDRESS); LLVM_READOBJ_TYPE_CASE(MIPS_LOCAL_GOTNO); LLVM_READOBJ_TYPE_CASE(MIPS_SYMTABNO); LLVM_READOBJ_TYPE_CASE(MIPS_UNREFEXTNO); LLVM_READOBJ_TYPE_CASE(MIPS_GOTSYM); LLVM_READOBJ_TYPE_CASE(MIPS_RLD_MAP); LLVM_READOBJ_TYPE_CASE(MIPS_PLTGOT); LLVM_READOBJ_TYPE_CASE(MIPS_OPTIONS); default: return "unknown"; } } #undef LLVM_READOBJ_TYPE_CASE #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \ { #enum, prefix##_##enum } static const EnumEntry<unsigned> ElfDynamicDTFlags[] = { LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN), LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC), LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL), LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW), LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS) }; static const EnumEntry<unsigned> ElfDynamicDTFlags1[] = { LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW), LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL), LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE), LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR), LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN), LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN), LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT), LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS), LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP), LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT), LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE), LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT), LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR), LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED), LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC), LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE), LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT), LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON) }; static const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = { LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE), LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART), LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT), LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT), LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE), LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY), LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT), LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS), LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT), LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE), LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD), LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART), LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED), LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD), LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF), LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE) }; #undef LLVM_READOBJ_DT_FLAG_ENT template <typename T, typename TFlag> void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) { typedef EnumEntry<TFlag> FlagEntry; typedef SmallVector<FlagEntry, 10> FlagVector; FlagVector SetFlags; for (const auto &Flag : Flags) { if (Flag.Value == 0) continue; if ((Value & Flag.Value) == Flag.Value) SetFlags.push_back(Flag); } for (const auto &Flag : SetFlags) { OS << Flag.Name << " "; } } template <class ELFT> static void printValue(const ELFFile<ELFT> *O, uint64_t Type, uint64_t Value, bool Is64, raw_ostream &OS) { switch (Type) { case DT_PLTREL: if (Value == DT_REL) { OS << "REL"; break; } else if (Value == DT_RELA) { OS << "RELA"; break; } // Fallthrough. case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: case DT_DEBUG: case DT_VERNEED: case DT_VERSYM: case DT_GNU_HASH: case DT_NULL: case DT_MIPS_BASE_ADDRESS: case DT_MIPS_GOTSYM: case DT_MIPS_RLD_MAP: case DT_MIPS_PLTGOT: case DT_MIPS_OPTIONS: OS << format("0x%" PRIX64, Value); break; case DT_RELCOUNT: case DT_VERNEEDNUM: case DT_MIPS_RLD_VERSION: case DT_MIPS_LOCAL_GOTNO: case DT_MIPS_SYMTABNO: case DT_MIPS_UNREFEXTNO: OS << Value; break; case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_RELSZ: case DT_RELENT: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_PREINIT_ARRAYSZ: OS << Value << " (bytes)"; break; case DT_NEEDED: OS << "SharedLibrary (" << O->getDynamicString(Value) << ")"; break; case DT_SONAME: OS << "LibrarySoname (" << O->getDynamicString(Value) << ")"; break; case DT_RPATH: case DT_RUNPATH: OS << O->getDynamicString(Value); break; case DT_MIPS_FLAGS: printFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags), OS); break; case DT_FLAGS: printFlags(Value, makeArrayRef(ElfDynamicDTFlags), OS); break; case DT_FLAGS_1: printFlags(Value, makeArrayRef(ElfDynamicDTFlags1), OS); break; default: OS << format("0x%" PRIX64, Value); break; } } template<class ELFT> void ELFDumper<ELFT>::printUnwindInfo() { W.startLine() << "UnwindInfo not implemented.\n"; } namespace { template <> void ELFDumper<ELFType<support::little, false>>::printUnwindInfo() { const unsigned Machine = Obj->getHeader()->e_machine; if (Machine == EM_ARM) { ARM::EHABI::PrinterContext<ELFType<support::little, false>> Ctx(W, Obj); return Ctx.PrintUnwindInformation(); } W.startLine() << "UnwindInfo not implemented.\n"; } } template<class ELFT> void ELFDumper<ELFT>::printDynamicTable() { auto DynTable = Obj->dynamic_table(true); ptrdiff_t Total = std::distance(DynTable.begin(), DynTable.end()); if (Total == 0) return; raw_ostream &OS = W.getOStream(); W.startLine() << "DynamicSection [ (" << Total << " entries)\n"; bool Is64 = ELFT::Is64Bits; W.startLine() << " Tag" << (Is64 ? " " : " ") << "Type" << " " << "Name/Value\n"; for (const auto &Entry : DynTable) { W.startLine() << " " << format(Is64 ? "0x%016" PRIX64 : "0x%08" PRIX64, Entry.getTag()) << " " << format("%-21s", getTypeString(Entry.getTag())); printValue(Obj, Entry.getTag(), Entry.getVal(), Is64, OS); OS << "\n"; } W.startLine() << "]\n"; } template<class ELFT> void ELFDumper<ELFT>::printNeededLibraries() { ListScope D(W, "NeededLibraries"); typedef std::vector<StringRef> LibsTy; LibsTy Libs; for (const auto &Entry : Obj->dynamic_table()) if (Entry.d_tag == ELF::DT_NEEDED) Libs.push_back(Obj->getDynamicString(Entry.d_un.d_val)); std::stable_sort(Libs.begin(), Libs.end()); for (LibsTy::const_iterator I = Libs.begin(), E = Libs.end(); I != E; ++I) { outs() << " " << *I << "\n"; } } template<class ELFT> void ELFDumper<ELFT>::printProgramHeaders() { ListScope L(W, "ProgramHeaders"); for (typename ELFO::Elf_Phdr_Iter PI = Obj->program_header_begin(), PE = Obj->program_header_end(); PI != PE; ++PI) { DictScope P(W, "ProgramHeader"); W.printHex ("Type", getElfSegmentType(Obj->getHeader()->e_machine, PI->p_type), PI->p_type); W.printHex ("Offset", PI->p_offset); W.printHex ("VirtualAddress", PI->p_vaddr); W.printHex ("PhysicalAddress", PI->p_paddr); W.printNumber("FileSize", PI->p_filesz); W.printNumber("MemSize", PI->p_memsz); W.printFlags ("Flags", PI->p_flags, makeArrayRef(ElfSegmentFlags)); W.printNumber("Alignment", PI->p_align); } } template <typename ELFT> void ELFDumper<ELFT>::printHashTable() { DictScope D(W, "HashTable"); auto HT = Obj->getHashTable(); if (!HT) return; W.printNumber("Num Buckets", HT->nbucket); W.printNumber("Num Chains", HT->nchain); W.printList("Buckets", HT->buckets()); W.printList("Chains", HT->chains()); } template <class ELFT> void ELFDumper<ELFT>::printAttributes() { W.startLine() << "Attributes not implemented.\n"; } namespace { template <> void ELFDumper<ELFType<support::little, false>>::printAttributes() { if (Obj->getHeader()->e_machine != EM_ARM) { W.startLine() << "Attributes not implemented.\n"; return; } DictScope BA(W, "BuildAttributes"); for (const ELFO::Elf_Shdr &Sec : Obj->sections()) { if (Sec.sh_type != ELF::SHT_ARM_ATTRIBUTES) continue; ErrorOr<ArrayRef<uint8_t>> Contents = Obj->getSectionContents(&Sec); if (!Contents) continue; if ((*Contents)[0] != ARMBuildAttrs::Format_Version) { errs() << "unrecognised FormatVersion: 0x" << utohexstr((*Contents)[0]) << '\n'; continue; } W.printHex("FormatVersion", (*Contents)[0]); if (Contents->size() == 1) continue; ARMAttributeParser(W).Parse(*Contents); } } } namespace { template <class ELFT> class MipsGOTParser { public: typedef object::ELFFile<ELFT> ObjectFile; typedef typename ObjectFile::Elf_Shdr Elf_Shdr; typedef typename ObjectFile::Elf_Sym Elf_Sym; MipsGOTParser(const ObjectFile *Obj, StreamWriter &W); void parseGOT(); void parsePLT(); private: typedef typename ObjectFile::Elf_Addr GOTEntry; typedef typename ObjectFile::template ELFEntityIterator<const GOTEntry> GOTIter; const ObjectFile *Obj; StreamWriter &W; llvm::Optional<uint64_t> DtPltGot; llvm::Optional<uint64_t> DtLocalGotNum; llvm::Optional<uint64_t> DtGotSym; llvm::Optional<uint64_t> DtMipsPltGot; llvm::Optional<uint64_t> DtJmpRel; std::size_t getGOTTotal(ArrayRef<uint8_t> GOT) const; GOTIter makeGOTIter(ArrayRef<uint8_t> GOT, std::size_t EntryNum); void printGotEntry(uint64_t GotAddr, GOTIter BeginIt, GOTIter It); void printGlobalGotEntry(uint64_t GotAddr, GOTIter BeginIt, GOTIter It, const Elf_Sym *Sym, bool IsDynamic); void printPLTEntry(uint64_t PLTAddr, GOTIter BeginIt, GOTIter It, StringRef Purpose); void printPLTEntry(uint64_t PLTAddr, GOTIter BeginIt, GOTIter It, const Elf_Sym *Sym); }; } template <class ELFT> MipsGOTParser<ELFT>::MipsGOTParser(const ObjectFile *Obj, StreamWriter &W) : Obj(Obj), W(W) { for (const auto &Entry : Obj->dynamic_table()) { switch (Entry.getTag()) { case ELF::DT_PLTGOT: DtPltGot = Entry.getVal(); break; case ELF::DT_MIPS_LOCAL_GOTNO: DtLocalGotNum = Entry.getVal(); break; case ELF::DT_MIPS_GOTSYM: DtGotSym = Entry.getVal(); break; case ELF::DT_MIPS_PLTGOT: DtMipsPltGot = Entry.getVal(); break; case ELF::DT_JMPREL: DtJmpRel = Entry.getVal(); break; } } } template <class ELFT> void MipsGOTParser<ELFT>::parseGOT() { // See "Global Offset Table" in Chapter 5 in the following document // for detailed GOT description. // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf if (!DtPltGot) { W.startLine() << "Cannot find PLTGOT dynamic table tag.\n"; return; } if (!DtLocalGotNum) { W.startLine() << "Cannot find MIPS_LOCAL_GOTNO dynamic table tag.\n"; return; } if (!DtGotSym) { W.startLine() << "Cannot find MIPS_GOTSYM dynamic table tag.\n"; return; } const Elf_Shdr *GOTShdr = findSectionByAddress(Obj, *DtPltGot); if (!GOTShdr) { W.startLine() << "There is no .got section in the file.\n"; return; } ErrorOr<ArrayRef<uint8_t>> GOT = Obj->getSectionContents(GOTShdr); if (!GOT) { W.startLine() << "The .got section is empty.\n"; return; } if (*DtLocalGotNum > getGOTTotal(*GOT)) { W.startLine() << "MIPS_LOCAL_GOTNO exceeds a number of GOT entries.\n"; return; } const Elf_Sym *DynSymBegin = Obj->dynamic_symbol_begin(); const Elf_Sym *DynSymEnd = Obj->dynamic_symbol_end(); std::size_t DynSymTotal = std::size_t(std::distance(DynSymBegin, DynSymEnd)); if (*DtGotSym > DynSymTotal) { W.startLine() << "MIPS_GOTSYM exceeds a number of dynamic symbols.\n"; return; } std::size_t GlobalGotNum = DynSymTotal - *DtGotSym; if (*DtLocalGotNum + GlobalGotNum > getGOTTotal(*GOT)) { W.startLine() << "Number of global GOT entries exceeds the size of GOT.\n"; return; } GOTIter GotBegin = makeGOTIter(*GOT, 0); GOTIter GotLocalEnd = makeGOTIter(*GOT, *DtLocalGotNum); GOTIter It = GotBegin; DictScope GS(W, "Primary GOT"); W.printHex("Canonical gp value", GOTShdr->sh_addr + 0x7ff0); { ListScope RS(W, "Reserved entries"); { DictScope D(W, "Entry"); printGotEntry(GOTShdr->sh_addr, GotBegin, It++); W.printString("Purpose", StringRef("Lazy resolver")); } if (It != GotLocalEnd && (*It >> (sizeof(GOTEntry) * 8 - 1)) != 0) { DictScope D(W, "Entry"); printGotEntry(GOTShdr->sh_addr, GotBegin, It++); W.printString("Purpose", StringRef("Module pointer (GNU extension)")); } } { ListScope LS(W, "Local entries"); for (; It != GotLocalEnd; ++It) { DictScope D(W, "Entry"); printGotEntry(GOTShdr->sh_addr, GotBegin, It); } } { ListScope GS(W, "Global entries"); GOTIter GotGlobalEnd = makeGOTIter(*GOT, *DtLocalGotNum + GlobalGotNum); const Elf_Sym *GotDynSym = DynSymBegin + *DtGotSym; for (; It != GotGlobalEnd; ++It) { DictScope D(W, "Entry"); printGlobalGotEntry(GOTShdr->sh_addr, GotBegin, It, GotDynSym++, true); } } std::size_t SpecGotNum = getGOTTotal(*GOT) - *DtLocalGotNum - GlobalGotNum; W.printNumber("Number of TLS and multi-GOT entries", uint64_t(SpecGotNum)); } template <class ELFT> void MipsGOTParser<ELFT>::parsePLT() { if (!DtMipsPltGot) { W.startLine() << "Cannot find MIPS_PLTGOT dynamic table tag.\n"; return; } if (!DtJmpRel) { W.startLine() << "Cannot find JMPREL dynamic table tag.\n"; return; } const Elf_Shdr *PLTShdr = findSectionByAddress(Obj, *DtMipsPltGot); if (!PLTShdr) { W.startLine() << "There is no .got.plt section in the file.\n"; return; } ErrorOr<ArrayRef<uint8_t>> PLT = Obj->getSectionContents(PLTShdr); if (!PLT) { W.startLine() << "The .got.plt section is empty.\n"; return; } const Elf_Shdr *PLTRelShdr = findSectionByAddress(Obj, *DtJmpRel); if (!PLTShdr) { W.startLine() << "There is no .rel.plt section in the file.\n"; return; } GOTIter PLTBegin = makeGOTIter(*PLT, 0); GOTIter PLTEnd = makeGOTIter(*PLT, getGOTTotal(*PLT)); GOTIter It = PLTBegin; DictScope GS(W, "PLT GOT"); { ListScope RS(W, "Reserved entries"); printPLTEntry(PLTShdr->sh_addr, PLTBegin, It++, "PLT lazy resolver"); if (It != PLTEnd) printPLTEntry(PLTShdr->sh_addr, PLTBegin, It++, "Module pointer"); } { ListScope GS(W, "Entries"); switch (PLTRelShdr->sh_type) { case ELF::SHT_REL: for (typename ObjectFile::Elf_Rel_Iter RI = Obj->rel_begin(PLTRelShdr), RE = Obj->rel_end(PLTRelShdr); RI != RE && It != PLTEnd; ++RI, ++It) { const Elf_Sym *Sym = Obj->getRelocationSymbol(&*PLTRelShdr, &*RI).second; printPLTEntry(PLTShdr->sh_addr, PLTBegin, It, Sym); } break; case ELF::SHT_RELA: for (typename ObjectFile::Elf_Rela_Iter RI = Obj->rela_begin(PLTRelShdr), RE = Obj->rela_end(PLTRelShdr); RI != RE && It != PLTEnd; ++RI, ++It) { const Elf_Sym *Sym = Obj->getRelocationSymbol(&*PLTRelShdr, &*RI).second; printPLTEntry(PLTShdr->sh_addr, PLTBegin, It, Sym); } break; } } } template <class ELFT> std::size_t MipsGOTParser<ELFT>::getGOTTotal(ArrayRef<uint8_t> GOT) const { return GOT.size() / sizeof(GOTEntry); } template <class ELFT> typename MipsGOTParser<ELFT>::GOTIter MipsGOTParser<ELFT>::makeGOTIter(ArrayRef<uint8_t> GOT, std::size_t EntryNum) { const char *Data = reinterpret_cast<const char *>(GOT.data()); return GOTIter(sizeof(GOTEntry), Data + EntryNum * sizeof(GOTEntry)); } template <class ELFT> void MipsGOTParser<ELFT>::printGotEntry(uint64_t GotAddr, GOTIter BeginIt, GOTIter It) { int64_t Offset = std::distance(BeginIt, It) * sizeof(GOTEntry); W.printHex("Address", GotAddr + Offset); W.printNumber("Access", Offset - 0x7ff0); W.printHex("Initial", *It); } template <class ELFT> void MipsGOTParser<ELFT>::printGlobalGotEntry(uint64_t GotAddr, GOTIter BeginIt, GOTIter It, const Elf_Sym *Sym, bool IsDynamic) { printGotEntry(GotAddr, BeginIt, It); W.printHex("Value", Sym->st_value); W.printEnum("Type", Sym->getType(), makeArrayRef(ElfSymbolTypes)); unsigned SectionIndex = 0; StringRef SectionName; getSectionNameIndex(*Obj, Sym, SectionName, SectionIndex); W.printHex("Section", SectionName, SectionIndex); std::string FullSymbolName = getFullSymbolName(*Obj, Sym, IsDynamic); W.printNumber("Name", FullSymbolName, Sym->st_name); } template <class ELFT> void MipsGOTParser<ELFT>::printPLTEntry(uint64_t PLTAddr, GOTIter BeginIt, GOTIter It, StringRef Purpose) { DictScope D(W, "Entry"); int64_t Offset = std::distance(BeginIt, It) * sizeof(GOTEntry); W.printHex("Address", PLTAddr + Offset); W.printHex("Initial", *It); W.printString("Purpose", Purpose); } template <class ELFT> void MipsGOTParser<ELFT>::printPLTEntry(uint64_t PLTAddr, GOTIter BeginIt, GOTIter It, const Elf_Sym *Sym) { DictScope D(W, "Entry"); int64_t Offset = std::distance(BeginIt, It) * sizeof(GOTEntry); W.printHex("Address", PLTAddr + Offset); W.printHex("Initial", *It); W.printHex("Value", Sym->st_value); W.printEnum("Type", Sym->getType(), makeArrayRef(ElfSymbolTypes)); unsigned SectionIndex = 0; StringRef SectionName; getSectionNameIndex(*Obj, Sym, SectionName, SectionIndex); W.printHex("Section", SectionName, SectionIndex); std::string FullSymbolName = getFullSymbolName(*Obj, Sym, true); W.printNumber("Name", FullSymbolName, Sym->st_name); } template <class ELFT> void ELFDumper<ELFT>::printMipsPLTGOT() { if (Obj->getHeader()->e_machine != EM_MIPS) { W.startLine() << "MIPS PLT GOT is available for MIPS targets only.\n"; return; } MipsGOTParser<ELFT> GOTParser(Obj, W); GOTParser.parseGOT(); GOTParser.parsePLT(); } static const EnumEntry<unsigned> ElfMipsISAExtType[] = { {"None", Mips::AFL_EXT_NONE}, {"Broadcom SB-1", Mips::AFL_EXT_SB1}, {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON}, {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2}, {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP}, {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3}, {"LSI R4010", Mips::AFL_EXT_4010}, {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E}, {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F}, {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A}, {"MIPS R4650", Mips::AFL_EXT_4650}, {"MIPS R5900", Mips::AFL_EXT_5900}, {"MIPS R10000", Mips::AFL_EXT_10000}, {"NEC VR4100", Mips::AFL_EXT_4100}, {"NEC VR4111/VR4181", Mips::AFL_EXT_4111}, {"NEC VR4120", Mips::AFL_EXT_4120}, {"NEC VR5400", Mips::AFL_EXT_5400}, {"NEC VR5500", Mips::AFL_EXT_5500}, {"RMI Xlr", Mips::AFL_EXT_XLR}, {"Toshiba R3900", Mips::AFL_EXT_3900} }; static const EnumEntry<unsigned> ElfMipsASEFlags[] = { {"DSP", Mips::AFL_ASE_DSP}, {"DSPR2", Mips::AFL_ASE_DSPR2}, {"Enhanced VA Scheme", Mips::AFL_ASE_EVA}, {"MCU", Mips::AFL_ASE_MCU}, {"MDMX", Mips::AFL_ASE_MDMX}, {"MIPS-3D", Mips::AFL_ASE_MIPS3D}, {"MT", Mips::AFL_ASE_MT}, {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS}, {"VZ", Mips::AFL_ASE_VIRT}, {"MSA", Mips::AFL_ASE_MSA}, {"MIPS16", Mips::AFL_ASE_MIPS16}, {"microMIPS", Mips::AFL_ASE_MICROMIPS}, {"XPA", Mips::AFL_ASE_XPA} }; static const EnumEntry<unsigned> ElfMipsFpABIType[] = { {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY}, {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE}, {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE}, {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT}, {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)", Mips::Val_GNU_MIPS_ABI_FP_OLD_64}, {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX}, {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64}, {"Hard float compat (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64A} }; static const EnumEntry<unsigned> ElfMipsFlags1[] { {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG}, }; static int getMipsRegisterSize(uint8_t Flag) { switch (Flag) { case Mips::AFL_REG_NONE: return 0; case Mips::AFL_REG_32: return 32; case Mips::AFL_REG_64: return 64; case Mips::AFL_REG_128: return 128; default: return -1; } } template <class ELFT> void ELFDumper<ELFT>::printMipsABIFlags() { const Elf_Shdr *Shdr = findSectionByName(*Obj, ".MIPS.abiflags"); if (!Shdr) { W.startLine() << "There is no .MIPS.abiflags section in the file.\n"; return; } ErrorOr<ArrayRef<uint8_t>> Sec = Obj->getSectionContents(Shdr); if (!Sec) { W.startLine() << "The .MIPS.abiflags section is empty.\n"; return; } if (Sec->size() != sizeof(Elf_Mips_ABIFlags<ELFT>)) { W.startLine() << "The .MIPS.abiflags section has a wrong size.\n"; return; } auto *Flags = reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(Sec->data()); raw_ostream &OS = W.getOStream(); DictScope GS(W, "MIPS ABI Flags"); W.printNumber("Version", Flags->version); W.startLine() << "ISA: "; if (Flags->isa_rev <= 1) OS << format("MIPS%u", Flags->isa_level); else OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev); OS << "\n"; W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)); W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags)); W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)); W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size)); W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size)); W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size)); W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1)); W.printHex("Flags 2", Flags->flags2); } template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() { const Elf_Shdr *Shdr = findSectionByName(*Obj, ".reginfo"); if (!Shdr) { W.startLine() << "There is no .reginfo section in the file.\n"; return; } ErrorOr<ArrayRef<uint8_t>> Sec = Obj->getSectionContents(Shdr); if (!Sec) { W.startLine() << "The .reginfo section is empty.\n"; return; } if (Sec->size() != sizeof(Elf_Mips_RegInfo<ELFT>)) { W.startLine() << "The .reginfo section has a wrong size.\n"; return; } auto *Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(Sec->data()); DictScope GS(W, "MIPS RegInfo"); W.printHex("GP", Reginfo->ri_gp_value); W.printHex("General Mask", Reginfo->ri_gprmask); W.printHex("Co-Proc Mask0", Reginfo->ri_cprmask[0]); W.printHex("Co-Proc Mask1", Reginfo->ri_cprmask[1]); W.printHex("Co-Proc Mask2", Reginfo->ri_cprmask[2]); W.printHex("Co-Proc Mask3", Reginfo->ri_cprmask[3]); } template <class ELFT> void ELFDumper<ELFT>::printStackMap() const { const typename ELFFile<ELFT>::Elf_Shdr *StackMapSection = nullptr; for (const auto &Sec : Obj->sections()) { ErrorOr<StringRef> Name = Obj->getSectionName(&Sec); if (*Name == ".llvm_stackmaps") { StackMapSection = &Sec; break; } } if (!StackMapSection) return; StringRef StackMapContents; ErrorOr<ArrayRef<uint8_t>> StackMapContentsArray = Obj->getSectionContents(StackMapSection); prettyPrintStackMap( llvm::outs(), StackMapV1Parser<ELFT::TargetEndianness>(*StackMapContentsArray)); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/LLVMBuild.txt
;===- ./tools/llvm-readobj/LLVMBuild.txt ---------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-readobj parent = Tools required_libraries = all-targets BitReader Object
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ARMAttributeParser.h
//===--- ARMAttributeParser.h - ARM Attribute Information Printer ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_ARMATTRIBUTEPARSER_H #define LLVM_TOOLS_LLVM_READOBJ_ARMATTRIBUTEPARSER_H #include "StreamWriter.h" #include "llvm/Support/ARMBuildAttributes.h" namespace llvm { class StringRef; class ARMAttributeParser { StreamWriter &SW; struct DisplayHandler { ARMBuildAttrs::AttrType Attribute; void (ARMAttributeParser::*Routine)(ARMBuildAttrs::AttrType, const uint8_t *, uint32_t &); }; static const DisplayHandler DisplayRoutines[]; uint64_t ParseInteger(const uint8_t *Data, uint32_t &Offset); StringRef ParseString(const uint8_t *Data, uint32_t &Offset); void IntegerAttribute(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void StringAttribute(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void PrintAttribute(unsigned Tag, unsigned Value, StringRef ValueDesc); void CPU_arch(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void CPU_arch_profile(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ARM_ISA_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void THUMB_ISA_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void FP_arch(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void WMMX_arch(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void Advanced_SIMD_arch(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void PCS_config(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_PCS_R9_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_PCS_RW_data(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_PCS_RO_data(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_PCS_GOT_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_PCS_wchar_t(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_rounding(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_denormal(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_exceptions(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_user_exceptions(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_number_model(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_align_needed(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_align_preserved(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_enum_size(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_HardFP_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_VFP_args(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_WMMX_args(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_optimization_goals(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_optimization_goals(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void compatibility(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void CPU_unaligned_access(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void FP_HP_extension(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ABI_FP_16bit_format(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void MPextension_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void DIV_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void T2EE_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void Virtualization_use(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void nodefaults(ARMBuildAttrs::AttrType Tag, const uint8_t *Data, uint32_t &Offset); void ParseAttributeList(const uint8_t *Data, uint32_t &Offset, uint32_t Length); void ParseIndexList(const uint8_t *Data, uint32_t &Offset, SmallVectorImpl<uint8_t> &IndexList); void ParseSubsection(const uint8_t *Data, uint32_t Length); public: ARMAttributeParser(StreamWriter &SW) : SW(SW) {} void Parse(ArrayRef<uint8_t> Section); }; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ARMWinEHPrinter.h
//===--- ARMWinEHPrinter.h - Windows on ARM Unwind Information Printer ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_ARMWINEHPRINTER_H #define LLVM_TOOLS_LLVM_READOBJ_ARMWINEHPRINTER_H #include "StreamWriter.h" #include "llvm/Object/COFF.h" #include "llvm/Support/ErrorOr.h" namespace llvm { namespace ARM { namespace WinEH { class RuntimeFunction; class Decoder { static const size_t PDataEntrySize; StreamWriter &SW; raw_ostream &OS; struct RingEntry { uint8_t Mask; uint8_t Value; bool (Decoder::*Routine)(const uint8_t *, unsigned &, unsigned, bool); }; static const RingEntry Ring[]; bool opcode_0xxxxxxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_10Lxxxxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_1100xxxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11010Lxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11011Lxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11100xxx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_111010xx(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_1110110L(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11101110(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11101111(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11110101(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11110110(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11110111(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111000(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111001(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111010(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111011(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111100(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111101(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111110(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); bool opcode_11111111(const uint8_t *Opcodes, unsigned &Offset, unsigned Length, bool Prologue); void decodeOpcodes(ArrayRef<uint8_t> Opcodes, unsigned Offset, bool Prologue); void printRegisters(const std::pair<uint16_t, uint32_t> &RegisterMask); ErrorOr<object::SectionRef> getSectionContaining(const object::COFFObjectFile &COFF, uint64_t Address); ErrorOr<object::SymbolRef> getSymbol(const object::COFFObjectFile &COFF, uint64_t Address, bool FunctionOnly = false); ErrorOr<object::SymbolRef> getRelocatedSymbol(const object::COFFObjectFile &COFF, const object::SectionRef &Section, uint64_t Offset); bool dumpXDataRecord(const object::COFFObjectFile &COFF, const object::SectionRef &Section, uint64_t FunctionAddress, uint64_t VA); bool dumpUnpackedEntry(const object::COFFObjectFile &COFF, const object::SectionRef Section, uint64_t Offset, unsigned Index, const RuntimeFunction &Entry); bool dumpPackedEntry(const object::COFFObjectFile &COFF, const object::SectionRef Section, uint64_t Offset, unsigned Index, const RuntimeFunction &Entry); bool dumpProcedureDataEntry(const object::COFFObjectFile &COFF, const object::SectionRef Section, unsigned Entry, ArrayRef<uint8_t> Contents); void dumpProcedureData(const object::COFFObjectFile &COFF, const object::SectionRef Section); public: Decoder(StreamWriter &SW) : SW(SW), OS(SW.getOStream()) {} std::error_code dumpProcedureData(const object::COFFObjectFile &COFF); }; } } } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/Error.h
//===- Error.h - system_error extensions for llvm-readobj -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This declares a new error_category for the llvm-readobj tool. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_ERROR_H #define LLVM_TOOLS_LLVM_READOBJ_ERROR_H #include <system_error> namespace llvm { const std::error_category &readobj_category(); enum class readobj_error { success = 0, file_not_found, unsupported_file_format, unrecognized_file_format, unsupported_obj_file_format, unknown_symbol }; inline std::error_code make_error_code(readobj_error e) { return std::error_code(static_cast<int>(e), readobj_category()); } } // namespace llvm namespace std { template <> struct is_error_code_enum<llvm::readobj_error> : std::true_type {}; } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ARMWinEHPrinter.cpp
//===-- ARMWinEHPrinter.cpp - Windows on ARM EH Data Printer ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ARMWinEHPrinter.h" #include "Error.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/ARMWinEH.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace llvm::object; using namespace llvm::support; namespace llvm { raw_ostream &operator<<(raw_ostream &OS, const ARM::WinEH::ReturnType &RT) { switch (RT) { case ARM::WinEH::ReturnType::RT_POP: OS << "pop {pc}"; break; case ARM::WinEH::ReturnType::RT_B: OS << "b target"; break; case ARM::WinEH::ReturnType::RT_BW: OS << "b.w target"; break; case ARM::WinEH::ReturnType::RT_NoEpilogue: OS << "(no epilogue)"; break; } return OS; } } static std::string formatSymbol(StringRef Name, uint64_t Address, uint64_t Offset = 0) { std::string Buffer; raw_string_ostream OS(Buffer); if (!Name.empty()) OS << Name << " "; if (Offset) OS << format("+0x%X (0x%" PRIX64 ")", Offset, Address); else if (!Name.empty()) OS << format("(0x%" PRIX64 ")", Address); else OS << format("0x%" PRIX64, Address); return OS.str(); } namespace llvm { namespace ARM { namespace WinEH { const size_t Decoder::PDataEntrySize = sizeof(RuntimeFunction); // TODO name the uops more appropriately const Decoder::RingEntry Decoder::Ring[] = { { 0x80, 0x00, &Decoder::opcode_0xxxxxxx }, // UOP_STACK_FREE (16-bit) { 0xc0, 0x80, &Decoder::opcode_10Lxxxxx }, // UOP_POP (32-bit) { 0xf0, 0xc0, &Decoder::opcode_1100xxxx }, // UOP_STACK_SAVE (16-bit) { 0xf8, 0xd0, &Decoder::opcode_11010Lxx }, // UOP_POP (16-bit) { 0xf8, 0xd8, &Decoder::opcode_11011Lxx }, // UOP_POP (32-bit) { 0xf8, 0xe0, &Decoder::opcode_11100xxx }, // UOP_VPOP (32-bit) { 0xfc, 0xe8, &Decoder::opcode_111010xx }, // UOP_STACK_FREE (32-bit) { 0xfe, 0xec, &Decoder::opcode_1110110L }, // UOP_POP (16-bit) { 0xff, 0xee, &Decoder::opcode_11101110 }, // UOP_MICROSOFT_SPECIFIC (16-bit) // UOP_PUSH_MACHINE_FRAME // UOP_PUSH_CONTEXT // UOP_PUSH_TRAP_FRAME // UOP_REDZONE_RESTORE_LR { 0xff, 0xef, &Decoder::opcode_11101111 }, // UOP_LDRPC_POSTINC (32-bit) { 0xff, 0xf5, &Decoder::opcode_11110101 }, // UOP_VPOP (32-bit) { 0xff, 0xf6, &Decoder::opcode_11110110 }, // UOP_VPOP (32-bit) { 0xff, 0xf7, &Decoder::opcode_11110111 }, // UOP_STACK_RESTORE (16-bit) { 0xff, 0xf8, &Decoder::opcode_11111000 }, // UOP_STACK_RESTORE (16-bit) { 0xff, 0xf9, &Decoder::opcode_11111001 }, // UOP_STACK_RESTORE (32-bit) { 0xff, 0xfa, &Decoder::opcode_11111010 }, // UOP_STACK_RESTORE (32-bit) { 0xff, 0xfb, &Decoder::opcode_11111011 }, // UOP_NOP (16-bit) { 0xff, 0xfc, &Decoder::opcode_11111100 }, // UOP_NOP (32-bit) { 0xff, 0xfd, &Decoder::opcode_11111101 }, // UOP_NOP (16-bit) / END { 0xff, 0xfe, &Decoder::opcode_11111110 }, // UOP_NOP (32-bit) / END { 0xff, 0xff, &Decoder::opcode_11111111 }, // UOP_END }; void Decoder::printRegisters(const std::pair<uint16_t, uint32_t> &RegisterMask) { static const char * const GPRRegisterNames[16] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "ip", "sp", "lr", "pc", }; const uint16_t GPRMask = std::get<0>(RegisterMask); const uint16_t VFPMask = std::get<1>(RegisterMask); OS << '{'; bool Comma = false; for (unsigned RI = 0, RE = 11; RI < RE; ++RI) { if (GPRMask & (1 << RI)) { if (Comma) OS << ", "; OS << GPRRegisterNames[RI]; Comma = true; } } for (unsigned RI = 0, RE = 32; RI < RE; ++RI) { if (VFPMask & (1 << RI)) { if (Comma) OS << ", "; OS << "d" << unsigned(RI); Comma = true; } } for (unsigned RI = 11, RE = 16; RI < RE; ++RI) { if (GPRMask & (1 << RI)) { if (Comma) OS << ", "; OS << GPRRegisterNames[RI]; Comma = true; } } OS << '}'; } ErrorOr<object::SectionRef> Decoder::getSectionContaining(const COFFObjectFile &COFF, uint64_t VA) { for (const auto &Section : COFF.sections()) { uint64_t Address = Section.getAddress(); uint64_t Size = Section.getSize(); if (VA >= Address && (VA - Address) <= Size) return Section; } return readobj_error::unknown_symbol; } ErrorOr<object::SymbolRef> Decoder::getSymbol(const COFFObjectFile &COFF, uint64_t VA, bool FunctionOnly) { for (const auto &Symbol : COFF.symbols()) { if (FunctionOnly && Symbol.getType() != SymbolRef::ST_Function) continue; ErrorOr<uint64_t> Address = Symbol.getAddress(); if (std::error_code EC = Address.getError()) return EC; if (*Address == VA) return Symbol; } return readobj_error::unknown_symbol; } ErrorOr<SymbolRef> Decoder::getRelocatedSymbol(const COFFObjectFile &, const SectionRef &Section, uint64_t Offset) { for (const auto &Relocation : Section.relocations()) { uint64_t RelocationOffset = Relocation.getOffset(); if (RelocationOffset == Offset) return *Relocation.getSymbol(); } return readobj_error::unknown_symbol; } bool Decoder::opcode_0xxxxxxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint8_t Imm = OC[Offset] & 0x7f; SW.startLine() << format("0x%02x ; %s sp, #(%u * 4)\n", OC[Offset], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset; return false; } bool Decoder::opcode_10Lxxxxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned Link = (OC[Offset] & 0x20) >> 5; uint16_t RegisterMask = (Link << (Prologue ? 14 : 15)) | ((OC[Offset + 0] & 0x1f) << 8) | ((OC[Offset + 1] & 0xff) << 0); assert((~RegisterMask & (1 << 13)) && "sp must not be set"); assert((~RegisterMask & (1 << (Prologue ? 15 : 14))) && "pc must not be set"); SW.startLine() << format("0x%02x 0x%02x ; %s.w ", OC[Offset + 0], OC[Offset + 1], Prologue ? "push" : "pop"); printRegisters(std::make_pair(RegisterMask, 0)); OS << '\n'; ++Offset, ++Offset; return false; } bool Decoder::opcode_1100xxxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { if (Prologue) SW.startLine() << format("0x%02x ; mov r%u, sp\n", OC[Offset], OC[Offset] & 0xf); else SW.startLine() << format("0x%02x ; mov sp, r%u\n", OC[Offset], OC[Offset] & 0xf); ++Offset; return false; } bool Decoder::opcode_11010Lxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned Link = (OC[Offset] & 0x4) >> 3; unsigned Count = (OC[Offset] & 0x3); uint16_t GPRMask = (Link << (Prologue ? 14 : 15)) | (((1 << (Count + 1)) - 1) << 4); SW.startLine() << format("0x%02x ; %s ", OC[Offset], Prologue ? "push" : "pop"); printRegisters(std::make_pair(GPRMask, 0)); OS << '\n'; ++Offset; return false; } bool Decoder::opcode_11011Lxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned Link = (OC[Offset] & 0x4) >> 2; unsigned Count = (OC[Offset] & 0x3) + 4; uint16_t GPRMask = (Link << (Prologue ? 14 : 15)) | (((1 << (Count + 1)) - 1) << 4); SW.startLine() << format("0x%02x ; %s.w ", OC[Offset], Prologue ? "push" : "pop"); printRegisters(std::make_pair(GPRMask, 0)); OS << '\n'; ++Offset; return false; } bool Decoder::opcode_11100xxx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned High = (OC[Offset] & 0x7); uint32_t VFPMask = (((1 << (High + 1)) - 1) << 8); SW.startLine() << format("0x%02x ; %s ", OC[Offset], Prologue ? "vpush" : "vpop"); printRegisters(std::make_pair(0, VFPMask)); OS << '\n'; ++Offset; return false; } bool Decoder::opcode_111010xx(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint16_t Imm = ((OC[Offset + 0] & 0x03) << 8) | ((OC[Offset + 1] & 0xff) << 0); SW.startLine() << format("0x%02x 0x%02x ; %s.w sp, #(%u * 4)\n", OC[Offset + 0], OC[Offset + 1], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset, ++Offset; return false; } bool Decoder::opcode_1110110L(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint8_t GPRMask = ((OC[Offset + 0] & 0x01) << (Prologue ? 14 : 15)) | ((OC[Offset + 1] & 0xff) << 0); SW.startLine() << format("0x%02x 0x%02x ; %s ", OC[Offset + 0], OC[Offset + 1], Prologue ? "push" : "pop"); printRegisters(std::make_pair(GPRMask, 0)); OS << '\n'; ++Offset, ++Offset; return false; } bool Decoder::opcode_11101110(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { assert(!Prologue && "may not be used in prologue"); if (OC[Offset + 1] & 0xf0) SW.startLine() << format("0x%02x 0x%02x ; reserved\n", OC[Offset + 0], OC[Offset + 1]); else SW.startLine() << format("0x%02x 0x%02x ; microsoft-specific (type: %u)\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] & 0x0f); ++Offset, ++Offset; return false; } bool Decoder::opcode_11101111(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { assert(!Prologue && "may not be used in prologue"); if (OC[Offset + 1] & 0xf0) SW.startLine() << format("0x%02x 0x%02x ; reserved\n", OC[Offset + 0], OC[Offset + 1]); else SW.startLine() << format("0x%02x 0x%02x ; ldr.w lr, [sp], #%u\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 1] << 2); ++Offset, ++Offset; return false; } bool Decoder::opcode_11110101(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned Start = (OC[Offset + 1] & 0xf0) >> 4; unsigned End = (OC[Offset + 1] & 0x0f) >> 0; uint32_t VFPMask = ((1 << (End - Start)) - 1) << Start; SW.startLine() << format("0x%02x 0x%02x ; %s ", OC[Offset + 0], OC[Offset + 1], Prologue ? "vpush" : "vpop"); printRegisters(std::make_pair(0, VFPMask)); OS << '\n'; ++Offset, ++Offset; return false; } bool Decoder::opcode_11110110(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { unsigned Start = (OC[Offset + 1] & 0xf0) >> 4; unsigned End = (OC[Offset + 1] & 0x0f) >> 0; uint32_t VFPMask = ((1 << (End - Start)) - 1) << 16; SW.startLine() << format("0x%02x 0x%02x ; %s ", OC[Offset + 0], OC[Offset + 1], Prologue ? "vpush" : "vpop"); printRegisters(std::make_pair(0, VFPMask)); OS << '\n'; ++Offset, ++Offset; return false; } bool Decoder::opcode_11110111(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0); SW.startLine() << format("0x%02x 0x%02x 0x%02x ; %s sp, sp, #(%u * 4)\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset, ++Offset, ++Offset; return false; } bool Decoder::opcode_11111000(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint32_t Imm = (OC[Offset + 1] << 16) | (OC[Offset + 2] << 8) | (OC[Offset + 3] << 0); SW.startLine() << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s sp, sp, #(%u * 4)\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset, ++Offset, ++Offset, ++Offset; return false; } bool Decoder::opcode_11111001(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint32_t Imm = (OC[Offset + 1] << 8) | (OC[Offset + 2] << 0); SW.startLine() << format("0x%02x 0x%02x 0x%02x ; %s.w sp, sp, #(%u * 4)\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset, ++Offset, ++Offset; return false; } bool Decoder::opcode_11111010(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { uint32_t Imm = (OC[Offset + 1] << 16) | (OC[Offset + 2] << 8) | (OC[Offset + 3] << 0); SW.startLine() << format("0x%02x 0x%02x 0x%02x 0x%02x ; %s.w sp, sp, #(%u * 4)\n", OC[Offset + 0], OC[Offset + 1], OC[Offset + 2], OC[Offset + 3], static_cast<const char *>(Prologue ? "sub" : "add"), Imm); ++Offset, ++Offset, ++Offset, ++Offset; return false; } bool Decoder::opcode_11111011(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { SW.startLine() << format("0x%02x ; nop\n", OC[Offset]); ++Offset; return false; } bool Decoder::opcode_11111100(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { SW.startLine() << format("0x%02x ; nop.w\n", OC[Offset]); ++Offset; return false; } bool Decoder::opcode_11111101(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { SW.startLine() << format("0x%02x ; b\n", OC[Offset]); ++Offset; return true; } bool Decoder::opcode_11111110(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { SW.startLine() << format("0x%02x ; b.w\n", OC[Offset]); ++Offset; return true; } bool Decoder::opcode_11111111(const uint8_t *OC, unsigned &Offset, unsigned Length, bool Prologue) { ++Offset; return true; } void Decoder::decodeOpcodes(ArrayRef<uint8_t> Opcodes, unsigned Offset, bool Prologue) { assert((!Prologue || Offset == 0) && "prologue should always use offset 0"); bool Terminated = false; for (unsigned OI = Offset, OE = Opcodes.size(); !Terminated && OI < OE; ) { for (unsigned DI = 0;; ++DI) { if ((Opcodes[OI] & Ring[DI].Mask) == Ring[DI].Value) { Terminated = (this->*Ring[DI].Routine)(Opcodes.data(), OI, 0, Prologue); break; } assert(DI < array_lengthof(Ring) && "unhandled opcode"); } } } bool Decoder::dumpXDataRecord(const COFFObjectFile &COFF, const SectionRef &Section, uint64_t FunctionAddress, uint64_t VA) { ArrayRef<uint8_t> Contents; if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents)) return false; uint64_t SectionVA = Section.getAddress(); uint64_t Offset = VA - SectionVA; const ulittle32_t *Data = reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset); const ExceptionDataRecord XData(Data); DictScope XRS(SW, "ExceptionData"); SW.printNumber("FunctionLength", XData.FunctionLength() << 1); SW.printNumber("Version", XData.Vers()); SW.printBoolean("ExceptionData", XData.X()); SW.printBoolean("EpiloguePacked", XData.E()); SW.printBoolean("Fragment", XData.F()); SW.printNumber(XData.E() ? "EpilogueOffset" : "EpilogueScopes", XData.EpilogueCount()); SW.printNumber("ByteCodeLength", static_cast<uint64_t>(XData.CodeWords() * sizeof(uint32_t))); if (XData.E()) { ArrayRef<uint8_t> UC = XData.UnwindByteCode(); if (!XData.F()) { ListScope PS(SW, "Prologue"); decodeOpcodes(UC, 0, /*Prologue=*/true); } if (XData.EpilogueCount()) { ListScope ES(SW, "Epilogue"); decodeOpcodes(UC, XData.EpilogueCount(), /*Prologue=*/false); } } else { ArrayRef<ulittle32_t> EpilogueScopes = XData.EpilogueScopes(); ListScope ESS(SW, "EpilogueScopes"); for (const EpilogueScope ES : EpilogueScopes) { DictScope ESES(SW, "EpilogueScope"); SW.printNumber("StartOffset", ES.EpilogueStartOffset()); SW.printNumber("Condition", ES.Condition()); SW.printNumber("EpilogueStartIndex", ES.EpilogueStartIndex()); ListScope Opcodes(SW, "Opcodes"); decodeOpcodes(XData.UnwindByteCode(), ES.EpilogueStartIndex(), /*Prologue=*/false); } } if (XData.X()) { const uint32_t Address = XData.ExceptionHandlerRVA(); const uint32_t Parameter = XData.ExceptionHandlerParameter(); const size_t HandlerOffset = HeaderWords(XData) + (XData.E() ? 0 : XData.EpilogueCount()) + XData.CodeWords(); ErrorOr<SymbolRef> Symbol = getRelocatedSymbol(COFF, Section, HandlerOffset * sizeof(uint32_t)); if (!Symbol) Symbol = getSymbol(COFF, Address, /*FunctionOnly=*/true); ErrorOr<StringRef> Name = Symbol->getName(); if (std::error_code EC = Name.getError()) report_fatal_error(EC.message()); ListScope EHS(SW, "ExceptionHandler"); SW.printString("Routine", formatSymbol(*Name, Address)); SW.printHex("Parameter", Parameter); } return true; } bool Decoder::dumpUnpackedEntry(const COFFObjectFile &COFF, const SectionRef Section, uint64_t Offset, unsigned Index, const RuntimeFunction &RF) { assert(RF.Flag() == RuntimeFunctionFlag::RFF_Unpacked && "packed entry cannot be treated as an unpacked entry"); ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset); if (!Function) Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true); ErrorOr<SymbolRef> XDataRecord = getRelocatedSymbol(COFF, Section, Offset + 4); if (!XDataRecord) XDataRecord = getSymbol(COFF, RF.ExceptionInformationRVA()); if (!RF.BeginAddress && !Function) return false; if (!RF.UnwindData && !XDataRecord) return false; StringRef FunctionName; uint64_t FunctionAddress; if (Function) { ErrorOr<StringRef> FunctionNameOrErr = Function->getName(); if (std::error_code EC = FunctionNameOrErr.getError()) report_fatal_error(EC.message()); FunctionName = *FunctionNameOrErr; ErrorOr<uint64_t> FunctionAddressOrErr = Function->getAddress(); if (std::error_code EC = FunctionAddressOrErr.getError()) report_fatal_error(EC.message()); FunctionAddress = *FunctionAddressOrErr; } else { const pe32_header *PEHeader; if (COFF.getPE32Header(PEHeader)) return false; FunctionAddress = PEHeader->ImageBase + RF.BeginAddress; } SW.printString("Function", formatSymbol(FunctionName, FunctionAddress)); if (XDataRecord) { ErrorOr<StringRef> Name = XDataRecord->getName(); if (std::error_code EC = Name.getError()) report_fatal_error(EC.message()); ErrorOr<uint64_t> AddressOrErr = XDataRecord->getAddress(); if (std::error_code EC = AddressOrErr.getError()) report_fatal_error(EC.message()); uint64_t Address = *AddressOrErr; SW.printString("ExceptionRecord", formatSymbol(*Name, Address)); section_iterator SI = COFF.section_end(); if (XDataRecord->getSection(SI)) return false; return dumpXDataRecord(COFF, *SI, FunctionAddress, Address); } else { const pe32_header *PEHeader; if (COFF.getPE32Header(PEHeader)) return false; uint64_t Address = PEHeader->ImageBase + RF.ExceptionInformationRVA(); SW.printString("ExceptionRecord", formatSymbol("", Address)); ErrorOr<SectionRef> Section = getSectionContaining(COFF, RF.ExceptionInformationRVA()); if (!Section) return false; return dumpXDataRecord(COFF, *Section, FunctionAddress, RF.ExceptionInformationRVA()); } } bool Decoder::dumpPackedEntry(const object::COFFObjectFile &COFF, const SectionRef Section, uint64_t Offset, unsigned Index, const RuntimeFunction &RF) { assert((RF.Flag() == RuntimeFunctionFlag::RFF_Packed || RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "unpacked entry cannot be treated as a packed entry"); ErrorOr<SymbolRef> Function = getRelocatedSymbol(COFF, Section, Offset); if (!Function) Function = getSymbol(COFF, RF.BeginAddress, /*FunctionOnly=*/true); StringRef FunctionName; uint64_t FunctionAddress; if (Function) { ErrorOr<StringRef> FunctionNameOrErr = Function->getName(); if (std::error_code EC = FunctionNameOrErr.getError()) report_fatal_error(EC.message()); FunctionName = *FunctionNameOrErr; ErrorOr<uint64_t> FunctionAddressOrErr = Function->getAddress(); FunctionAddress = *FunctionAddressOrErr; } else { const pe32_header *PEHeader; if (COFF.getPE32Header(PEHeader)) return false; FunctionAddress = PEHeader->ImageBase + RF.BeginAddress; } SW.printString("Function", formatSymbol(FunctionName, FunctionAddress)); SW.printBoolean("Fragment", RF.Flag() == RuntimeFunctionFlag::RFF_PackedFragment); SW.printNumber("FunctionLength", RF.FunctionLength()); SW.startLine() << "ReturnType: " << RF.Ret() << '\n'; SW.printBoolean("HomedParameters", RF.H()); SW.startLine() << "SavedRegisters: "; printRegisters(SavedRegisterMask(RF)); OS << '\n'; SW.printNumber("StackAdjustment", StackAdjustment(RF) << 2); return true; } bool Decoder::dumpProcedureDataEntry(const COFFObjectFile &COFF, const SectionRef Section, unsigned Index, ArrayRef<uint8_t> Contents) { uint64_t Offset = PDataEntrySize * Index; const ulittle32_t *Data = reinterpret_cast<const ulittle32_t *>(Contents.data() + Offset); const RuntimeFunction Entry(Data); DictScope RFS(SW, "RuntimeFunction"); if (Entry.Flag() == RuntimeFunctionFlag::RFF_Unpacked) return dumpUnpackedEntry(COFF, Section, Offset, Index, Entry); return dumpPackedEntry(COFF, Section, Offset, Index, Entry); } void Decoder::dumpProcedureData(const COFFObjectFile &COFF, const SectionRef Section) { ArrayRef<uint8_t> Contents; if (COFF.getSectionContents(COFF.getCOFFSection(Section), Contents)) return; if (Contents.size() % PDataEntrySize) { errs() << ".pdata content is not " << PDataEntrySize << "-byte aligned\n"; return; } for (unsigned EI = 0, EE = Contents.size() / PDataEntrySize; EI < EE; ++EI) if (!dumpProcedureDataEntry(COFF, Section, EI, Contents)) break; } std::error_code Decoder::dumpProcedureData(const COFFObjectFile &COFF) { for (const auto &Section : COFF.sections()) { StringRef SectionName; if (std::error_code EC = COFF.getSectionName(COFF.getCOFFSection(Section), SectionName)) return EC; if (SectionName.startswith(".pdata")) dumpProcedureData(COFF, Section); } return std::error_code(); } } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/StreamWriter.h
//===-- StreamWriter.h ----------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_STREAMWRITER_H #define LLVM_TOOLS_LLVM_READOBJ_STREAMWRITER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; using namespace llvm::support; namespace llvm { template<typename T> struct EnumEntry { StringRef Name; T Value; }; struct HexNumber { // To avoid sign-extension we have to explicitly cast to the appropriate // unsigned type. The overloads are here so that every type that is implicitly // convertible to an integer (including enums and endian helpers) can be used // without requiring type traits or call-site changes. HexNumber(int8_t Value) : Value(static_cast<uint8_t >(Value)) { } HexNumber(int16_t Value) : Value(static_cast<uint16_t>(Value)) { } HexNumber(int32_t Value) : Value(static_cast<uint32_t>(Value)) { } HexNumber(int64_t Value) : Value(static_cast<uint64_t>(Value)) { } HexNumber(uint8_t Value) : Value(Value) { } HexNumber(uint16_t Value) : Value(Value) { } HexNumber(uint32_t Value) : Value(Value) { } HexNumber(uint64_t Value) : Value(Value) { } uint64_t Value; }; raw_ostream &operator<<(raw_ostream &OS, const HexNumber& Value); class StreamWriter { public: StreamWriter(raw_ostream &OS) : OS(OS) , IndentLevel(0) { } void flush() { OS.flush(); } void indent(int Levels = 1) { IndentLevel += Levels; } void unindent(int Levels = 1) { IndentLevel = std::max(0, IndentLevel - Levels); } void printIndent() { for (int i = 0; i < IndentLevel; ++i) OS << " "; } template<typename T> HexNumber hex(T Value) { return HexNumber(Value); } template<typename T, typename TEnum> void printEnum(StringRef Label, T Value, ArrayRef<EnumEntry<TEnum> > EnumValues) { StringRef Name; bool Found = false; for (const auto &EnumItem : EnumValues) { if (EnumItem.Value == Value) { Name = EnumItem.Name; Found = true; break; } } if (Found) { startLine() << Label << ": " << Name << " (" << hex(Value) << ")\n"; } else { startLine() << Label << ": " << hex(Value) << "\n"; } } template <typename T, typename TFlag> void printFlags(StringRef Label, T Value, ArrayRef<EnumEntry<TFlag>> Flags, TFlag EnumMask1 = {}, TFlag EnumMask2 = {}, TFlag EnumMask3 = {}) { typedef EnumEntry<TFlag> FlagEntry; typedef SmallVector<FlagEntry, 10> FlagVector; FlagVector SetFlags; for (const auto &Flag : Flags) { if (Flag.Value == 0) continue; TFlag EnumMask{}; if (Flag.Value & EnumMask1) EnumMask = EnumMask1; else if (Flag.Value & EnumMask2) EnumMask = EnumMask2; else if (Flag.Value & EnumMask3) EnumMask = EnumMask3; bool IsEnum = (Flag.Value & EnumMask) != 0; if ((!IsEnum && (Value & Flag.Value) == Flag.Value) || (IsEnum && (Value & EnumMask) == Flag.Value)) { SetFlags.push_back(Flag); } } std::sort(SetFlags.begin(), SetFlags.end(), &flagName<TFlag>); startLine() << Label << " [ (" << hex(Value) << ")\n"; for (const auto &Flag : SetFlags) { startLine() << " " << Flag.Name << " (" << hex(Flag.Value) << ")\n"; } startLine() << "]\n"; } template<typename T> void printFlags(StringRef Label, T Value) { startLine() << Label << " [ (" << hex(Value) << ")\n"; uint64_t Flag = 1; uint64_t Curr = Value; while (Curr > 0) { if (Curr & 1) startLine() << " " << hex(Flag) << "\n"; Curr >>= 1; Flag <<= 1; } startLine() << "]\n"; } void printNumber(StringRef Label, uint64_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, uint32_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, uint16_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, uint8_t Value) { startLine() << Label << ": " << unsigned(Value) << "\n"; } void printNumber(StringRef Label, int64_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, int32_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, int16_t Value) { startLine() << Label << ": " << Value << "\n"; } void printNumber(StringRef Label, int8_t Value) { startLine() << Label << ": " << int(Value) << "\n"; } void printBoolean(StringRef Label, bool Value) { startLine() << Label << ": " << (Value ? "Yes" : "No") << '\n'; } template <typename T> void printList(StringRef Label, const T &List) { startLine() << Label << ": ["; bool Comma = false; for (const auto &Item : List) { if (Comma) OS << ", "; OS << Item; Comma = true; } OS << "]\n"; } template<typename T> void printHex(StringRef Label, T Value) { startLine() << Label << ": " << hex(Value) << "\n"; } template<typename T> void printHex(StringRef Label, StringRef Str, T Value) { startLine() << Label << ": " << Str << " (" << hex(Value) << ")\n"; } void printString(StringRef Label, StringRef Value) { startLine() << Label << ": " << Value << "\n"; } void printString(StringRef Label, const std::string &Value) { startLine() << Label << ": " << Value << "\n"; } template<typename T> void printNumber(StringRef Label, StringRef Str, T Value) { startLine() << Label << ": " << Str << " (" << Value << ")\n"; } void printBinary(StringRef Label, StringRef Str, ArrayRef<uint8_t> Value) { printBinaryImpl(Label, Str, Value, false); } void printBinary(StringRef Label, StringRef Str, ArrayRef<char> Value) { auto V = makeArrayRef(reinterpret_cast<const uint8_t*>(Value.data()), Value.size()); printBinaryImpl(Label, Str, V, false); } void printBinary(StringRef Label, ArrayRef<uint8_t> Value) { printBinaryImpl(Label, StringRef(), Value, false); } void printBinary(StringRef Label, ArrayRef<char> Value) { auto V = makeArrayRef(reinterpret_cast<const uint8_t*>(Value.data()), Value.size()); printBinaryImpl(Label, StringRef(), V, false); } void printBinary(StringRef Label, StringRef Value) { auto V = makeArrayRef(reinterpret_cast<const uint8_t*>(Value.data()), Value.size()); printBinaryImpl(Label, StringRef(), V, false); } void printBinaryBlock(StringRef Label, StringRef Value) { auto V = makeArrayRef(reinterpret_cast<const uint8_t*>(Value.data()), Value.size()); printBinaryImpl(Label, StringRef(), V, true); } raw_ostream& startLine() { printIndent(); return OS; } raw_ostream& getOStream() { return OS; } private: template<typename T> static bool flagName(const EnumEntry<T>& lhs, const EnumEntry<T>& rhs) { return lhs.Name < rhs.Name; } void printBinaryImpl(StringRef Label, StringRef Str, ArrayRef<uint8_t> Value, bool Block); raw_ostream &OS; int IndentLevel; }; struct DictScope { DictScope(StreamWriter& W, StringRef N) : W(W) { W.startLine() << N << " {\n"; W.indent(); } ~DictScope() { W.unindent(); W.startLine() << "}\n"; } StreamWriter& W; }; struct ListScope { ListScope(StreamWriter& W, StringRef N) : W(W) { W.startLine() << N << " [\n"; W.indent(); } ~ListScope() { W.unindent(); W.startLine() << "]\n"; } StreamWriter& W; }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/ObjDumper.cpp
//===-- ObjDumper.cpp - Base dumper class -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements ObjDumper. /// //===----------------------------------------------------------------------===// #include "ObjDumper.h" #include "Error.h" #include "StreamWriter.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/raw_ostream.h" namespace llvm { ObjDumper::ObjDumper(StreamWriter& Writer) : W(Writer) { } ObjDumper::~ObjDumper() { } } // namespace llvm
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-readobj/StackMapPrinter.h
//===-------- StackMapPrinter.h - Pretty-print stackmaps --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_READOBJ_STACKMAPPRINTER_H #define LLVM_TOOLS_LLVM_READOBJ_STACKMAPPRINTER_H #include "llvm/Object/StackMapParser.h" namespace llvm { // Pretty print a stackmap to the given ostream. template <typename OStreamT, typename StackMapParserT> void prettyPrintStackMap(OStreamT &OS, const StackMapParserT &SMP) { OS << "LLVM StackMap Version: " << SMP.getVersion() << "\nNum Functions: " << SMP.getNumFunctions(); // Functions: for (const auto &F : SMP.functions()) OS << "\n Function address: " << F.getFunctionAddress() << ", stack size: " << F.getStackSize(); // Constants: OS << "\nNum Constants: " << SMP.getNumConstants(); unsigned ConstantIndex = 0; for (const auto &C : SMP.constants()) OS << "\n #" << ++ConstantIndex << ": " << C.getValue(); // Records: OS << "\nNum Records: " << SMP.getNumRecords(); for (const auto &R : SMP.records()) { OS << "\n Record ID: " << R.getID() << ", instruction offset: " << R.getInstructionOffset() << "\n " << R.getNumLocations() << " locations:"; unsigned LocationIndex = 0; for (const auto &Loc : R.locations()) { OS << "\n #" << ++LocationIndex << ": "; switch (Loc.getKind()) { case StackMapParserT::LocationKind::Register: OS << "Register R#" << Loc.getDwarfRegNum(); break; case StackMapParserT::LocationKind::Direct: OS << "Direct R#" << Loc.getDwarfRegNum() << " + " << Loc.getOffset(); break; case StackMapParserT::LocationKind::Indirect: OS << "Indirect [R#" << Loc.getDwarfRegNum() << " + " << Loc.getOffset() << "]"; break; case StackMapParserT::LocationKind::Constant: OS << "Constant " << Loc.getSmallConstant(); break; case StackMapParserT::LocationKind::ConstantIndex: OS << "ConstantIndex #" << Loc.getConstantIndex() << " (" << SMP.getConstant(Loc.getConstantIndex()).getValue() << ")"; break; } } OS << "\n " << R.getNumLiveOuts() << " live-outs: [ "; for (const auto &LO : R.liveouts()) OS << "R#" << LO.getDwarfRegNum() << " (" << LO.getSizeInBytes() << "-bytes) "; OS << "]\n"; } OS << "\n"; } } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/msbuild/Microsoft.Cpp.Win32.llvm.props.in
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\@VS_VERSION@\Microsoft.Cpp.$(Platform).@[email protected]" Condition="Exists('$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\@VS_VERSION@\Microsoft.Cpp.$(Platform).@[email protected]')"/> <Import Project="$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\@VS_VERSION@\Toolset.props" Condition="Exists('$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\@VS_VERSION@\Toolset.props')"/> <PropertyGroup> <LLVMInstallDir>$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\LLVM\@REG_KEY@)</LLVMInstallDir> <LLVMInstallDir Condition="'$(LLVMInstallDir)' == ''">$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\LLVM\@REG_KEY@)</LLVMInstallDir> <ExecutablePath>$(LLVMInstallDir)\msbuild-bin;$(ExecutablePath)</ExecutablePath> <LibraryPath>$(LLVMInstallDir)\lib\clang\@LIB_PATH_VERSION@\lib\windows;$(LibraryPath)</LibraryPath> </PropertyGroup> <ItemDefinitionGroup> <ClCompile> <!-- Set the value of _MSC_VER to claim for compatibility --> <AdditionalOptions>-@mflag@ -fmsc-version=@MSC_VERSION@ %(AdditionalOptions)</AdditionalOptions> </ClCompile> </ItemDefinitionGroup> </Project>
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/msbuild/CMakeLists.txt
if (WIN32) # CPack will install a registry key in this format that we wish to reference. set(REG_KEY "${CPACK_PACKAGE_INSTALL_REGISTRY_KEY}") set(LIB_PATH_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}") foreach (platform "Win32" "x64") set(prop_file_in "Microsoft.Cpp.Win32.llvm.props.in") set(prop_file_v100 "Microsoft.Cpp.${platform}.LLVM-vs2010.props") set(prop_file_v110 "Microsoft.Cpp.${platform}.LLVM-vs2012.props") set(prop_file_v110_xp "Microsoft.Cpp.${platform}.LLVM-vs2012_xp.props") set(prop_file_v120 "toolset-vs2013.props") set(prop_file_v120_xp "toolset-vs2013_xp.props") set(prop_file_v140 "toolset-vs2014.props") set(prop_file_v140_xp "toolset-vs2014_xp.props") if (platform STREQUAL "Win32") set(mflag "m32") else() set(mflag "m64") endif() set(VS_VERSION "v100") set(MSC_VERSION "1600") configure_file(${prop_file_in} ${platform}/${prop_file_v100}) set(VS_VERSION "v110") set(MSC_VERSION "1700") configure_file(${prop_file_in} ${platform}/${prop_file_v110}) set(VS_VERSION "v110_xp") configure_file(${prop_file_in} ${platform}/${prop_file_v110_xp}) set(VS_VERSION "v120") set(MSC_VERSION "1800") configure_file(${prop_file_in} ${platform}/${prop_file_v120}) set(VS_VERSION "v120_xp") configure_file(${prop_file_in} ${platform}/${prop_file_v120_xp}) set(VS_VERSION "v140") set(MSC_VERSION "1900") configure_file(${prop_file_in} ${platform}/${prop_file_v140}) set(VS_VERSION "v140_xp") configure_file(${prop_file_in} ${platform}/${prop_file_v140_xp}) set(VS_VERSION) set(MSC_VERSION) set(mflag) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v100}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v110}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v110_xp}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v120}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v120_xp}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v140}" DESTINATION tools/msbuild/${platform}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${platform}/${prop_file_v140_xp}" DESTINATION tools/msbuild/${platform}) install(FILES "Microsoft.Cpp.Win32.LLVM-vs2010.targets" DESTINATION "tools/msbuild/${platform}" RENAME "Microsoft.Cpp.${platform}.LLVM-vs2010.targets") install(FILES "Microsoft.Cpp.Win32.LLVM-vs2012.targets" DESTINATION "tools/msbuild/${platform}" RENAME "Microsoft.Cpp.${platform}.LLVM-vs2012.targets") install(FILES "Microsoft.Cpp.Win32.LLVM-vs2012_xp.targets" DESTINATION "tools/msbuild/${platform}" RENAME "Microsoft.Cpp.${platform}.LLVM-vs2012_xp.targets") install(FILES "toolset-vs2013.targets" DESTINATION "tools/msbuild/${platform}") install(FILES "toolset-vs2013_xp.targets" DESTINATION "tools/msbuild/${platform}") install(FILES "toolset-vs2014.targets" DESTINATION "tools/msbuild/${platform}") install(FILES "toolset-vs2014_xp.targets" DESTINATION "tools/msbuild/${platform}") endforeach() set(LIB_PATH_VERSION) set(REG_KEY) install(DIRECTORY . DESTINATION tools/msbuild FILES_MATCHING PATTERN "*.bat" PATTERN ".svn" EXCLUDE ) endif()
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/msbuild/uninstall.bat
@echo off echo Uninstalling MSVC integration... REM CD to the directory of this batch file. cd /d %~dp0 set PLATFORM=None :LOOPHEAD IF %PLATFORM% == x64 GOTO LOOPEND IF %PLATFORM% == Win32 SET PLATFORM=x64 IF %PLATFORM% == None SET PLATFORM=Win32 SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2010 del %D%\LLVM-vs2010\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.props IF EXIST %D%\LLVM-vs2010 del %D%\LLVM-vs2010\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.targets IF EXIST %D%\LLVM-vs2010 rmdir %D%\LLVM-vs2010 SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2010 del %D%\LLVM-vs2010\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.props IF EXIST %D%\LLVM-vs2010 del %D%\LLVM-vs2010\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.targets IF EXIST %D%\LLVM-vs2010 rmdir %D%\LLVM-vs2010 SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2012 del %D%\LLVM-vs2012\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.props IF EXIST %D%\LLVM-vs2012 del %D%\LLVM-vs2012\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.targets IF EXIST %D%\LLVM-vs2012 rmdir %D%\LLVM-vs2012 IF EXIST %D%\LLVM-vs2012_xp del %D%\LLVM-vs2012_xp\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.props IF EXIST %D%\LLVM-vs2012_xp del %D%\LLVM-vs2012_xp\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.targets IF EXIST %D%\LLVM-vs2012_xp rmdir %D%\LLVM-vs2012_xp SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2012 del %D%\LLVM-vs2012\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.props IF EXIST %D%\LLVM-vs2012 del %D%\LLVM-vs2012\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.targets IF EXIST %D%\LLVM-vs2012 rmdir %D%\LLVM-vs2012 IF EXIST %D%\LLVM-vs2012_xp del %D%\LLVM-vs2012_xp\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.props IF EXIST %D%\LLVM-vs2012_xp del %D%\LLVM-vs2012_xp\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.targets IF EXIST %D%\LLVM-vs2012_xp rmdir %D%\LLVM-vs2012_xp SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V120\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2013 del %D%\LLVM-vs2013\toolset.props IF EXIST %D%\LLVM-vs2013 del %D%\LLVM-vs2013\toolset.targets IF EXIST %D%\LLVM-vs2013 rmdir %D%\LLVM-vs2013 IF EXIST %D%\LLVM-vs2013_xp del %D%\LLVM-vs2013_xp\toolset.props IF EXIST %D%\LLVM-vs2013_xp del %D%\LLVM-vs2013_xp\toolset.targets IF EXIST %D%\LLVM-vs2013_xp rmdir %D%\LLVM-vs2013_xp SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V120\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2013 del %D%\LLVM-vs2013\toolset.props IF EXIST %D%\LLVM-vs2013 del %D%\LLVM-vs2013\toolset.targets IF EXIST %D%\LLVM-vs2013 rmdir %D%\LLVM-vs2013 IF EXIST %D%\LLVM-vs2013_xp del %D%\LLVM-vs2013_xp\toolset.props IF EXIST %D%\LLVM-vs2013_xp del %D%\LLVM-vs2013_xp\toolset.targets IF EXIST %D%\LLVM-vs2013_xp rmdir %D%\LLVM-vs2013_xp SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2014 del %D%\LLVM-vs2014\toolset.props IF EXIST %D%\LLVM-vs2014 del %D%\LLVM-vs2014\toolset.targets IF EXIST %D%\LLVM-vs2014 rmdir %D%\LLVM-vs2014 IF EXIST %D%\LLVM-vs2014_xp del %D%\LLVM-vs2014_xp\toolset.props IF EXIST %D%\LLVM-vs2014_xp del %D%\LLVM-vs2014_xp\toolset.targets IF EXIST %D%\LLVM-vs2014_xp rmdir %D%\LLVM-vs2014_xp SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D%\LLVM-vs2014 del %D%\LLVM-vs2014\toolset.props IF EXIST %D%\LLVM-vs2014 del %D%\LLVM-vs2014\toolset.targets IF EXIST %D%\LLVM-vs2014 rmdir %D%\LLVM-vs2014 IF EXIST %D%\LLVM-vs2014_xp del %D%\LLVM-vs2014_xp\toolset.props IF EXIST %D%\LLVM-vs2014_xp del %D%\LLVM-vs2014_xp\toolset.targets IF EXIST %D%\LLVM-vs2014_xp rmdir %D%\LLVM-vs2014_xp GOTO LOOPHEAD :LOOPEND echo Done!
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/msbuild/install.bat
@echo off echo Installing MSVC integration... set SUCCESS=0 REM Change to the directory of this batch file. cd /d %~dp0 REM Loop over the two platforms in awkward batch file fashion. set PLATFORM=None :PLATFORMLOOPHEAD IF %PLATFORM% == x64 GOTO PLATFORMLOOPEND IF %PLATFORM% == Win32 SET PLATFORM=x64 IF %PLATFORM% == None SET PLATFORM=Win32 REM Search for the MSBuild toolsets directory. SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V100 SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V100 :TRY_V110 SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V110 SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V110 :TRY_V120 SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V120\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V120 SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V120\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V120 :TRY_V140 SET D="%ProgramFiles%\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V140 SET D="%ProgramFiles(x86)%\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\%PLATFORM%\PlatformToolsets" IF EXIST %D% GOTO FOUND_V140 :TRY_V150 GOTO PLATFORMLOOPHEAD :PLATFORMLOOPEND IF %SUCCESS% == 1 goto DONE echo Failed to find MSBuild toolsets directory. goto FAILED :FOUND_V100 REM Routine for installing v100 toolchain. IF NOT EXIST %D%\LLVM-vs2010 mkdir %D%\LLVM-vs2010 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.props %D%\LLVM-vs2010 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2010.targets %D%\LLVM-vs2010 IF NOT %ERRORLEVEL% == 0 GOTO FAILED set SUCCESS=1 GOTO TRY_V110 :FOUND_V110 REM Routine for installing v110 toolchain. IF NOT EXIST %D%\LLVM-vs2012 mkdir %D%\LLVM-vs2012 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.props %D%\LLVM-vs2012 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012.targets %D%\LLVM-vs2012 IF NOT %ERRORLEVEL% == 0 GOTO FAILED IF NOT EXIST %D%\LLVM-vs2012_xp mkdir %D%\LLVM-vs2012_xp IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.props %D%\LLVM-vs2012_xp IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\Microsoft.Cpp.%PLATFORM%.LLVM-vs2012_xp.targets %D%\LLVM-vs2012_xp IF NOT %ERRORLEVEL% == 0 GOTO FAILED set SUCCESS=1 GOTO TRY_V120 :FOUND_V120 REM Routine for installing v120 toolchain. IF NOT EXIST %D%\LLVM-vs2013 mkdir %D%\LLVM-vs2013 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2013.props %D%\LLVM-vs2013\toolset.props IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2013.targets %D%\LLVM-vs2013\toolset.targets IF NOT %ERRORLEVEL% == 0 GOTO FAILED IF NOT EXIST %D%\LLVM-vs2013_xp mkdir %D%\LLVM-vs2013_xp IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2013_xp.props %D%\LLVM-vs2013_xp\toolset.props IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2013_xp.targets %D%\LLVM-vs2013_xp\toolset.targets IF NOT %ERRORLEVEL% == 0 GOTO FAILED set SUCCESS=1 GOTO TRY_V140 :FOUND_V140 REM Routine for installing v140 toolchain. IF NOT EXIST %D%\LLVM-vs2014 mkdir %D%\LLVM-vs2014 IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2014.props %D%\LLVM-vs2014\toolset.props IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2014.targets %D%\LLVM-vs2014\toolset.targets IF NOT %ERRORLEVEL% == 0 GOTO FAILED IF NOT EXIST %D%\LLVM-vs2014_xp mkdir %D%\LLVM-vs2014_xp IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2014_xp.props %D%\LLVM-vs2014_xp\toolset.props IF NOT %ERRORLEVEL% == 0 GOTO FAILED copy %PLATFORM%\toolset-vs2014_xp.targets %D%\LLVM-vs2014_xp\toolset.targets IF NOT %ERRORLEVEL% == 0 GOTO FAILED set SUCCESS=1 GOTO TRY_V150 :DONE echo Done! goto END :FAILED echo MSVC integration install failed. pause goto END :END
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-nm/llvm-nm.cpp
//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like traditional Unix "nm", that is, it // prints out the names of symbols in a bitcode or object file, along with some // information about each symbol. // // This "nm" supports many of the features of GNU "nm", including its different // output formats. // //===----------------------------------------------------------------------===// #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Object/Archive.h" #include "llvm/Object/COFF.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/IRObjectFile.h" #include "llvm/Object/MachO.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/COFF.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cctype> #include <cerrno> #include <cstring> #include <system_error> #include <vector> using namespace llvm; using namespace object; namespace { enum OutputFormatTy { bsd, sysv, posix, darwin }; cl::opt<OutputFormatTy> OutputFormat( "format", cl::desc("Specify output format"), cl::values(clEnumVal(bsd, "BSD format"), clEnumVal(sysv, "System V format"), clEnumVal(posix, "POSIX.2 format"), clEnumVal(darwin, "Darwin -m format"), clEnumValEnd), cl::init(bsd)); cl::alias OutputFormat2("f", cl::desc("Alias for --format"), cl::aliasopt(OutputFormat)); cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore); cl::opt<bool> UndefinedOnly("undefined-only", cl::desc("Show only undefined symbols")); cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"), cl::aliasopt(UndefinedOnly)); cl::opt<bool> DynamicSyms("dynamic", cl::desc("Display the dynamic symbols instead " "of normal symbols.")); cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"), cl::aliasopt(DynamicSyms)); cl::opt<bool> DefinedOnly("defined-only", cl::desc("Show only defined symbols")); cl::alias DefinedOnly2("U", cl::desc("Alias for --defined-only"), cl::aliasopt(DefinedOnly)); cl::opt<bool> ExternalOnly("extern-only", cl::desc("Show only external symbols")); cl::alias ExternalOnly2("g", cl::desc("Alias for --extern-only"), cl::aliasopt(ExternalOnly)); cl::opt<bool> BSDFormat("B", cl::desc("Alias for --format=bsd")); cl::opt<bool> POSIXFormat("P", cl::desc("Alias for --format=posix")); cl::opt<bool> DarwinFormat("m", cl::desc("Alias for --format=darwin")); static cl::list<std::string> ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), cl::ZeroOrMore); bool ArchAll = false; cl::opt<bool> PrintFileName( "print-file-name", cl::desc("Precede each symbol with the object file it came from")); cl::alias PrintFileNameA("A", cl::desc("Alias for --print-file-name"), cl::aliasopt(PrintFileName)); cl::alias PrintFileNameo("o", cl::desc("Alias for --print-file-name"), cl::aliasopt(PrintFileName)); cl::opt<bool> DebugSyms("debug-syms", cl::desc("Show all symbols, even debugger only")); cl::alias DebugSymsa("a", cl::desc("Alias for --debug-syms"), cl::aliasopt(DebugSyms)); cl::opt<bool> NumericSort("numeric-sort", cl::desc("Sort symbols by address")); cl::alias NumericSortn("n", cl::desc("Alias for --numeric-sort"), cl::aliasopt(NumericSort)); cl::alias NumericSortv("v", cl::desc("Alias for --numeric-sort"), cl::aliasopt(NumericSort)); cl::opt<bool> NoSort("no-sort", cl::desc("Show symbols in order encountered")); cl::alias NoSortp("p", cl::desc("Alias for --no-sort"), cl::aliasopt(NoSort)); cl::opt<bool> ReverseSort("reverse-sort", cl::desc("Sort in reverse order")); cl::alias ReverseSortr("r", cl::desc("Alias for --reverse-sort"), cl::aliasopt(ReverseSort)); cl::opt<bool> PrintSize("print-size", cl::desc("Show symbol size instead of address")); cl::alias PrintSizeS("S", cl::desc("Alias for --print-size"), cl::aliasopt(PrintSize)); cl::opt<bool> SizeSort("size-sort", cl::desc("Sort symbols by size")); cl::opt<bool> WithoutAliases("without-aliases", cl::Hidden, cl::desc("Exclude aliases from output")); cl::opt<bool> ArchiveMap("print-armap", cl::desc("Print the archive map")); cl::alias ArchiveMaps("M", cl::desc("Alias for --print-armap"), cl::aliasopt(ArchiveMap)); cl::opt<bool> JustSymbolName("just-symbol-name", cl::desc("Print just the symbol's name")); cl::alias JustSymbolNames("j", cl::desc("Alias for --just-symbol-name"), cl::aliasopt(JustSymbolName)); // FIXME: This option takes exactly two strings and should be allowed anywhere // on the command line. Such that "llvm-nm -s __TEXT __text foo.o" would work. // But that does not as the CommandLine Library does not have a way to make // this work. For now the "-s __TEXT __text" has to be last on the command // line. cl::list<std::string> SegSect("s", cl::Positional, cl::ZeroOrMore, cl::desc("Dump only symbols from this segment " "and section name, Mach-O only")); cl::opt<bool> FormatMachOasHex("x", cl::desc("Print symbol entry in hex, " "Mach-O only")); cl::opt<bool> NoLLVMBitcode("no-llvm-bc", cl::desc("Disable LLVM bitcode reader")); bool PrintAddress = true; bool MultipleFiles = false; bool HadError = false; std::string ToolName; } static void error(Twine Message, Twine Path = Twine()) { HadError = true; errs() << ToolName << ": " << Path << ": " << Message << ".\n"; } static bool error(std::error_code EC, Twine Path = Twine()) { if (EC) { error(EC.message(), Path); return true; } return false; } namespace { struct NMSymbol { uint64_t Address; uint64_t Size; char TypeChar; StringRef Name; BasicSymbolRef Sym; }; } static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) { bool ADefined = !(A.Sym.getFlags() & SymbolRef::SF_Undefined); bool BDefined = !(B.Sym.getFlags() & SymbolRef::SF_Undefined); return std::make_tuple(ADefined, A.Address, A.Name, A.Size) < std::make_tuple(BDefined, B.Address, B.Name, B.Size); } static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) { return std::make_tuple(A.Size, A.Name, A.Address) < std::make_tuple(B.Size, B.Name, B.Address); } static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) { return std::make_tuple(A.Name, A.Size, A.Address) < std::make_tuple(B.Name, B.Size, B.Address); } static char isSymbolList64Bit(SymbolicFile &Obj) { if (isa<IRObjectFile>(Obj)) return false; if (isa<COFFObjectFile>(Obj)) return false; if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) return MachO->is64Bit(); return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8; } static StringRef CurrentFilename; typedef std::vector<NMSymbol> SymbolListT; static SymbolListT SymbolList; // darwinPrintSymbol() is used to print a symbol from a Mach-O file when the // the OutputFormat is darwin or we are printing Mach-O symbols in hex. For // the darwin format it produces the same output as darwin's nm(1) -m output // and when printing Mach-O symbols in hex it produces the same output as // darwin's nm(1) -x format. static void darwinPrintSymbol(MachOObjectFile *MachO, SymbolListT::iterator I, char *SymbolAddrStr, const char *printBlanks) { MachO::mach_header H; MachO::mach_header_64 H_64; uint32_t Filetype, Flags; MachO::nlist_64 STE_64; MachO::nlist STE; uint8_t NType; uint8_t NSect; uint16_t NDesc; uint32_t NStrx; uint64_t NValue; DataRefImpl SymDRI = I->Sym.getRawDataRefImpl(); if (MachO->is64Bit()) { H_64 = MachO->MachOObjectFile::getHeader64(); Filetype = H_64.filetype; Flags = H_64.flags; STE_64 = MachO->getSymbol64TableEntry(SymDRI); NType = STE_64.n_type; NSect = STE_64.n_sect; NDesc = STE_64.n_desc; NStrx = STE_64.n_strx; NValue = STE_64.n_value; } else { H = MachO->MachOObjectFile::getHeader(); Filetype = H.filetype; Flags = H.flags; STE = MachO->getSymbolTableEntry(SymDRI); NType = STE.n_type; NSect = STE.n_sect; NDesc = STE.n_desc; NStrx = STE.n_strx; NValue = STE.n_value; } // If we are printing Mach-O symbols in hex do that and return. if (FormatMachOasHex) { char Str[18] = ""; const char *printFormat; if (MachO->is64Bit()) printFormat = "%016" PRIx64; else printFormat = "%08" PRIx64; format(printFormat, NValue).print(Str, sizeof(Str)); outs() << Str << ' '; format("%02x", NType).print(Str, sizeof(Str)); outs() << Str << ' '; format("%02x", NSect).print(Str, sizeof(Str)); outs() << Str << ' '; format("%04x", NDesc).print(Str, sizeof(Str)); outs() << Str << ' '; format("%08x", NStrx).print(Str, sizeof(Str)); outs() << Str << ' '; outs() << I->Name << "\n"; return; } if (PrintAddress) { if ((NType & MachO::N_TYPE) == MachO::N_INDR) strcpy(SymbolAddrStr, printBlanks); outs() << SymbolAddrStr << ' '; } switch (NType & MachO::N_TYPE) { case MachO::N_UNDF: if (NValue != 0) { outs() << "(common) "; if (MachO::GET_COMM_ALIGN(NDesc) != 0) outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") "; } else { if ((NType & MachO::N_TYPE) == MachO::N_PBUD) outs() << "(prebound "; else outs() << "("; if ((NDesc & MachO::REFERENCE_TYPE) == MachO::REFERENCE_FLAG_UNDEFINED_LAZY) outs() << "undefined [lazy bound]) "; else if ((NDesc & MachO::REFERENCE_TYPE) == MachO::REFERENCE_FLAG_UNDEFINED_LAZY) outs() << "undefined [private lazy bound]) "; else if ((NDesc & MachO::REFERENCE_TYPE) == MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY) outs() << "undefined [private]) "; else outs() << "undefined) "; } break; case MachO::N_ABS: outs() << "(absolute) "; break; case MachO::N_INDR: outs() << "(indirect) "; break; case MachO::N_SECT: { section_iterator Sec = MachO->section_end(); MachO->getSymbolSection(I->Sym.getRawDataRefImpl(), Sec); DataRefImpl Ref = Sec->getRawDataRefImpl(); StringRef SectionName; MachO->getSectionName(Ref, SectionName); StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref); outs() << "(" << SegmentName << "," << SectionName << ") "; break; } default: outs() << "(?) "; break; } if (NType & MachO::N_EXT) { if (NDesc & MachO::REFERENCED_DYNAMICALLY) outs() << "[referenced dynamically] "; if (NType & MachO::N_PEXT) { if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) outs() << "weak private external "; else outs() << "private external "; } else { if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF || (NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) { if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) == (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) outs() << "weak external automatically hidden "; else outs() << "weak external "; } else outs() << "external "; } } else { if (NType & MachO::N_PEXT) outs() << "non-external (was a private external) "; else outs() << "non-external "; } if (Filetype == MachO::MH_OBJECT && (NDesc & MachO::N_NO_DEAD_STRIP) == MachO::N_NO_DEAD_STRIP) outs() << "[no dead strip] "; if (Filetype == MachO::MH_OBJECT && ((NType & MachO::N_TYPE) != MachO::N_UNDF) && (NDesc & MachO::N_SYMBOL_RESOLVER) == MachO::N_SYMBOL_RESOLVER) outs() << "[symbol resolver] "; if (Filetype == MachO::MH_OBJECT && ((NType & MachO::N_TYPE) != MachO::N_UNDF) && (NDesc & MachO::N_ALT_ENTRY) == MachO::N_ALT_ENTRY) outs() << "[alt entry] "; if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF) outs() << "[Thumb] "; if ((NType & MachO::N_TYPE) == MachO::N_INDR) { outs() << I->Name << " (for "; StringRef IndirectName; if (MachO->getIndirectName(I->Sym.getRawDataRefImpl(), IndirectName)) outs() << "?)"; else outs() << IndirectName << ")"; } else outs() << I->Name; if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL && (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) || (NType & MachO::N_TYPE) == MachO::N_PBUD)) { uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc); if (LibraryOrdinal != 0) { if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL) outs() << " (from executable)"; else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL) outs() << " (dynamically looked up)"; else { StringRef LibraryName; if (MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName)) outs() << " (from bad library ordinal " << LibraryOrdinal << ")"; else outs() << " (from " << LibraryName << ")"; } } } outs() << "\n"; } // Table that maps Darwin's Mach-O stab constants to strings to allow printing. struct DarwinStabName { uint8_t NType; const char *Name; }; static const struct DarwinStabName DarwinStabNames[] = { {MachO::N_GSYM, "GSYM"}, {MachO::N_FNAME, "FNAME"}, {MachO::N_FUN, "FUN"}, {MachO::N_STSYM, "STSYM"}, {MachO::N_LCSYM, "LCSYM"}, {MachO::N_BNSYM, "BNSYM"}, {MachO::N_PC, "PC"}, {MachO::N_AST, "AST"}, {MachO::N_OPT, "OPT"}, {MachO::N_RSYM, "RSYM"}, {MachO::N_SLINE, "SLINE"}, {MachO::N_ENSYM, "ENSYM"}, {MachO::N_SSYM, "SSYM"}, {MachO::N_SO, "SO"}, {MachO::N_OSO, "OSO"}, {MachO::N_LSYM, "LSYM"}, {MachO::N_BINCL, "BINCL"}, {MachO::N_SOL, "SOL"}, {MachO::N_PARAMS, "PARAM"}, {MachO::N_VERSION, "VERS"}, {MachO::N_OLEVEL, "OLEV"}, {MachO::N_PSYM, "PSYM"}, {MachO::N_EINCL, "EINCL"}, {MachO::N_ENTRY, "ENTRY"}, {MachO::N_LBRAC, "LBRAC"}, {MachO::N_EXCL, "EXCL"}, {MachO::N_RBRAC, "RBRAC"}, {MachO::N_BCOMM, "BCOMM"}, {MachO::N_ECOMM, "ECOMM"}, {MachO::N_ECOML, "ECOML"}, {MachO::N_LENG, "LENG"}, {0, 0}}; static const char *getDarwinStabString(uint8_t NType) { for (unsigned i = 0; DarwinStabNames[i].Name; i++) { if (DarwinStabNames[i].NType == NType) return DarwinStabNames[i].Name; } return 0; } // darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of // a stab n_type value in a Mach-O file. static void darwinPrintStab(MachOObjectFile *MachO, SymbolListT::iterator I) { MachO::nlist_64 STE_64; MachO::nlist STE; uint8_t NType; uint8_t NSect; uint16_t NDesc; DataRefImpl SymDRI = I->Sym.getRawDataRefImpl(); if (MachO->is64Bit()) { STE_64 = MachO->getSymbol64TableEntry(SymDRI); NType = STE_64.n_type; NSect = STE_64.n_sect; NDesc = STE_64.n_desc; } else { STE = MachO->getSymbolTableEntry(SymDRI); NType = STE.n_type; NSect = STE.n_sect; NDesc = STE.n_desc; } char Str[18] = ""; format("%02x", NSect).print(Str, sizeof(Str)); outs() << ' ' << Str << ' '; format("%04x", NDesc).print(Str, sizeof(Str)); outs() << Str << ' '; if (const char *stabString = getDarwinStabString(NType)) format("%5.5s", stabString).print(Str, sizeof(Str)); else format(" %02x", NType).print(Str, sizeof(Str)); outs() << Str; } static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName, std::string ArchiveName, std::string ArchitectureName) { if (!NoSort) { std::function<bool(const NMSymbol &, const NMSymbol &)> Cmp; if (NumericSort) Cmp = compareSymbolAddress; else if (SizeSort) Cmp = compareSymbolSize; else Cmp = compareSymbolName; if (ReverseSort) Cmp = [=](const NMSymbol &A, const NMSymbol &B) { return Cmp(B, A); }; std::sort(SymbolList.begin(), SymbolList.end(), Cmp); } if (!PrintFileName) { if (OutputFormat == posix && MultipleFiles && printName) { outs() << '\n' << CurrentFilename << ":\n"; } else if (OutputFormat == bsd && MultipleFiles && printName) { outs() << "\n" << CurrentFilename << ":\n"; } else if (OutputFormat == sysv) { outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n" << "Name Value Class Type" << " Size Line Section\n"; } } const char *printBlanks, *printFormat; if (isSymbolList64Bit(Obj)) { printBlanks = " "; printFormat = "%016" PRIx64; } else { printBlanks = " "; printFormat = "%08" PRIx64; } for (SymbolListT::iterator I = SymbolList.begin(), E = SymbolList.end(); I != E; ++I) { uint32_t SymFlags = I->Sym.getFlags(); bool Undefined = SymFlags & SymbolRef::SF_Undefined; if (!Undefined && UndefinedOnly) continue; if (Undefined && DefinedOnly) continue; if (SizeSort && !PrintAddress) continue; if (PrintFileName) { if (!ArchitectureName.empty()) outs() << "(for architecture " << ArchitectureName << "):"; if (!ArchiveName.empty()) outs() << ArchiveName << ":"; outs() << CurrentFilename << ": "; } if (JustSymbolName || (UndefinedOnly && isa<MachOObjectFile>(Obj))) { outs() << I->Name << "\n"; continue; } char SymbolAddrStr[18] = ""; char SymbolSizeStr[18] = ""; if (OutputFormat == sysv || I->TypeChar == 'U') strcpy(SymbolAddrStr, printBlanks); if (OutputFormat == sysv) strcpy(SymbolSizeStr, printBlanks); if (I->TypeChar != 'U') format(printFormat, I->Address) .print(SymbolAddrStr, sizeof(SymbolAddrStr)); format(printFormat, I->Size).print(SymbolSizeStr, sizeof(SymbolSizeStr)); // If OutputFormat is darwin or we are printing Mach-O symbols in hex and // we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's // nm(1) -m output or hex, else if OutputFormat is darwin or we are // printing Mach-O symbols in hex and not a Mach-O object fall back to // OutputFormat bsd (see below). MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); if ((OutputFormat == darwin || FormatMachOasHex) && MachO) { darwinPrintSymbol(MachO, I, SymbolAddrStr, printBlanks); } else if (OutputFormat == posix) { outs() << I->Name << " " << I->TypeChar << " " << SymbolAddrStr << SymbolSizeStr << "\n"; } else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) { if (PrintAddress) outs() << SymbolAddrStr << ' '; if (PrintSize) { outs() << SymbolSizeStr; outs() << ' '; } outs() << I->TypeChar; if (I->TypeChar == '-' && MachO) darwinPrintStab(MachO, I); outs() << " " << I->Name << "\n"; } else if (OutputFormat == sysv) { std::string PaddedName(I->Name); while (PaddedName.length() < 20) PaddedName += " "; outs() << PaddedName << "|" << SymbolAddrStr << "| " << I->TypeChar << " | |" << SymbolSizeStr << "| |\n"; } } SymbolList.clear(); } static char getSymbolNMTypeChar(ELFObjectFileBase &Obj, basic_symbol_iterator I) { // OK, this is ELF elf_symbol_iterator SymI(I); elf_section_iterator SecI = Obj.section_end(); if (error(SymI->getSection(SecI))) return '?'; if (SecI != Obj.section_end()) { switch (SecI->getType()) { case ELF::SHT_PROGBITS: case ELF::SHT_DYNAMIC: switch (SecI->getFlags()) { case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR): return 't'; case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE): case (ELF::SHF_ALLOC | ELF::SHF_WRITE): return 'd'; case ELF::SHF_ALLOC: case (ELF::SHF_ALLOC | ELF::SHF_MERGE): case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS): return 'r'; } break; case ELF::SHT_NOBITS: return 'b'; } } if (SymI->getELFType() == ELF::STT_SECTION) { ErrorOr<StringRef> Name = SymI->getName(); if (error(Name.getError())) return '?'; return StringSwitch<char>(*Name) .StartsWith(".debug", 'N') .StartsWith(".note", 'n') .Default('?'); } return 'n'; } static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) { COFFSymbolRef Symb = Obj.getCOFFSymbol(*I); // OK, this is COFF. symbol_iterator SymI(I); ErrorOr<StringRef> Name = SymI->getName(); if (error(Name.getError())) return '?'; char Ret = StringSwitch<char>(*Name) .StartsWith(".debug", 'N') .StartsWith(".sxdata", 'N') .Default('?'); if (Ret != '?') return Ret; uint32_t Characteristics = 0; if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) { section_iterator SecI = Obj.section_end(); if (error(SymI->getSection(SecI))) return '?'; const coff_section *Section = Obj.getCOFFSection(*SecI); Characteristics = Section->Characteristics; } switch (Symb.getSectionNumber()) { case COFF::IMAGE_SYM_DEBUG: return 'n'; default: // Check section type. if (Characteristics & COFF::IMAGE_SCN_CNT_CODE) return 't'; if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r'; if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) return 'b'; if (Characteristics & COFF::IMAGE_SCN_LNK_INFO) return 'i'; // Check for section symbol. if (Symb.isSectionDefinition()) return 's'; } return '?'; } static uint8_t getNType(MachOObjectFile &Obj, DataRefImpl Symb) { if (Obj.is64Bit()) { MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb); return STE.n_type; } MachO::nlist STE = Obj.getSymbolTableEntry(Symb); return STE.n_type; } static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) { DataRefImpl Symb = I->getRawDataRefImpl(); uint8_t NType = getNType(Obj, Symb); if (NType & MachO::N_STAB) return '-'; switch (NType & MachO::N_TYPE) { case MachO::N_ABS: return 's'; case MachO::N_INDR: return 'i'; case MachO::N_SECT: { section_iterator Sec = Obj.section_end(); Obj.getSymbolSection(Symb, Sec); DataRefImpl Ref = Sec->getRawDataRefImpl(); StringRef SectionName; Obj.getSectionName(Ref, SectionName); StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref); if (SegmentName == "__TEXT" && SectionName == "__text") return 't'; else if (SegmentName == "__DATA" && SectionName == "__data") return 'd'; else if (SegmentName == "__DATA" && SectionName == "__bss") return 'b'; else return 's'; } } return '?'; } static char getSymbolNMTypeChar(const GlobalValue &GV) { if (GV.getType()->getElementType()->isFunctionTy()) return 't'; // FIXME: should we print 'b'? At the IR level we cannot be sure if this // will be in bss or not, but we could approximate. return 'd'; } static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) { const GlobalValue *GV = Obj.getSymbolGV(I->getRawDataRefImpl()); if (!GV) return 't'; return getSymbolNMTypeChar(*GV); } static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) { auto *ELF = dyn_cast<ELFObjectFileBase>(&Obj); if (!ELF) return false; return elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT; } static char getNMTypeChar(SymbolicFile &Obj, basic_symbol_iterator I) { uint32_t Symflags = I->getFlags(); if ((Symflags & object::SymbolRef::SF_Weak) && !isa<MachOObjectFile>(Obj)) { char Ret = isObject(Obj, I) ? 'v' : 'w'; if (!(Symflags & object::SymbolRef::SF_Undefined)) Ret = toupper(Ret); return Ret; } if (Symflags & object::SymbolRef::SF_Undefined) return 'U'; if (Symflags & object::SymbolRef::SF_Common) return 'C'; char Ret = '?'; if (Symflags & object::SymbolRef::SF_Absolute) Ret = 'a'; else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) Ret = getSymbolNMTypeChar(*IR, I); else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj)) Ret = getSymbolNMTypeChar(*COFF, I); else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj)) Ret = getSymbolNMTypeChar(*MachO, I); else Ret = getSymbolNMTypeChar(cast<ELFObjectFileBase>(Obj), I); if (Symflags & object::SymbolRef::SF_Global) Ret = toupper(Ret); return Ret; } // getNsectForSegSect() is used to implement the Mach-O "-s segname sectname" // option to dump only those symbols from that section in a Mach-O file. // It is called once for each Mach-O file from dumpSymbolNamesFromObject() // to get the section number for that named section from the command line // arguments. It returns the section number for that section in the Mach-O // file or zero it is not present. static unsigned getNsectForSegSect(MachOObjectFile *Obj) { unsigned Nsect = 1; for (section_iterator I = Obj->section_begin(), E = Obj->section_end(); I != E; ++I) { DataRefImpl Ref = I->getRawDataRefImpl(); StringRef SectionName; Obj->getSectionName(Ref, SectionName); StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref); if (SegmentName == SegSect[0] && SectionName == SegSect[1]) return Nsect; Nsect++; } return 0; } // getNsectInMachO() is used to implement the Mach-O "-s segname sectname" // option to dump only those symbols from that section in a Mach-O file. // It is called once for each symbol in a Mach-O file from // dumpSymbolNamesFromObject() and returns the section number for that symbol // if it is in a section, else it returns 0. static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) { DataRefImpl Symb = Sym.getRawDataRefImpl(); if (Obj.is64Bit()) { MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb); if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT) return STE.n_sect; return 0; } MachO::nlist STE = Obj.getSymbolTableEntry(Symb); if ((STE.n_type & MachO::N_TYPE) == MachO::N_SECT) return STE.n_sect; return 0; } static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName, std::string ArchiveName = std::string(), std::string ArchitectureName = std::string()) { auto Symbols = Obj.symbols(); if (DynamicSyms) { const auto *E = dyn_cast<ELFObjectFileBase>(&Obj); if (!E) { error("File format has no dynamic symbol table", Obj.getFileName()); return; } auto DynSymbols = E->getDynamicSymbolIterators(); Symbols = make_range<basic_symbol_iterator>(DynSymbols.begin(), DynSymbols.end()); } std::string NameBuffer; raw_string_ostream OS(NameBuffer); // If a "-s segname sectname" option was specified and this is a Mach-O // file get the section number for that section in this object file. unsigned int Nsect = 0; MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj); if (SegSect.size() != 0 && MachO) { Nsect = getNsectForSegSect(MachO); // If this section is not in the object file no symbols are printed. if (Nsect == 0) return; } for (BasicSymbolRef Sym : Symbols) { uint32_t SymFlags = Sym.getFlags(); if (!DebugSyms && (SymFlags & SymbolRef::SF_FormatSpecific)) continue; if (WithoutAliases) { if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj)) { const GlobalValue *GV = IR->getSymbolGV(Sym.getRawDataRefImpl()); if (GV && isa<GlobalAlias>(GV)) continue; } } // If a "-s segname sectname" option was specified and this is a Mach-O // file and this section appears in this file, Nsect will be non-zero then // see if this symbol is a symbol from that section and if not skip it. if (Nsect && Nsect != getNsectInMachO(*MachO, Sym)) continue; NMSymbol S; S.Size = 0; S.Address = 0; if (PrintSize) { if (isa<ELFObjectFileBase>(&Obj)) S.Size = ELFSymbolRef(Sym).getSize(); } if (PrintAddress && isa<ObjectFile>(Obj)) { SymbolRef SymRef(Sym); ErrorOr<uint64_t> AddressOrErr = SymRef.getAddress(); if (error(AddressOrErr.getError())) break; S.Address = *AddressOrErr; } S.TypeChar = getNMTypeChar(Obj, Sym); if (error(Sym.printName(OS))) break; OS << '\0'; S.Sym = Sym; SymbolList.push_back(S); } OS.flush(); const char *P = NameBuffer.c_str(); for (unsigned I = 0; I < SymbolList.size(); ++I) { SymbolList[I].Name = P; P += strlen(P) + 1; } CurrentFilename = Obj.getFileName(); sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName); } // checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file // and if it is and there is a list of architecture flags is specified then // check to make sure this Mach-O file is one of those architectures or all // architectures was specificed. If not then an error is generated and this // routine returns false. Else it returns true. static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) { MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O); if (!MachO || ArchAll || ArchFlags.size() == 0) return true; MachO::mach_header H; MachO::mach_header_64 H_64; Triple T; if (MachO->is64Bit()) { H_64 = MachO->MachOObjectFile::getHeader64(); T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype); } else { H = MachO->MachOObjectFile::getHeader(); T = MachOObjectFile::getArch(H.cputype, H.cpusubtype); } if (std::none_of( ArchFlags.begin(), ArchFlags.end(), [&](const std::string &Name) { return Name == T.getArchName(); })) { error("No architecture specified", Filename); return false; } return true; } static void dumpSymbolNamesFromFile(std::string &Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename); if (error(BufferOrErr.getError(), Filename)) return; LLVMContext &Context = getGlobalContext(); ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary( BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context); if (error(BinaryOrErr.getError(), Filename)) return; Binary &Bin = *BinaryOrErr.get(); if (Archive *A = dyn_cast<Archive>(&Bin)) { if (ArchiveMap) { Archive::symbol_iterator I = A->symbol_begin(); Archive::symbol_iterator E = A->symbol_end(); if (I != E) { outs() << "Archive map\n"; for (; I != E; ++I) { ErrorOr<Archive::child_iterator> C = I->getMember(); if (error(C.getError())) return; ErrorOr<StringRef> FileNameOrErr = C.get()->getName(); if (error(FileNameOrErr.getError())) return; StringRef SymName = I->getName(); outs() << SymName << " in " << FileNameOrErr.get() << "\n"; } outs() << "\n"; } } for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E; ++I) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary(&Context); if (ChildOrErr.getError()) continue; if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { if (!checkMachOAndArchFlags(O, Filename)) return; if (!PrintFileName) { outs() << "\n"; if (isa<MachOObjectFile>(O)) { outs() << Filename << "(" << O->getFileName() << ")"; } else outs() << O->getFileName(); outs() << ":\n"; } dumpSymbolNamesFromObject(*O, false, Filename); } } return; } if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { // If we have a list of architecture flags specified dump only those. if (!ArchAll && ArchFlags.size() != 0) { // Look for a slice in the universal binary that matches each ArchFlag. bool ArchFound; for (unsigned i = 0; i < ArchFlags.size(); ++i) { ArchFound = false; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (ArchFlags[i] == I->getArchTypeName()) { ArchFound = true; ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchiveName; std::string ArchitectureName; ArchiveName.clear(); ArchitectureName.clear(); if (ObjOrErr) { ObjectFile &Obj = *ObjOrErr.get(); if (ArchFlags.size() > 1) { if (PrintFileName) ArchitectureName = I->getArchTypeName(); else outs() << "\n" << Obj.getFileName() << " (for architecture " << I->getArchTypeName() << ")" << ":\n"; } dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(&Context); if (ChildOrErr.getError()) continue; if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { if (PrintFileName) { ArchiveName = A->getFileName(); if (ArchFlags.size() > 1) ArchitectureName = I->getArchTypeName(); } else { outs() << "\n" << A->getFileName(); outs() << "(" << O->getFileName() << ")"; if (ArchFlags.size() > 1) { outs() << " (for architecture " << I->getArchTypeName() << ")"; } outs() << ":\n"; } dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName); } } } } } if (!ArchFound) { error(ArchFlags[i], "file: " + Filename + " does not contain architecture"); return; } } return; } // No architecture flags were specified so if this contains a slice that // matches the host architecture dump only that. if (!ArchAll) { StringRef HostArchName = MachOObjectFile::getHostArch().getArchName(); for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { if (HostArchName == I->getArchTypeName()) { ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchiveName; ArchiveName.clear(); if (ObjOrErr) { ObjectFile &Obj = *ObjOrErr.get(); dumpSymbolNamesFromObject(Obj, false); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(&Context); if (ChildOrErr.getError()) continue; if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { if (PrintFileName) ArchiveName = A->getFileName(); else outs() << "\n" << A->getFileName() << "(" << O->getFileName() << ")" << ":\n"; dumpSymbolNamesFromObject(*O, false, ArchiveName); } } } return; } } } // Either all architectures have been specified or none have been specified // and this does not contain the host architecture so dump all the slices. bool moreThanOneArch = UB->getNumberOfObjects() > 1; for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), E = UB->end_objects(); I != E; ++I) { ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); std::string ArchiveName; std::string ArchitectureName; ArchiveName.clear(); ArchitectureName.clear(); if (ObjOrErr) { ObjectFile &Obj = *ObjOrErr.get(); if (PrintFileName) { if (isa<MachOObjectFile>(Obj) && moreThanOneArch) ArchitectureName = I->getArchTypeName(); } else { if (moreThanOneArch) outs() << "\n"; outs() << Obj.getFileName(); if (isa<MachOObjectFile>(Obj) && moreThanOneArch) outs() << " (for architecture " << I->getArchTypeName() << ")"; outs() << ":\n"; } dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName); } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end(); AI != AE; ++AI) { ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary(&Context); if (ChildOrErr.getError()) continue; if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) { if (PrintFileName) { ArchiveName = A->getFileName(); if (isa<MachOObjectFile>(O) && moreThanOneArch) ArchitectureName = I->getArchTypeName(); } else { outs() << "\n" << A->getFileName(); if (isa<MachOObjectFile>(O)) { outs() << "(" << O->getFileName() << ")"; if (moreThanOneArch) outs() << " (for architecture " << I->getArchTypeName() << ")"; } else outs() << ":" << O->getFileName(); outs() << ":\n"; } dumpSymbolNamesFromObject(*O, false, ArchiveName, ArchitectureName); } } } } return; } if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) { if (!checkMachOAndArchFlags(O, Filename)) return; dumpSymbolNamesFromObject(*O, true); return; } error("unrecognizable file type", Filename); return; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n"); // llvm-nm only reads binary files. if (error(sys::ChangeStdinToBinary())) return 1; llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); ToolName = argv[0]; if (BSDFormat) OutputFormat = bsd; if (POSIXFormat) OutputFormat = posix; if (DarwinFormat) OutputFormat = darwin; // The relative order of these is important. If you pass --size-sort it should // only print out the size. However, if you pass -S --size-sort, it should // print out both the size and address. if (SizeSort && !PrintSize) PrintAddress = false; if (OutputFormat == sysv || SizeSort) PrintSize = true; switch (InputFilenames.size()) { case 0: InputFilenames.push_back("a.out"); case 1: break; default: MultipleFiles = true; } for (unsigned i = 0; i < ArchFlags.size(); ++i) { if (ArchFlags[i] == "all") { ArchAll = true; } else { if (!MachOObjectFile::isValidArch(ArchFlags[i])) error("Unknown architecture named '" + ArchFlags[i] + "'", "for the -arch option"); } } if (SegSect.size() != 0 && SegSect.size() != 2) error("bad number of arguments (must be two arguments)", "for the -s option"); std::for_each(InputFilenames.begin(), InputFilenames.end(), dumpSymbolNamesFromFile); if (HadError) return 1; return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-nm/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} Core Object Support ) add_llvm_tool(llvm-nm llvm-nm.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-nm/LLVMBuild.txt
;===- ./tools/llvm-nm/LLVMBuild.txt ----------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-nm parent = Tools required_libraries = BitReader Object
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-mc/Disassembler.cpp
//===- Disassembler.cpp - Disassembler for hex strings --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements the disassembler of strings of bytes written in // hexadecimal, from standard input or from a file. // //===----------------------------------------------------------------------===// #include "Disassembler.h" #include "llvm/ADT/Triple.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; typedef std::pair<std::vector<unsigned char>, std::vector<const char *>> ByteArrayTy; static bool PrintInsts(const MCDisassembler &DisAsm, const ByteArrayTy &Bytes, SourceMgr &SM, raw_ostream &Out, MCStreamer &Streamer, bool InAtomicBlock, const MCSubtargetInfo &STI) { ArrayRef<uint8_t> Data(Bytes.first.data(), Bytes.first.size()); // Disassemble it to strings. uint64_t Size; uint64_t Index; for (Index = 0; Index < Bytes.first.size(); Index += Size) { MCInst Inst; MCDisassembler::DecodeStatus S; S = DisAsm.getInstruction(Inst, Size, Data.slice(Index), Index, /*REMOVE*/ nulls(), nulls()); switch (S) { case MCDisassembler::Fail: SM.PrintMessage(SMLoc::getFromPointer(Bytes.second[Index]), SourceMgr::DK_Warning, "invalid instruction encoding"); // Don't try to resynchronise the stream in a block if (InAtomicBlock) return true; if (Size == 0) Size = 1; // skip illegible bytes break; case MCDisassembler::SoftFail: SM.PrintMessage(SMLoc::getFromPointer(Bytes.second[Index]), SourceMgr::DK_Warning, "potentially undefined instruction encoding"); // Fall through case MCDisassembler::Success: Streamer.EmitInstruction(Inst, STI); break; } } return false; } static bool SkipToToken(StringRef &Str) { for (;;) { if (Str.empty()) return false; // Strip horizontal whitespace and commas. if (size_t Pos = Str.find_first_not_of(" \t\r\n,")) { Str = Str.substr(Pos); continue; } // If this is the start of a comment, remove the rest of the line. if (Str[0] == '#') { Str = Str.substr(Str.find_first_of('\n')); continue; } return true; } } static bool ByteArrayFromString(ByteArrayTy &ByteArray, StringRef &Str, SourceMgr &SM) { while (SkipToToken(Str)) { // Handled by higher level if (Str[0] == '[' || Str[0] == ']') return false; // Get the current token. size_t Next = Str.find_first_of(" \t\n\r,#[]"); StringRef Value = Str.substr(0, Next); // Convert to a byte and add to the byte vector. unsigned ByteVal; if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) { // If we have an error, print it and skip to the end of line. SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error, "invalid input token"); Str = Str.substr(Str.find('\n')); ByteArray.first.clear(); ByteArray.second.clear(); continue; } ByteArray.first.push_back(ByteVal); ByteArray.second.push_back(Value.data()); Str = Str.substr(Next); } return false; } int Disassembler::disassemble(const Target &T, const std::string &Triple, MCSubtargetInfo &STI, MCStreamer &Streamer, MemoryBuffer &Buffer, SourceMgr &SM, raw_ostream &Out) { std::unique_ptr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple)); if (!MRI) { errs() << "error: no register info for target " << Triple << "\n"; return -1; } std::unique_ptr<const MCAsmInfo> MAI(T.createMCAsmInfo(*MRI, Triple)); if (!MAI) { errs() << "error: no assembly info for target " << Triple << "\n"; return -1; } // Set up the MCContext for creating symbols and MCExpr's. MCContext Ctx(MAI.get(), MRI.get(), nullptr); std::unique_ptr<const MCDisassembler> DisAsm( T.createMCDisassembler(STI, Ctx)); if (!DisAsm) { errs() << "error: no disassembler for target " << Triple << "\n"; return -1; } // Set up initial section manually here Streamer.InitSections(false); bool ErrorOccurred = false; // Convert the input to a vector for disassembly. ByteArrayTy ByteArray; StringRef Str = Buffer.getBuffer(); bool InAtomicBlock = false; while (SkipToToken(Str)) { ByteArray.first.clear(); ByteArray.second.clear(); if (Str[0] == '[') { if (InAtomicBlock) { SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error, "nested atomic blocks make no sense"); ErrorOccurred = true; } InAtomicBlock = true; Str = Str.drop_front(); continue; } else if (Str[0] == ']') { if (!InAtomicBlock) { SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error, "attempt to close atomic block without opening"); ErrorOccurred = true; } InAtomicBlock = false; Str = Str.drop_front(); continue; } // It's a real token, get the bytes and emit them ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM); if (!ByteArray.first.empty()) ErrorOccurred |= PrintInsts(*DisAsm, ByteArray, SM, Out, Streamer, InAtomicBlock, STI); } if (InAtomicBlock) { SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error, "unclosed atomic block"); ErrorOccurred = true; } return ErrorOccurred; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-mc/CMakeLists.txt
set(LLVM_LINK_COMPONENTS AllTargetsAsmPrinters AllTargetsAsmParsers AllTargetsDescs AllTargetsDisassemblers AllTargetsInfos MC MCParser Support ) add_llvm_tool(llvm-mc llvm-mc.cpp Disassembler.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-mc/LLVMBuild.txt
;===- ./tools/llvm-mc/LLVMBuild.txt ----------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-mc parent = Tools required_libraries = MC MCDisassembler MCParser Support all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-mc/Disassembler.h
//===- Disassembler.h - Text File Disassembler ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements the disassembler of strings of bytes written in // hexadecimal, from standard input or from a file. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_LLVM_MC_DISASSEMBLER_H #define LLVM_TOOLS_LLVM_MC_DISASSEMBLER_H #include <string> namespace llvm { class MemoryBuffer; class Target; class raw_ostream; class SourceMgr; class MCSubtargetInfo; class MCStreamer; class Disassembler { public: static int disassemble(const Target &T, const std::string &Triple, MCSubtargetInfo &STI, MCStreamer &Streamer, MemoryBuffer &Buffer, SourceMgr &SM, raw_ostream &Out); }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-mc/llvm-mc.cpp
//===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility is a simple driver that allows command line hacking on machine // code. // //===----------------------------------------------------------------------===// #include "Disassembler.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/AsmLexer.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCTargetAsmParser.h" #include "llvm/MC/MCTargetOptionsCommandFlags.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compression.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" using namespace llvm; static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> ShowEncoding("show-encoding", cl::desc("Show instruction encodings")); static cl::opt<bool> CompressDebugSections("compress-debug-sections", cl::desc("Compress DWARF debug sections")); static cl::opt<bool> ShowInst("show-inst", cl::desc("Show internal instruction representation")); static cl::opt<bool> ShowInstOperands("show-inst-operands", cl::desc("Show instructions operands as parsed")); static cl::opt<unsigned> OutputAsmVariant("output-asm-variant", cl::desc("Syntax variant to use for output printing")); static cl::opt<bool> PrintImmHex("print-imm-hex", cl::init(false), cl::desc("Prefer hex format for immediate values")); static cl::list<std::string> DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant")); enum OutputFileType { OFT_Null, OFT_AssemblyFile, OFT_ObjectFile }; static cl::opt<OutputFileType> FileType("filetype", cl::init(OFT_AssemblyFile), cl::desc("Choose an output file type:"), cl::values( clEnumValN(OFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"), clEnumValN(OFT_Null, "null", "Don't emit anything (for timing purposes)"), clEnumValN(OFT_ObjectFile, "obj", "Emit a native object ('.o') file"), clEnumValEnd)); static cl::list<std::string> IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix); static cl::opt<std::string> ArchName("arch", cl::desc("Target arch to assemble for, " "see -version for available targets")); static cl::opt<std::string> TripleName("triple", cl::desc("Target triple to assemble for, " "see -version for available targets")); static cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); static cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); static cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); static cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::Default), cl::values(clEnumValN(CodeModel::Default, "default", "Target default code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); static cl::opt<bool> NoInitialTextSection("n", cl::desc("Don't assume assembly file starts " "in the text section")); static cl::opt<bool> GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly " "source files")); static cl::opt<std::string> DebugCompilationDir("fdebug-compilation-dir", cl::desc("Specifies the debug info's compilation dir")); static cl::opt<std::string> MainFileName("main-file-name", cl::desc("Specifies the name we should consider the input file")); static cl::opt<bool> SaveTempLabels("save-temp-labels", cl::desc("Don't discard temporary labels")); static cl::opt<bool> NoExecStack("no-exec-stack", cl::desc("File doesn't need an exec stack")); enum ActionType { AC_AsLex, AC_Assemble, AC_Disassemble, AC_MDisassemble, }; static cl::opt<ActionType> Action(cl::desc("Action to perform:"), cl::init(AC_Assemble), cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"), clEnumValN(AC_Assemble, "assemble", "Assemble a .s file (default)"), clEnumValN(AC_Disassemble, "disassemble", "Disassemble strings of hex bytes"), clEnumValN(AC_MDisassemble, "mdis", "Marked up disassembly of strings of hex bytes"), clEnumValEnd)); static const Target *GetTarget(const char *ProgName) { // Figure out the target triple. if (TripleName.empty()) TripleName = sys::getDefaultTargetTriple(); Triple TheTriple(Triple::normalize(TripleName)); // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, Error); if (!TheTarget) { errs() << ProgName << ": " << Error; return nullptr; } // Update the triple name and return the found target. TripleName = TheTriple.getTriple(); return TheTarget; } static std::unique_ptr<tool_output_file> GetOutputStream() { if (OutputFilename == "") OutputFilename = "-"; std::error_code EC; auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC, sys::fs::F_None); if (EC) { errs() << EC.message() << '\n'; return nullptr; } return Out; } static std::string DwarfDebugFlags; static void setDwarfDebugFlags(int argc, char **argv) { if (!getenv("RC_DEBUG_OPTIONS")) return; for (int i = 0; i < argc; i++) { DwarfDebugFlags += argv[i]; if (i + 1 < argc) DwarfDebugFlags += " "; } } static std::string DwarfDebugProducer; static void setDwarfDebugProducer(void) { if(!getenv("DEBUG_PRODUCER")) return; DwarfDebugProducer += getenv("DEBUG_PRODUCER"); } static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, raw_ostream &OS) { AsmLexer Lexer(MAI); Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer()); bool Error = false; while (Lexer.Lex().isNot(AsmToken::Eof)) { AsmToken Tok = Lexer.getTok(); switch (Tok.getKind()) { default: SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning, "unknown token"); Error = true; break; case AsmToken::Error: Error = true; // error already printed. break; case AsmToken::Identifier: OS << "identifier: " << Lexer.getTok().getString(); break; case AsmToken::Integer: OS << "int: " << Lexer.getTok().getString(); break; case AsmToken::Real: OS << "real: " << Lexer.getTok().getString(); break; case AsmToken::String: OS << "string: " << Lexer.getTok().getString(); break; case AsmToken::Amp: OS << "Amp"; break; case AsmToken::AmpAmp: OS << "AmpAmp"; break; case AsmToken::At: OS << "At"; break; case AsmToken::Caret: OS << "Caret"; break; case AsmToken::Colon: OS << "Colon"; break; case AsmToken::Comma: OS << "Comma"; break; case AsmToken::Dollar: OS << "Dollar"; break; case AsmToken::Dot: OS << "Dot"; break; case AsmToken::EndOfStatement: OS << "EndOfStatement"; break; case AsmToken::Eof: OS << "Eof"; break; case AsmToken::Equal: OS << "Equal"; break; case AsmToken::EqualEqual: OS << "EqualEqual"; break; case AsmToken::Exclaim: OS << "Exclaim"; break; case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break; case AsmToken::Greater: OS << "Greater"; break; case AsmToken::GreaterEqual: OS << "GreaterEqual"; break; case AsmToken::GreaterGreater: OS << "GreaterGreater"; break; case AsmToken::Hash: OS << "Hash"; break; case AsmToken::LBrac: OS << "LBrac"; break; case AsmToken::LCurly: OS << "LCurly"; break; case AsmToken::LParen: OS << "LParen"; break; case AsmToken::Less: OS << "Less"; break; case AsmToken::LessEqual: OS << "LessEqual"; break; case AsmToken::LessGreater: OS << "LessGreater"; break; case AsmToken::LessLess: OS << "LessLess"; break; case AsmToken::Minus: OS << "Minus"; break; case AsmToken::Percent: OS << "Percent"; break; case AsmToken::Pipe: OS << "Pipe"; break; case AsmToken::PipePipe: OS << "PipePipe"; break; case AsmToken::Plus: OS << "Plus"; break; case AsmToken::RBrac: OS << "RBrac"; break; case AsmToken::RCurly: OS << "RCurly"; break; case AsmToken::RParen: OS << "RParen"; break; case AsmToken::Slash: OS << "Slash"; break; case AsmToken::Star: OS << "Star"; break; case AsmToken::Tilde: OS << "Tilde"; break; } // Print the token string. OS << " (\""; OS.write_escaped(Tok.getString()); OS << "\")\n"; } return Error; } static int fillCommandLineSymbols(MCAsmParser &Parser){ for(auto &I: DefineSymbol){ auto Pair = StringRef(I).split('='); if(Pair.second.empty()){ errs() << "error: defsym must be of the form: sym=value: " << I; return 1; } int64_t Value; if(Pair.second.getAsInteger(0, Value)){ errs() << "error: Value is not an integer: " << Pair.second; return 1; } auto &Context = Parser.getContext(); auto Symbol = Context.getOrCreateSymbol(Pair.first); Parser.getStreamer().EmitAssignment(Symbol, MCConstantExpr::create(Value, Context)); } return 0; } static int AssembleInput(const char *ProgName, const Target *TheTarget, SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII, MCTargetOptions &MCOptions) { std::unique_ptr<MCAsmParser> Parser( createMCAsmParser(SrcMgr, Ctx, Str, MAI)); std::unique_ptr<MCTargetAsmParser> TAP( TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions)); if (!TAP) { errs() << ProgName << ": error: this target does not support assembly parsing.\n"; return 1; } int SymbolResult = fillCommandLineSymbols(*Parser); if(SymbolResult) return SymbolResult; Parser->setShowParsedOperands(ShowInstOperands); Parser->setTargetParser(*TAP); int Res = Parser->Run(NoInitialTextSection); return Res; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets and assembly printers/parsers. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllDisassemblers(); // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags(); TripleName = Triple::normalize(TripleName); setDwarfDebugFlags(argc, argv); setDwarfDebugProducer(); const char *ProgName = argv[0]; const Target *TheTarget = GetTarget(ProgName); if (!TheTarget) return 1; // Now that GetTarget() has (potentially) replaced TripleName, it's safe to // construct the Triple object. Triple TheTriple(TripleName); ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr = MemoryBuffer::getFileOrSTDIN(InputFilename); if (std::error_code EC = BufferPtr.getError()) { errs() << ProgName << ": " << EC.message() << '\n'; return 1; } MemoryBuffer *Buffer = BufferPtr->get(); SourceMgr SrcMgr; // Tell SrcMgr about this buffer, which is what the parser will pick up. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc()); // Record the location of the include directories so that the lexer can find // it later. SrcMgr.setIncludeDirs(IncludeDirs); std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); assert(MRI && "Unable to create target register info!"); std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName)); assert(MAI && "Unable to create target asm info!"); if (CompressDebugSections) { if (!zlib::isAvailable()) { errs() << ProgName << ": build tools with zlib to enable -compress-debug-sections"; return 1; } MAI->setCompressDebugSections(true); } // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and // MCObjectFileInfo needs a MCContext reference in order to initialize itself. MCObjectFileInfo MOFI; MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr); MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx); if (SaveTempLabels) Ctx.setAllowTemporaryLabels(false); Ctx.setGenDwarfForAssembly(GenDwarfForAssembly); // Default to 4 for dwarf version. unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4; if (DwarfVersion < 2 || DwarfVersion > 4) { errs() << ProgName << ": Dwarf version " << DwarfVersion << " is not supported." << '\n'; return 1; } Ctx.setDwarfVersion(DwarfVersion); if (!DwarfDebugFlags.empty()) Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags)); if (!DwarfDebugProducer.empty()) Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer)); if (!DebugCompilationDir.empty()) Ctx.setCompilationDir(DebugCompilationDir); if (!MainFileName.empty()) Ctx.setMainFileName(MainFileName); // Package up features to be passed to target/subtarget std::string FeaturesStr; if (MAttrs.size()) { SubtargetFeatures Features; for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); FeaturesStr = Features.getString(); } std::unique_ptr<tool_output_file> Out = GetOutputStream(); if (!Out) return 1; std::unique_ptr<buffer_ostream> BOS; raw_pwrite_stream *OS = &Out->os(); std::unique_ptr<MCStreamer> Str; std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); std::unique_ptr<MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); MCInstPrinter *IP = nullptr; if (FileType == OFT_AssemblyFile) { IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI); // Set the display preference for hex vs. decimal immediates. IP->setPrintImmHex(PrintImmHex); // Set up the AsmStreamer. MCCodeEmitter *CE = nullptr; MCAsmBackend *MAB = nullptr; if (ShowEncoding) { CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); } auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS); Str.reset(TheTarget->createAsmStreamer( Ctx, std::move(FOut), /*asmverbose*/ true, /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst)); } else if (FileType == OFT_Null) { Str.reset(TheTarget->createNullStreamer(Ctx)); } else { assert(FileType == OFT_ObjectFile && "Invalid file type!"); // Don't waste memory on names of temp labels. Ctx.setUseNamesOnTempLabels(false); if (!Out->os().supportsSeeking()) { BOS = make_unique<buffer_ostream>(Out->os()); OS = BOS.get(); } MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); Str.reset(TheTarget->createMCObjectStreamer(TheTriple, Ctx, *MAB, *OS, CE, *STI, RelaxAll, /*DWARFMustBeAtTheEnd*/ false)); if (NoExecStack) Str->InitSections(true); } int Res = 1; bool disassemble = false; switch (Action) { case AC_AsLex: Res = AsLexInput(SrcMgr, *MAI, Out->os()); break; case AC_Assemble: Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII, MCOptions); break; case AC_MDisassemble: assert(IP && "Expected assembly output"); IP->setUseMarkup(1); disassemble = true; break; case AC_Disassemble: disassemble = true; break; } if (disassemble) Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer, SrcMgr, Out->os()); // Keep output if no errors. if (Res == 0) Out->keep(); return Res; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/dsymutil.cpp
//===-- dsymutil.cpp - Debug info dumping utility for llvm ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that aims to be a dropin replacement for // Darwin's dsymutil. // //===----------------------------------------------------------------------===// #include "DebugMap.h" #include "dsymutil.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Options.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/TargetSelect.h" #include <string> using namespace llvm::dsymutil; namespace { using namespace llvm::cl; static opt<std::string> InputFile(Positional, desc("<input file>"), init("a.out")); static opt<std::string> OutputFileOpt("o", desc("Specify the output file. default: <input file>.dwarf"), value_desc("filename")); static opt<std::string> OsoPrependPath( "oso-prepend-path", desc("Specify a directory to prepend to the paths of object files."), value_desc("path")); static opt<bool> Verbose("v", desc("Verbosity level"), init(false)); static opt<bool> NoOutput("no-output", desc("Do the link in memory, but do not emit the result file."), init(false)); static opt<bool> DumpDebugMap( "dump-debug-map", desc("Parse and dump the debug map to standard output. Not DWARF link " "will take place."), init(false)); static opt<bool> InputIsYAMLDebugMap( "y", desc("Treat the input file is a YAML debug map rather than a binary."), init(false)); } int main(int argc, char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram StackPrinter(argc, argv); llvm::llvm_shutdown_obj Shutdown; LinkOptions Options; llvm::cl::ParseCommandLineOptions(argc, argv, "llvm dsymutil\n"); auto DebugMapPtrOrErr = parseDebugMap(InputFile, OsoPrependPath, Verbose, InputIsYAMLDebugMap); Options.Verbose = Verbose; Options.NoOutput = NoOutput; llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllTargets(); llvm::InitializeAllAsmPrinters(); if (auto EC = DebugMapPtrOrErr.getError()) { llvm::errs() << "error: cannot parse the debug map for \"" << InputFile << "\": " << EC.message() << '\n'; return 1; } if (Verbose || DumpDebugMap) (*DebugMapPtrOrErr)->print(llvm::outs()); if (DumpDebugMap) return 0; std::string OutputFile; if (OutputFileOpt.empty()) { if (InputFile == "-") OutputFile = "a.out.dwarf"; else OutputFile = InputFile + ".dwarf"; } else { OutputFile = OutputFileOpt; } return !linkDwarf(OutputFile, **DebugMapPtrOrErr, Options); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/dsymutil.h
//===- tools/dsymutil/dsymutil.h - dsymutil high-level functionality ------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// This file contains the class declaration for the code that parses STABS /// debug maps that are embedded in the binaries symbol tables. /// //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H #define LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H #include "DebugMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ErrorOr.h" #include <memory> namespace llvm { namespace dsymutil { struct LinkOptions { bool Verbose; ///< Verbosity bool NoOutput; ///< Skip emitting output LinkOptions() : Verbose(false), NoOutput(false) {} }; /// \brief Extract the DebugMap from the given file. /// The file has to be a MachO object file. llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose, bool InputIsYAML); /// \brief Link the Dwarf debuginfo as directed by the passed DebugMap /// \p DM into a DwarfFile named \p OutputFilename. /// \returns false if the link failed. bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, const LinkOptions &Options); } } #endif // LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/DebugMap.h
//===- tools/dsymutil/DebugMap.h - Generic debug map representation -------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// This file contains the class declaration of the DebugMap /// entity. A DebugMap lists all the object files linked together to /// produce an executable along with the linked address of all the /// atoms used in these object files. /// The DebugMap is an input to the DwarfLinker class that will /// extract the Dwarf debug information from the referenced object /// files and link their usefull debug info together. /// //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H #define LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/Format.h" #include "llvm/Support/Path.h" #include "llvm/Support/YAMLTraits.h" #include <vector> namespace llvm { class raw_ostream; namespace dsymutil { class DebugMapObject; /// \brief The DebugMap object stores the list of object files to /// query for debug information along with the mapping between the /// symbols' addresses in the object file to their linked address in /// the linked binary. /// /// A DebugMap producer could look like this: /// DebugMap *DM = new DebugMap(); /// for (const auto &Obj: LinkedObjects) { /// DebugMapObject &DMO = DM->addDebugMapObject(Obj.getPath()); /// for (const auto &Sym: Obj.getLinkedSymbols()) /// DMO.addSymbol(Sym.getName(), Sym.getObjectFileAddress(), /// Sym.getBinaryAddress()); /// } /// /// A DebugMap consumer can then use the map to link the debug /// information. For example something along the lines of: /// for (const auto &DMO: DM->objects()) { /// auto Obj = createBinary(DMO.getObjectFilename()); /// for (auto &DIE: Obj.getDwarfDIEs()) { /// if (SymbolMapping *Sym = DMO.lookup(DIE.getName())) /// DIE.relocate(Sym->ObjectAddress, Sym->BinaryAddress); /// else /// DIE.discardSubtree(); /// } /// } class DebugMap { Triple BinaryTriple; typedef std::vector<std::unique_ptr<DebugMapObject>> ObjectContainer; ObjectContainer Objects; /// For YAML IO support. ///@{ friend yaml::MappingTraits<std::unique_ptr<DebugMap>>; friend yaml::MappingTraits<DebugMap>; DebugMap() = default; ///@} public: DebugMap(const Triple &BinaryTriple) : BinaryTriple(BinaryTriple) {} typedef ObjectContainer::const_iterator const_iterator; iterator_range<const_iterator> objects() const { return make_range(begin(), end()); } const_iterator begin() const { return Objects.begin(); } const_iterator end() const { return Objects.end(); } /// This function adds an DebugMapObject to the list owned by this /// debug map. DebugMapObject &addDebugMapObject(StringRef ObjectFilePath); const Triple &getTriple() const { return BinaryTriple; } void print(raw_ostream &OS) const; #ifndef NDEBUG void dump() const; #endif /// Read a debug map for \a InputFile. static ErrorOr<std::unique_ptr<DebugMap>> parseYAMLDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose); }; /// \brief The DebugMapObject represents one object file described by /// the DebugMap. It contains a list of mappings between addresses in /// the object file and in the linked binary for all the linked atoms /// in this object file. class DebugMapObject { public: struct SymbolMapping { yaml::Hex64 ObjectAddress; yaml::Hex64 BinaryAddress; yaml::Hex32 Size; SymbolMapping(uint64_t ObjectAddress, uint64_t BinaryAddress, uint32_t Size) : ObjectAddress(ObjectAddress), BinaryAddress(BinaryAddress), Size(Size) {} /// For YAML IO support SymbolMapping() = default; }; typedef StringMapEntry<SymbolMapping> DebugMapEntry; /// \brief Adds a symbol mapping to this DebugMapObject. /// \returns false if the symbol was already registered. The request /// is discarded in this case. bool addSymbol(llvm::StringRef SymName, uint64_t ObjectAddress, uint64_t LinkedAddress, uint32_t Size); /// \brief Lookup a symbol mapping. /// \returns null if the symbol isn't found. const DebugMapEntry *lookupSymbol(StringRef SymbolName) const; /// \brief Lookup an objectfile address. /// \returns null if the address isn't found. const DebugMapEntry *lookupObjectAddress(uint64_t Address) const; llvm::StringRef getObjectFilename() const { return Filename; } iterator_range<StringMap<SymbolMapping>::const_iterator> symbols() const { return make_range(Symbols.begin(), Symbols.end()); } void print(raw_ostream &OS) const; #ifndef NDEBUG void dump() const; #endif private: friend class DebugMap; /// DebugMapObjects can only be constructed by the owning DebugMap. DebugMapObject(StringRef ObjectFilename); std::string Filename; StringMap<SymbolMapping> Symbols; DenseMap<uint64_t, DebugMapEntry *> AddressToMapping; /// For YAMLIO support. ///@{ typedef std::pair<std::string, SymbolMapping> YAMLSymbolMapping; friend yaml::MappingTraits<dsymutil::DebugMapObject>; friend yaml::SequenceTraits<std::vector<std::unique_ptr<DebugMapObject>>>; friend yaml::SequenceTraits<std::vector<YAMLSymbolMapping>>; DebugMapObject() = default; public: DebugMapObject &operator=(DebugMapObject RHS) { std::swap(Filename, RHS.Filename); std::swap(Symbols, RHS.Symbols); std::swap(AddressToMapping, RHS.AddressToMapping); return *this; } DebugMapObject(DebugMapObject &&RHS) { Filename = std::move(RHS.Filename); Symbols = std::move(RHS.Symbols); AddressToMapping = std::move(RHS.AddressToMapping); } ///@} }; } } LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::dsymutil::DebugMapObject::YAMLSymbolMapping) namespace llvm { namespace yaml { using namespace llvm::dsymutil; template <> struct MappingTraits<std::pair<std::string, DebugMapObject::SymbolMapping>> { static void mapping(IO &io, std::pair<std::string, DebugMapObject::SymbolMapping> &s); static const bool flow = true; }; template <> struct MappingTraits<dsymutil::DebugMapObject> { struct YamlDMO; static void mapping(IO &io, dsymutil::DebugMapObject &DMO); }; template <> struct ScalarTraits<Triple> { static void output(const Triple &val, void *, llvm::raw_ostream &out); static StringRef input(StringRef scalar, void *, Triple &value); static bool mustQuote(StringRef) { return true; } }; template <> struct SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>> { static size_t size(IO &io, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq); static dsymutil::DebugMapObject & element(IO &, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq, size_t index); }; template <> struct MappingTraits<dsymutil::DebugMap> { static void mapping(IO &io, dsymutil::DebugMap &DM); }; template <> struct MappingTraits<std::unique_ptr<dsymutil::DebugMap>> { static void mapping(IO &io, std::unique_ptr<dsymutil::DebugMap> &DM); }; } } #endif // LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} AsmPrinter DebugInfoDWARF MC Object Support Target ) add_llvm_tool(llvm-dsymutil dsymutil.cpp BinaryHolder.cpp DebugMap.cpp DwarfLinker.cpp MachODebugMapParser.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/LLVMBuild.txt
;===- ./tools/dsymutil/LLVMBuild.txt ---------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-dsymutil parent = Tools required_libraries = AsmPrinter DebugInfoDWARF MC Object Support all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/DebugMap.cpp
//===- tools/dsymutil/DebugMap.cpp - Generic debug map representation -----===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DebugMap.h" #include "BinaryHolder.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> // // /////////////////////////////////////////////////////////////////////////////// namespace llvm { namespace dsymutil { using namespace llvm::object; DebugMapObject::DebugMapObject(StringRef ObjectFilename) : Filename(ObjectFilename) {} bool DebugMapObject::addSymbol(StringRef Name, uint64_t ObjectAddress, uint64_t LinkedAddress, uint32_t Size) { auto InsertResult = Symbols.insert( std::make_pair(Name, SymbolMapping(ObjectAddress, LinkedAddress, Size))); if (InsertResult.second) AddressToMapping[ObjectAddress] = &*InsertResult.first; return InsertResult.second; } void DebugMapObject::print(raw_ostream &OS) const { OS << getObjectFilename() << ":\n"; // Sort the symbols in alphabetical order, like llvm-nm (and to get // deterministic output for testing). typedef std::pair<StringRef, SymbolMapping> Entry; std::vector<Entry> Entries; Entries.reserve(Symbols.getNumItems()); for (const auto &Sym : make_range(Symbols.begin(), Symbols.end())) Entries.push_back(std::make_pair(Sym.getKey(), Sym.getValue())); std::sort( Entries.begin(), Entries.end(), [](const Entry &LHS, const Entry &RHS) { return LHS.first < RHS.first; }); for (const auto &Sym : Entries) { OS << format("\t%016" PRIx64 " => %016" PRIx64 "+0x%x\t%s\n", uint64_t(Sym.second.ObjectAddress), uint64_t(Sym.second.BinaryAddress), uint32_t(Sym.second.Size), Sym.first.data()); } OS << '\n'; } #ifndef NDEBUG void DebugMapObject::dump() const { print(errs()); } #endif DebugMapObject &DebugMap::addDebugMapObject(StringRef ObjectFilePath) { Objects.emplace_back(new DebugMapObject(ObjectFilePath)); return *Objects.back(); } const DebugMapObject::DebugMapEntry * DebugMapObject::lookupSymbol(StringRef SymbolName) const { StringMap<SymbolMapping>::const_iterator Sym = Symbols.find(SymbolName); if (Sym == Symbols.end()) return nullptr; return &*Sym; } const DebugMapObject::DebugMapEntry * DebugMapObject::lookupObjectAddress(uint64_t Address) const { auto Mapping = AddressToMapping.find(Address); if (Mapping == AddressToMapping.end()) return nullptr; return Mapping->getSecond(); } void DebugMap::print(raw_ostream &OS) const { yaml::Output yout(OS, /* Ctxt = */ nullptr, /* WrapColumn = */ 0); yout << const_cast<DebugMap &>(*this); } #ifndef NDEBUG void DebugMap::dump() const { print(errs()); } #endif namespace { struct YAMLContext { StringRef PrependPath; Triple BinaryTriple; }; } ErrorOr<std::unique_ptr<DebugMap>> DebugMap::parseYAMLDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose) { auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(InputFile); if (auto Err = ErrOrFile.getError()) return Err; YAMLContext Ctxt; Ctxt.PrependPath = PrependPath; std::unique_ptr<DebugMap> Res; yaml::Input yin((*ErrOrFile)->getBuffer(), &Ctxt); yin >> Res; if (auto EC = yin.error()) return EC; return std::move(Res); } } namespace yaml { // Normalize/Denormalize between YAML and a DebugMapObject. struct MappingTraits<dsymutil::DebugMapObject>::YamlDMO { YamlDMO(IO &io) {} YamlDMO(IO &io, dsymutil::DebugMapObject &Obj); dsymutil::DebugMapObject denormalize(IO &IO); std::string Filename; std::vector<dsymutil::DebugMapObject::YAMLSymbolMapping> Entries; }; void MappingTraits<std::pair<std::string, DebugMapObject::SymbolMapping>>:: mapping(IO &io, std::pair<std::string, DebugMapObject::SymbolMapping> &s) { io.mapRequired("sym", s.first); io.mapRequired("objAddr", s.second.ObjectAddress); io.mapRequired("binAddr", s.second.BinaryAddress); io.mapOptional("size", s.second.Size); } void MappingTraits<dsymutil::DebugMapObject>::mapping( IO &io, dsymutil::DebugMapObject &DMO) { MappingNormalization<YamlDMO, dsymutil::DebugMapObject> Norm(io, DMO); io.mapRequired("filename", Norm->Filename); io.mapRequired("symbols", Norm->Entries); } void ScalarTraits<Triple>::output(const Triple &val, void *, llvm::raw_ostream &out) { out << val.str(); } StringRef ScalarTraits<Triple>::input(StringRef scalar, void *, Triple &value) { value = Triple(scalar); return StringRef(); } size_t SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::size( IO &io, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq) { return seq.size(); } dsymutil::DebugMapObject & SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::element( IO &, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq, size_t index) { if (index >= seq.size()) { seq.resize(index + 1); seq[index].reset(new dsymutil::DebugMapObject); } return *seq[index]; } void MappingTraits<dsymutil::DebugMap>::mapping(IO &io, dsymutil::DebugMap &DM) { io.mapRequired("triple", DM.BinaryTriple); io.mapOptional("objects", DM.Objects); if (void *Ctxt = io.getContext()) reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM.BinaryTriple; } void MappingTraits<std::unique_ptr<dsymutil::DebugMap>>::mapping( IO &io, std::unique_ptr<dsymutil::DebugMap> &DM) { if (!DM) DM.reset(new DebugMap()); io.mapRequired("triple", DM->BinaryTriple); io.mapOptional("objects", DM->Objects); if (void *Ctxt = io.getContext()) reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM->BinaryTriple; } MappingTraits<dsymutil::DebugMapObject>::YamlDMO::YamlDMO( IO &io, dsymutil::DebugMapObject &Obj) { Filename = Obj.Filename; Entries.reserve(Obj.Symbols.size()); for (auto &Entry : Obj.Symbols) Entries.push_back(std::make_pair(Entry.getKey(), Entry.getValue())); } dsymutil::DebugMapObject MappingTraits<dsymutil::DebugMapObject>::YamlDMO::denormalize(IO &IO) { BinaryHolder BinHolder(/* Verbose =*/false); const auto &Ctxt = *reinterpret_cast<YAMLContext *>(IO.getContext()); SmallString<80> Path(Ctxt.PrependPath); StringMap<uint64_t> SymbolAddresses; sys::path::append(Path, Filename); auto ErrOrObjectFile = BinHolder.GetObjectFile(Path); if (auto EC = ErrOrObjectFile.getError()) { llvm::errs() << "warning: Unable to open " << Path << " " << EC.message() << '\n'; } else { // Rewrite the object file symbol addresses in the debug map. The // YAML input is mainly used to test llvm-dsymutil without // requiring binaries checked-in. If we generate the object files // during the test, we can't hardcode the symbols addresses, so // look them up here and rewrite them. for (const auto &Sym : ErrOrObjectFile->symbols()) { uint64_t Address = Sym.getValue(); ErrorOr<StringRef> Name = Sym.getName(); if (!Name) continue; SymbolAddresses[*Name] = Address; } } dsymutil::DebugMapObject Res(Path); for (auto &Entry : Entries) { auto &Mapping = Entry.second; uint64_t ObjAddress = Mapping.ObjectAddress; auto AddressIt = SymbolAddresses.find(Entry.first); if (AddressIt != SymbolAddresses.end()) ObjAddress = AddressIt->getValue(); Res.addSymbol(Entry.first, ObjAddress, Mapping.BinaryAddress, Mapping.Size); } return Res; } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/DwarfLinker.cpp
//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DebugMap.h" #include "BinaryHolder.h" #include "DebugMap.h" #include "dsymutil.h" #include "llvm/ADT/IntervalMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/DIE.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h" #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include <string> #include <tuple> // // /////////////////////////////////////////////////////////////////////////////// namespace llvm { namespace dsymutil { namespace { void warn(const Twine &Warning, const Twine &Context) { errs() << Twine("while processing ") + Context + ":\n"; errs() << Twine("warning: ") + Warning + "\n"; } bool error(const Twine &Error, const Twine &Context) { errs() << Twine("while processing ") + Context + ":\n"; errs() << Twine("error: ") + Error + "\n"; return false; } template <typename KeyT, typename ValT> using HalfOpenIntervalMap = IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize, IntervalMapHalfOpenInfo<KeyT>>; typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals; // FIXME: Delete this structure. struct PatchLocation { DIE::value_iterator I; PatchLocation() = default; PatchLocation(DIE::value_iterator I) : I(I) {} void set(uint64_t New) const { assert(I); const auto &Old = *I; assert(Old.getType() == DIEValue::isInteger); *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New)); } uint64_t get() const { assert(I); return I->getDIEInteger().getValue(); } }; /// \brief Stores all information relating to a compile unit, be it in /// its original instance in the object file to its brand new cloned /// and linked DIE tree. class CompileUnit { public: /// \brief Information gathered about a DIE in the object file. struct DIEInfo { int64_t AddrAdjust; ///< Address offset to apply to the described entity. DIE *Clone; ///< Cloned version of that DIE. uint32_t ParentIdx; ///< The index of this DIE's parent. bool Keep; ///< Is the DIE part of the linked output? bool InDebugMap; ///< Was this DIE's entity found in the map? }; CompileUnit(DWARFUnit &OrigUnit, unsigned ID) : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(), Ranges(RangeAlloc) { Info.resize(OrigUnit.getNumDIEs()); } CompileUnit(CompileUnit &&RHS) : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)), CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset), NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) { // The CompileUnit container has been 'reserve()'d with the right // size. We cannot move the IntervalMap anyway. llvm_unreachable("CompileUnits should not be moved."); } DWARFUnit &getOrigUnit() const { return OrigUnit; } unsigned getUniqueID() const { return ID; } DIE *getOutputUnitDIE() const { return CUDie; } void setOutputUnitDIE(DIE *Die) { CUDie = Die; } DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; } const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; } uint64_t getStartOffset() const { return StartOffset; } uint64_t getNextUnitOffset() const { return NextUnitOffset; } void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; } uint64_t getLowPc() const { return LowPc; } uint64_t getHighPc() const { return HighPc; } Optional<PatchLocation> getUnitRangesAttribute() const { return UnitRangeAttribute; } const FunctionIntervals &getFunctionRanges() const { return Ranges; } const std::vector<PatchLocation> &getRangesAttributes() const { return RangeAttributes; } const std::vector<std::pair<PatchLocation, int64_t>> & getLocationAttributes() const { return LocationAttributes; } /// \brief Compute the end offset for this unit. Must be /// called after the CU's DIEs have been cloned. /// \returns the next unit offset (which is also the current /// debug_info section size). uint64_t computeNextUnitOffset(); /// \brief Keep track of a forward reference to DIE \p Die in \p /// RefUnit by \p Attr. The attribute should be fixed up later to /// point to the absolute offset of \p Die in the debug_info section. void noteForwardReference(DIE *Die, const CompileUnit *RefUnit, PatchLocation Attr); /// \brief Apply all fixups recored by noteForwardReference(). void fixupForwardReferences(); /// \brief Add a function range [\p LowPC, \p HighPC) that is /// relocatad by applying offset \p PCOffset. void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset); /// \brief Keep track of a DW_AT_range attribute that we will need to /// patch up later. void noteRangeAttribute(const DIE &Die, PatchLocation Attr); /// \brief Keep track of a location attribute pointing to a location /// list in the debug_loc section. void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset); /// \brief Add a name accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset, bool SkipPubnamesSection = false); /// \brief Add a type accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset); struct AccelInfo { StringRef Name; ///< Name of the entry. const DIE *Die; ///< DIE this entry describes. uint32_t NameOffset; ///< Offset of Name in the string pool. bool SkipPubSection; ///< Emit this entry only in the apple_* sections. AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset, bool SkipPubSection = false) : Name(Name), Die(Die), NameOffset(NameOffset), SkipPubSection(SkipPubSection) {} }; const std::vector<AccelInfo> &getPubnames() const { return Pubnames; } const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; } private: DWARFUnit &OrigUnit; unsigned ID; std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index. DIE *CUDie; ///< Root of the linked DIE tree. uint64_t StartOffset; uint64_t NextUnitOffset; uint64_t LowPc; uint64_t HighPc; /// \brief A list of attributes to fixup with the absolute offset of /// a DIE in the debug_info section. /// /// The offsets for the attributes in this array couldn't be set while /// cloning because for cross-cu forward refences the target DIE's /// offset isn't known you emit the reference attribute. std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>> ForwardDIEReferences; FunctionIntervals::Allocator RangeAlloc; /// \brief The ranges in that interval map are the PC ranges for /// functions in this unit, associated with the PC offset to apply /// to the addresses to get the linked address. FunctionIntervals Ranges; /// \brief DW_AT_ranges attributes to patch after we have gathered /// all the unit's function addresses. /// @{ std::vector<PatchLocation> RangeAttributes; Optional<PatchLocation> UnitRangeAttribute; /// @} /// \brief Location attributes that need to be transfered from th /// original debug_loc section to the liked one. They are stored /// along with the PC offset that is to be applied to their /// function's address. std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes; /// \brief Accelerator entries for the unit, both for the pub* /// sections and the apple* ones. /// @{ std::vector<AccelInfo> Pubnames; std::vector<AccelInfo> Pubtypes; /// @} }; uint64_t CompileUnit::computeNextUnitOffset() { NextUnitOffset = StartOffset + 11 /* Header size */; // The root DIE might be null, meaning that the Unit had nothing to // contribute to the linked output. In that case, we will emit the // unit header without any actual DIE. if (CUDie) NextUnitOffset += CUDie->getSize(); return NextUnitOffset; } /// \brief Keep track of a forward cross-cu reference from this unit /// to \p Die that lives in \p RefUnit. void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit, PatchLocation Attr) { ForwardDIEReferences.emplace_back(Die, RefUnit, Attr); } /// \brief Apply all fixups recorded by noteForwardReference(). void CompileUnit::fixupForwardReferences() { for (const auto &Ref : ForwardDIEReferences) { DIE *RefDie; const CompileUnit *RefUnit; PatchLocation Attr; std::tie(RefDie, RefUnit, Attr) = Ref; Attr.set(RefDie->getOffset() + RefUnit->getStartOffset()); } } void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc, int64_t PcOffset) { Ranges.insert(FuncLowPc, FuncHighPc, PcOffset); this->LowPc = std::min(LowPc, FuncLowPc + PcOffset); this->HighPc = std::max(HighPc, FuncHighPc + PcOffset); } void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) { if (Die.getTag() != dwarf::DW_TAG_compile_unit) RangeAttributes.push_back(Attr); else UnitRangeAttribute = Attr; } void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) { LocationAttributes.emplace_back(Attr, PcOffset); } /// \brief Add a name accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset, bool SkipPubSection) { Pubnames.emplace_back(Name, Die, Offset, SkipPubSection); } /// \brief Add a type accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset) { Pubtypes.emplace_back(Name, Die, Offset, false); } /// \brief A string table that doesn't need relocations. /// /// We are doing a final link, no need for a string table that /// has relocation entries for every reference to it. This class /// provides this ablitity by just associating offsets with /// strings. class NonRelocatableStringpool { public: /// \brief Entries are stored into the StringMap and simply linked /// together through the second element of this pair in order to /// keep track of insertion order. typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator> MapTy; NonRelocatableStringpool() : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) { // Legacy dsymutil puts an empty string at the start of the line // table. getStringOffset(""); } /// \brief Get the offset of string \p S in the string table. This /// can insert a new element or return the offset of a preexisitng /// one. uint32_t getStringOffset(StringRef S); /// \brief Get permanent storage for \p S (but do not necessarily /// emit \p S in the output section). /// \returns The StringRef that points to permanent storage to use /// in place of \p S. StringRef internString(StringRef S); // \brief Return the first entry of the string table. const MapTy::MapEntryTy *getFirstEntry() const { return getNextEntry(&Sentinel); } // \brief Get the entry following \p E in the string table or null // if \p E was the last entry. const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const { return static_cast<const MapTy::MapEntryTy *>(E->getValue().second); } uint64_t getSize() { return CurrentEndOffset; } private: MapTy Strings; uint32_t CurrentEndOffset; MapTy::MapEntryTy Sentinel, *Last; }; /// \brief Get the offset of string \p S in the string table. This /// can insert a new element or return the offset of a preexisitng /// one. uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) { if (S.empty() && !Strings.empty()) return 0; std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr); MapTy::iterator It; bool Inserted; // A non-empty string can't be at offset 0, so if we have an entry // with a 0 offset, it must be a previously interned string. std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry)); if (Inserted || It->getValue().first == 0) { // Set offset and chain at the end of the entries list. It->getValue().first = CurrentEndOffset; CurrentEndOffset += S.size() + 1; // +1 for the '\0'. Last->getValue().second = &*It; Last = &*It; } return It->getValue().first; } /// \brief Put \p S into the StringMap so that it gets permanent /// storage, but do not actually link it in the chain of elements /// that go into the output section. A latter call to /// getStringOffset() with the same string will chain it though. StringRef NonRelocatableStringpool::internString(StringRef S) { std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr); auto InsertResult = Strings.insert(std::make_pair(S, Entry)); return InsertResult.first->getKey(); } /// \brief The Dwarf streaming logic /// /// All interactions with the MC layer that is used to build the debug /// information binary representation are handled in this class. class DwarfStreamer { /// \defgroup MCObjects MC layer objects constructed by the streamer /// @{ std::unique_ptr<MCRegisterInfo> MRI; std::unique_ptr<MCAsmInfo> MAI; std::unique_ptr<MCObjectFileInfo> MOFI; std::unique_ptr<MCContext> MC; MCAsmBackend *MAB; // Owned by MCStreamer std::unique_ptr<MCInstrInfo> MII; std::unique_ptr<MCSubtargetInfo> MSTI; MCCodeEmitter *MCE; // Owned by MCStreamer MCStreamer *MS; // Owned by AsmPrinter std::unique_ptr<TargetMachine> TM; std::unique_ptr<AsmPrinter> Asm; /// @} /// \brief the file we stream the linked Dwarf to. std::unique_ptr<raw_fd_ostream> OutFile; uint32_t RangesSectionSize; uint32_t LocSectionSize; uint32_t LineSectionSize; uint32_t FrameSectionSize; /// \brief Emit the pubnames or pubtypes section contribution for \p /// Unit into \p Sec. The data is provided in \p Names. void emitPubSectionForUnit(MCSection *Sec, StringRef Name, const CompileUnit &Unit, const std::vector<CompileUnit::AccelInfo> &Names); public: /// \brief Actually create the streamer and the ouptut file. /// /// This could be done directly in the constructor, but it feels /// more natural to handle errors through return value. bool init(Triple TheTriple, StringRef OutputFilename); /// \brief Dump the file to the disk. bool finish(); AsmPrinter &getAsmPrinter() const { return *Asm; } /// \brief Set the current output section to debug_info and change /// the MC Dwarf version to \p DwarfVersion. void switchToDebugInfoSection(unsigned DwarfVersion); /// \brief Emit the compilation unit header for \p Unit in the /// debug_info section. /// /// As a side effect, this also switches the current Dwarf version /// of the MC layer to the one of U.getOrigUnit(). void emitCompileUnitHeader(CompileUnit &Unit); /// \brief Recursively emit the DIE tree rooted at \p Die. void emitDIE(DIE &Die); /// \brief Emit the abbreviation table \p Abbrevs to the /// debug_abbrev section. void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs); /// \brief Emit the string table described by \p Pool. void emitStrings(const NonRelocatableStringpool &Pool); /// \brief Emit debug_ranges for \p FuncRange by translating the /// original \p Entries. void emitRangesEntries( int64_t UnitPcOffset, uint64_t OrigLowPc, FunctionIntervals::const_iterator FuncRange, const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries, unsigned AddressSize); /// \brief Emit debug_aranges entries for \p Unit and if \p /// DoRangesSection is true, also emit the debug_ranges entries for /// the DW_TAG_compile_unit's DW_AT_ranges attribute. void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection); uint32_t getRangesSectionSize() const { return RangesSectionSize; } /// \brief Emit the debug_loc contribution for \p Unit by copying /// the entries from \p Dwarf and offseting them. Update the /// location attributes to point to the new entries. void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf); /// \brief Emit the line table described in \p Rows into the /// debug_line section. void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength, std::vector<DWARFDebugLine::Row> &Rows, unsigned AdddressSize); uint32_t getLineSectionSize() const { return LineSectionSize; } /// \brief Emit the .debug_pubnames contribution for \p Unit. void emitPubNamesForUnit(const CompileUnit &Unit); /// \brief Emit the .debug_pubtypes contribution for \p Unit. void emitPubTypesForUnit(const CompileUnit &Unit); /// \brief Emit a CIE. void emitCIE(StringRef CIEBytes); /// \brief Emit an FDE with data \p Bytes. void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address, StringRef Bytes); uint32_t getFrameSectionSize() const { return FrameSectionSize; } }; bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) { std::string ErrorStr; std::string TripleName; StringRef Context = "dwarf streamer init"; // Get the target. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr); if (!TheTarget) return error(ErrorStr, Context); TripleName = TheTriple.getTriple(); // Create all the MC Objects. MRI.reset(TheTarget->createMCRegInfo(TripleName)); if (!MRI) return error(Twine("no register info for target ") + TripleName, Context); MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName)); if (!MAI) return error("no asm info for target " + TripleName, Context); MOFI.reset(new MCObjectFileInfo); MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get())); MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default, *MC); MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, ""); if (!MAB) return error("no asm backend for target " + TripleName, Context); MII.reset(TheTarget->createMCInstrInfo()); if (!MII) return error("no instr info info for target " + TripleName, Context); MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", "")); if (!MSTI) return error("no subtarget info for target " + TripleName, Context); MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC); if (!MCE) return error("no code emitter for target " + TripleName, Context); // Create the output file. std::error_code EC; OutFile = llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None); if (EC) return error(Twine(OutputFilename) + ": " + EC.message(), Context); MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, false, /*DWARFMustBeAtTheEnd*/ false); if (!MS) return error("no object streamer for target " + TripleName, Context); // Finally create the AsmPrinter we'll use to emit the DIEs. TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions())); if (!TM) return error("no target machine for target " + TripleName, Context); Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS))); if (!Asm) return error("no asm printer for target " + TripleName, Context); RangesSectionSize = 0; LocSectionSize = 0; LineSectionSize = 0; FrameSectionSize = 0; return true; } bool DwarfStreamer::finish() { MS->Finish(); return true; } /// \brief Set the current output section to debug_info and change /// the MC Dwarf version to \p DwarfVersion. void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) { MS->SwitchSection(MOFI->getDwarfInfoSection()); MC->setDwarfVersion(DwarfVersion); } /// \brief Emit the compilation unit header for \p Unit in the /// debug_info section. /// /// A Dwarf scetion header is encoded as: /// uint32_t Unit length (omiting this field) /// uint16_t Version /// uint32_t Abbreviation table offset /// uint8_t Address size /// /// Leading to a total of 11 bytes. void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) { unsigned Version = Unit.getOrigUnit().getVersion(); switchToDebugInfoSection(Version); // Emit size of content not including length itself. The size has // already been computed in CompileUnit::computeOffsets(). Substract // 4 to that size to account for the length field. Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4); Asm->EmitInt16(Version); // We share one abbreviations table across all units so it's always at the // start of the section. Asm->EmitInt32(0); Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize()); } /// \brief Emit the \p Abbrevs array as the shared abbreviation table /// for the linked Dwarf file. void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) { MS->SwitchSection(MOFI->getDwarfAbbrevSection()); Asm->emitDwarfAbbrevs(Abbrevs); } /// \brief Recursively emit the DIE tree rooted at \p Die. void DwarfStreamer::emitDIE(DIE &Die) { MS->SwitchSection(MOFI->getDwarfInfoSection()); Asm->emitDwarfDIE(Die); } /// \brief Emit the debug_str section stored in \p Pool. void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection()); for (auto *Entry = Pool.getFirstEntry(); Entry; Entry = Pool.getNextEntry(Entry)) Asm->OutStreamer->EmitBytes( StringRef(Entry->getKey().data(), Entry->getKey().size() + 1)); } /// \brief Emit the debug_range section contents for \p FuncRange by /// translating the original \p Entries. The debug_range section /// format is totally trivial, consisting just of pairs of address /// sized addresses describing the ranges. void DwarfStreamer::emitRangesEntries( int64_t UnitPcOffset, uint64_t OrigLowPc, FunctionIntervals::const_iterator FuncRange, const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries, unsigned AddressSize) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); // Offset each range by the right amount. int64_t PcOffset = FuncRange.value() + UnitPcOffset; for (const auto &Range : Entries) { if (Range.isBaseAddressSelectionEntry(AddressSize)) { warn("unsupported base address selection operation", "emitting debug_ranges"); break; } // Do not emit empty ranges. if (Range.StartAddress == Range.EndAddress) continue; // All range entries should lie in the function range. if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() && Range.EndAddress + OrigLowPc <= FuncRange.stop())) warn("inconsistent range data.", "emitting debug_ranges"); MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize); MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize); RangesSectionSize += 2 * AddressSize; } // Add the terminator entry. MS->EmitIntValue(0, AddressSize); MS->EmitIntValue(0, AddressSize); RangesSectionSize += 2 * AddressSize; } /// \brief Emit the debug_aranges contribution of a unit and /// if \p DoDebugRanges is true the debug_range contents for a /// compile_unit level DW_AT_ranges attribute (Which are basically the /// same thing with a different base address). /// Just aggregate all the ranges gathered inside that unit. void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit, bool DoDebugRanges) { unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); // Gather the ranges in a vector, so that we can simplify them. The // IntervalMap will have coalesced the non-linked ranges, but here // we want to coalesce the linked addresses. std::vector<std::pair<uint64_t, uint64_t>> Ranges; const auto &FunctionRanges = Unit.getFunctionRanges(); for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end(); Range != End; ++Range) Ranges.push_back(std::make_pair(Range.start() + Range.value(), Range.stop() + Range.value())); // The object addresses where sorted, but again, the linked // addresses might end up in a different order. std::sort(Ranges.begin(), Ranges.end()); if (!Ranges.empty()) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection()); MCSymbol *BeginLabel = Asm->createTempSymbol("Barange"); MCSymbol *EndLabel = Asm->createTempSymbol("Earange"); unsigned HeaderSize = sizeof(int32_t) + // Size of contents (w/o this field sizeof(int16_t) + // DWARF ARange version number sizeof(int32_t) + // Offset of CU in the .debug_info section sizeof(int8_t) + // Pointer Size (in bytes) sizeof(int8_t); // Segment Size (in bytes) unsigned TupleSize = AddressSize * 2; unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize); Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length Asm->OutStreamer->EmitLabel(BeginLabel); Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset Asm->EmitInt8(AddressSize); // Address size Asm->EmitInt8(0); // Segment size Asm->OutStreamer->EmitFill(Padding, 0x0); for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) { uint64_t RangeStart = Range->first; MS->EmitIntValue(RangeStart, AddressSize); while ((Range + 1) != End && Range->second == (Range + 1)->first) ++Range; MS->EmitIntValue(Range->second - RangeStart, AddressSize); } // Emit terminator Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitLabel(EndLabel); } if (!DoDebugRanges) return; MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); // Offset each range by the right amount. int64_t PcOffset = -Unit.getLowPc(); // Emit coalesced ranges. for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) { MS->EmitIntValue(Range->first + PcOffset, AddressSize); while (Range + 1 != End && Range->second == (Range + 1)->first) ++Range; MS->EmitIntValue(Range->second + PcOffset, AddressSize); RangesSectionSize += 2 * AddressSize; } // Add the terminator entry. MS->EmitIntValue(0, AddressSize); MS->EmitIntValue(0, AddressSize); RangesSectionSize += 2 * AddressSize; } /// \brief Emit location lists for \p Unit and update attribtues to /// point to the new entries. void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) { const auto &Attributes = Unit.getLocationAttributes(); if (Attributes.empty()) return; MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection()); unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); const DWARFSection &InputSec = Dwarf.getLocSection(); DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize); DWARFUnit &OrigUnit = Unit.getOrigUnit(); const auto *OrigUnitDie = OrigUnit.getUnitDIE(false); int64_t UnitPcOffset = 0; uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress( &OrigUnit, dwarf::DW_AT_low_pc, -1ULL); if (OrigLowPc != -1ULL) UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc(); for (const auto &Attr : Attributes) { uint32_t Offset = Attr.first.get(); Attr.first.set(LocSectionSize); // This is the quantity to add to the old location address to get // the correct address for the new one. int64_t LocPcOffset = Attr.second + UnitPcOffset; while (Data.isValidOffset(Offset)) { uint64_t Low = Data.getUnsigned(&Offset, AddressSize); uint64_t High = Data.getUnsigned(&Offset, AddressSize); LocSectionSize += 2 * AddressSize; if (Low == 0 && High == 0) { Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitIntValue(0, AddressSize); break; } Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize); Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize); uint64_t Length = Data.getU16(&Offset); Asm->OutStreamer->EmitIntValue(Length, 2); // Just copy the bytes over. Asm->OutStreamer->EmitBytes( StringRef(InputSec.Data.substr(Offset, Length))); Offset += Length; LocSectionSize += Length + 2; } } } void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength, std::vector<DWARFDebugLine::Row> &Rows, unsigned PointerSize) { // Switch to the section where the table will be emitted into. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection()); MCSymbol *LineStartSym = MC->createTempSymbol(); MCSymbol *LineEndSym = MC->createTempSymbol(); // The first 4 bytes is the total length of the information for this // compilation unit (not including these 4 bytes for the length). Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4); Asm->OutStreamer->EmitLabel(LineStartSym); // Copy Prologue. MS->EmitBytes(PrologueBytes); LineSectionSize += PrologueBytes.size() + 4; SmallString<128> EncodingBuffer; raw_svector_ostream EncodingOS(EncodingBuffer); if (Rows.empty()) { // We only have the dummy entry, dsymutil emits an entry with a 0 // address in that case. MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); MS->EmitLabel(LineEndSym); return; } // Line table state machine fields unsigned FileNum = 1; unsigned LastLine = 1; unsigned Column = 0; unsigned IsStatement = 1; unsigned Isa = 0; uint64_t Address = -1ULL; unsigned RowsSinceLastSequence = 0; for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) { auto &Row = Rows[Idx]; int64_t AddressDelta; if (Address == -1ULL) { MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1); MS->EmitULEB128IntValue(PointerSize + 1); MS->EmitIntValue(dwarf::DW_LNE_set_address, 1); MS->EmitIntValue(Row.Address, PointerSize); LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1); AddressDelta = 0; } else { AddressDelta = (Row.Address - Address) / MinInstLength; } // FIXME: code copied and transfromed from // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share // this code, but the current compatibility requirement with // classic dsymutil makes it hard. Revisit that once this // requirement is dropped. if (FileNum != Row.File) { FileNum = Row.File; MS->EmitIntValue(dwarf::DW_LNS_set_file, 1); MS->EmitULEB128IntValue(FileNum); LineSectionSize += 1 + getULEB128Size(FileNum); } if (Column != Row.Column) { Column = Row.Column; MS->EmitIntValue(dwarf::DW_LNS_set_column, 1); MS->EmitULEB128IntValue(Column); LineSectionSize += 1 + getULEB128Size(Column); } // FIXME: We should handle the discriminator here, but dsymutil // doesn' consider it, thus ignore it for now. if (Isa != Row.Isa) { Isa = Row.Isa; MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); MS->EmitULEB128IntValue(Isa); LineSectionSize += 1 + getULEB128Size(Isa); } if (IsStatement != Row.IsStmt) { IsStatement = Row.IsStmt; MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); LineSectionSize += 1; } if (Row.BasicBlock) { MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); LineSectionSize += 1; } if (Row.PrologueEnd) { MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); LineSectionSize += 1; } if (Row.EpilogueBegin) { MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); LineSectionSize += 1; } int64_t LineDelta = int64_t(Row.Line) - LastLine; if (!Row.EndSequence) { MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); EncodingOS.resync(); Address = Row.Address; LastLine = Row.Line; RowsSinceLastSequence++; } else { if (LineDelta) { MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1); MS->EmitSLEB128IntValue(LineDelta); LineSectionSize += 1 + getSLEB128Size(LineDelta); } if (AddressDelta) { MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1); MS->EmitULEB128IntValue(AddressDelta); LineSectionSize += 1 + getULEB128Size(AddressDelta); } MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); EncodingOS.resync(); Address = -1ULL; LastLine = FileNum = IsStatement = 1; RowsSinceLastSequence = Column = Isa = 0; } } if (RowsSinceLastSequence) { MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); EncodingOS.resync(); } MS->EmitLabel(LineEndSym); } /// \brief Emit the pubnames or pubtypes section contribution for \p /// Unit into \p Sec. The data is provided in \p Names. void DwarfStreamer::emitPubSectionForUnit( MCSection *Sec, StringRef SecName, const CompileUnit &Unit, const std::vector<CompileUnit::AccelInfo> &Names) { if (Names.empty()) return; // Start the dwarf pubnames section. Asm->OutStreamer->SwitchSection(Sec); MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin"); MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end"); bool HeaderEmitted = false; // Emit the pubnames for this compilation unit. for (const auto &Name : Names) { if (Name.SkipPubSection) continue; if (!HeaderEmitted) { // Emit the header. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length Asm->OutStreamer->EmitLabel(BeginLabel); Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version Asm->EmitInt32(Unit.getStartOffset()); // Unit offset Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size HeaderEmitted = true; } Asm->EmitInt32(Name.Die->getOffset()); Asm->OutStreamer->EmitBytes( StringRef(Name.Name.data(), Name.Name.size() + 1)); } if (!HeaderEmitted) return; Asm->EmitInt32(0); // End marker. Asm->OutStreamer->EmitLabel(EndLabel); } /// \brief Emit .debug_pubnames for \p Unit. void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) { emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(), "names", Unit, Unit.getPubnames()); } /// \brief Emit .debug_pubtypes for \p Unit. void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) { emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(), "types", Unit, Unit.getPubtypes()); } /// \brief Emit a CIE into the debug_frame section. void DwarfStreamer::emitCIE(StringRef CIEBytes) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); MS->EmitBytes(CIEBytes); FrameSectionSize += CIEBytes.size(); } /// \brief Emit a FDE into the debug_frame section. \p FDEBytes /// contains the FDE data without the length, CIE offset and address /// which will be replaced with the paramter values. void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint32_t Address, StringRef FDEBytes) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4); MS->EmitIntValue(CIEOffset, 4); MS->EmitIntValue(Address, AddrSize); MS->EmitBytes(FDEBytes); FrameSectionSize += FDEBytes.size() + 8 + AddrSize; } /// \brief The core of the Dwarf linking logic. /// /// The link of the dwarf information from the object files will be /// driven by the selection of 'root DIEs', which are DIEs that /// describe variables or functions that are present in the linked /// binary (and thus have entries in the debug map). All the debug /// information that will be linked (the DIEs, but also the line /// tables, ranges, ...) is derived from that set of root DIEs. /// /// The root DIEs are identified because they contain relocations that /// correspond to a debug map entry at specific places (the low_pc for /// a function, the location for a variable). These relocations are /// called ValidRelocs in the DwarfLinker and are gathered as a very /// first step when we start processing a DebugMapObject. class DwarfLinker { public: DwarfLinker(StringRef OutputFilename, const LinkOptions &Options) : OutputFilename(OutputFilename), Options(Options), BinHolder(Options.Verbose), LastCIEOffset(0) {} ~DwarfLinker() { for (auto *Abbrev : Abbreviations) delete Abbrev; } /// \brief Link the contents of the DebugMap. bool link(const DebugMap &); private: /// \brief Called at the start of a debug object link. void startDebugObject(DWARFContext &, DebugMapObject &); /// \brief Called at the end of a debug object link. void endDebugObject(); /// \defgroup FindValidRelocations Translate debug map into a list /// of relevant relocations /// /// @{ struct ValidReloc { uint32_t Offset; uint32_t Size; uint64_t Addend; const DebugMapObject::DebugMapEntry *Mapping; ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend, const DebugMapObject::DebugMapEntry *Mapping) : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {} bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; } }; /// \brief The valid relocations for the current DebugMapObject. /// This vector is sorted by relocation offset. std::vector<ValidReloc> ValidRelocs; /// \brief Index into ValidRelocs of the next relocation to /// consider. As we walk the DIEs in acsending file offset and as /// ValidRelocs is sorted by file offset, keeping this index /// uptodate is all we have to do to have a cheap lookup during the /// root DIE selection and during DIE cloning. unsigned NextValidReloc; bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj, const DebugMapObject &DMO); bool findValidRelocs(const object::SectionRef &Section, const object::ObjectFile &Obj, const DebugMapObject &DMO); void findValidRelocsMachO(const object::SectionRef &Section, const object::MachOObjectFile &Obj, const DebugMapObject &DMO); /// @} /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries. /// /// @{ /// \brief Recursively walk the \p DIE tree and look for DIEs to /// keep. Store that information in \p CU's DIEInfo. void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE, const DebugMapObject &DMO, CompileUnit &CU, unsigned Flags); /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep enum TravesalFlags { TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept. TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope. TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE. TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE. }; /// \brief Mark the passed DIE as well as all the ones it depends on /// as kept. void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit::DIEInfo &MyInfo, const DebugMapObject &DMO, CompileUnit &CU, unsigned Flags); unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags); unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags); unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags); bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset, CompileUnit::DIEInfo &Info); /// @} /// \defgroup Linking Methods used to link the debug information /// /// @{ /// \brief Recursively clone \p InputDIE into an tree of DIE objects /// where useless (as decided by lookForDIEsToKeep()) bits have been /// stripped out and addresses have been rewritten according to the /// debug map. /// /// \param OutOffset is the offset the cloned DIE in the output /// compile unit. /// \param PCOffset (while cloning a function scope) is the offset /// applied to the entry point of the function to get the linked address. /// /// \returns the root of the cloned tree. DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U, int64_t PCOffset, uint32_t OutOffset); typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec; /// \brief Information gathered and exchanged between the various /// clone*Attributes helpers about the attributes of a particular DIE. struct AttributesInfo { const char *Name, *MangledName; ///< Names. uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool. uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE int64_t PCOffset; ///< Offset to apply to PC addresses inside a function. bool HasLowPc; ///< Does the DIE have a low_pc attribute? bool IsDeclaration; ///< Is this DIE only a declaration? AttributesInfo() : Name(nullptr), MangledName(nullptr), NameOffset(0), MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false), IsDeclaration(false) {} }; /// \brief Helper for cloneDIE. unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U, const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &AttrInfo); /// \brief Helper for cloneDIE. unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, const DWARFUnit &U); /// \brief Helper for cloneDIE. unsigned cloneDieReferenceAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val, CompileUnit &Unit); /// \brief Helper for cloneDIE. unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize); /// \brief Helper for cloneDIE. unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, const CompileUnit &Unit, AttributesInfo &Info); /// \brief Helper for cloneDIE. unsigned cloneScalarAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U, AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize, AttributesInfo &Info); /// \brief Helper for cloneDIE. bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset, bool isLittleEndian); /// \brief Assign an abbreviation number to \p Abbrev void AssignAbbrev(DIEAbbrev &Abbrev); /// \brief FoldingSet that uniques the abbreviations. FoldingSet<DIEAbbrev> AbbreviationsSet; /// \brief Storage for the unique Abbreviations. /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot /// be changed to a vecot of unique_ptrs. std::vector<DIEAbbrev *> Abbreviations; /// \brief Compute and emit debug_ranges section for \p Unit, and /// patch the attributes referencing it. void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const; /// \brief Generate and emit the DW_AT_ranges attribute for a /// compile_unit if it had one. void generateUnitRanges(CompileUnit &Unit) const; /// \brief Extract the line tables fromt he original dwarf, extract /// the relevant parts according to the linked function ranges and /// emit the result in the debug_line section. void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf); /// \brief Emit the accelerator entries for \p Unit. void emitAcceleratorEntriesForUnit(CompileUnit &Unit); /// \brief Patch the frame info for an object file and emit it. void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &, unsigned AddressSize); /// \brief DIELoc objects that need to be destructed (but not freed!). std::vector<DIELoc *> DIELocs; /// \brief DIEBlock objects that need to be destructed (but not freed!). std::vector<DIEBlock *> DIEBlocks; /// \brief Allocator used for all the DIEValue objects. BumpPtrAllocator DIEAlloc; /// @} /// \defgroup Helpers Various helper methods. /// /// @{ const DWARFDebugInfoEntryMinimal * resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit, const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&ReferencedCU); CompileUnit *getUnitForOffset(unsigned Offset); bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U, AttributesInfo &Info); void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr, const DWARFDebugInfoEntryMinimal *DIE = nullptr) const; bool createStreamer(Triple TheTriple, StringRef OutputFilename); /// @} private: std::string OutputFilename; LinkOptions Options; BinaryHolder BinHolder; std::unique_ptr<DwarfStreamer> Streamer; /// The units of the current debug map object. std::vector<CompileUnit> Units; /// The debug map object curently under consideration. DebugMapObject *CurrentDebugObject; /// \brief The Dwarf string pool NonRelocatableStringpool StringPool; /// \brief This map is keyed by the entry PC of functions in that /// debug object and the associated value is a pair storing the /// corresponding end PC and the offset to apply to get the linked /// address. /// /// See startDebugObject() for a more complete description of its use. std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges; /// \brief The CIEs that have been emitted in the output /// section. The actual CIE data serves a the key to this StringMap, /// this takes care of comparing the semantics of CIEs defined in /// different object files. StringMap<uint32_t> EmittedCIEs; /// Offset of the last CIE that has been emitted in the output /// debug_frame section. uint32_t LastCIEOffset; }; /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but /// returning our CompileUnit object instead. CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) { auto CU = std::upper_bound(Units.begin(), Units.end(), Offset, [](uint32_t LHS, const CompileUnit &RHS) { return LHS < RHS.getOrigUnit().getNextUnitOffset(); }); return CU != Units.end() ? &*CU : nullptr; } /// \brief Resolve the DIE attribute reference that has been /// extracted in \p RefValue. The resulting DIE migh be in another /// CompileUnit which is stored into \p ReferencedCU. /// \returns null if resolving fails for any reason. const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference( DWARFFormValue &RefValue, const DWARFUnit &Unit, const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) { assert(RefValue.isFormClass(DWARFFormValue::FC_Reference)); uint64_t RefOffset = *RefValue.getAsReference(&Unit); if ((RefCU = getUnitForOffset(RefOffset))) if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) return RefDie; reportWarning("could not find referenced DIE", &Unit, &DIE); return nullptr; } /// \brief Get the potential name and mangled name for the entity /// described by \p Die and store them in \Info if they are not /// already there. /// \returns is a name was found. bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U, AttributesInfo &Info) { // FIXME: a bit wastefull as the first getName might return the // short name. if (!Info.MangledName && (Info.MangledName = Die.getName(&U, DINameKind::LinkageName))) Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName); if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName))) Info.NameOffset = StringPool.getStringOffset(Info.Name); return Info.Name || Info.MangledName; } /// \brief Report a warning to the user, optionaly including /// information about a specific \p DIE related to the warning. void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit, const DWARFDebugInfoEntryMinimal *DIE) const { StringRef Context = "<debug map>"; if (CurrentDebugObject) Context = CurrentDebugObject->getObjectFilename(); warn(Warning, Context); if (!Options.Verbose || !DIE) return; errs() << " in DIE:\n"; DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */, 6 /* Indent */); } bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) { if (Options.NoOutput) return true; Streamer = llvm::make_unique<DwarfStreamer>(); return Streamer->init(TheTriple, OutputFilename); } /// \brief Recursive helper to gather the child->parent relationships in the /// original compile unit. static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE, unsigned ParentIdx, CompileUnit &CU) { unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE); CU.getInfo(MyIdx).ParentIdx = ParentIdx; if (DIE->hasChildren()) for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL(); Child = Child->getSibling()) gatherDIEParents(Child, MyIdx, CU); } static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) { switch (Tag) { default: return false; case dwarf::DW_TAG_subprogram: case dwarf::DW_TAG_lexical_block: case dwarf::DW_TAG_subroutine_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_union_type: return true; } llvm_unreachable("Invalid Tag"); } void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) { Units.reserve(Dwarf.getNumCompileUnits()); NextValidReloc = 0; // Iterate over the debug map entries and put all the ones that are // functions (because they have a size) into the Ranges map. This // map is very similar to the FunctionRanges that are stored in each // unit, with 2 notable differences: // - obviously this one is global, while the other ones are per-unit. // - this one contains not only the functions described in the DIE // tree, but also the ones that are only in the debug map. // The latter information is required to reproduce dsymutil's logic // while linking line tables. The cases where this information // matters look like bugs that need to be investigated, but for now // we need to reproduce dsymutil's behavior. // FIXME: Once we understood exactly if that information is needed, // maybe totally remove this (or try to use it to do a real // -gline-tables-only on Darwin. for (const auto &Entry : Obj.symbols()) { const auto &Mapping = Entry.getValue(); if (Mapping.Size) Ranges[Mapping.ObjectAddress] = std::make_pair( Mapping.ObjectAddress + Mapping.Size, int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress); } } void DwarfLinker::endDebugObject() { Units.clear(); ValidRelocs.clear(); Ranges.clear(); for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I) (*I)->~DIEBlock(); for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I) (*I)->~DIELoc(); DIEBlocks.clear(); DIELocs.clear(); DIEAlloc.Reset(); } /// \brief Iterate over the relocations of the given \p Section and /// store the ones that correspond to debug map entries into the /// ValidRelocs array. void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section, const object::MachOObjectFile &Obj, const DebugMapObject &DMO) { StringRef Contents; Section.getContents(Contents); DataExtractor Data(Contents, Obj.isLittleEndian(), 0); for (const object::RelocationRef &Reloc : Section.relocations()) { object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl(); MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef); unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc); uint64_t Offset64 = Reloc.getOffset(); if ((RelocSize != 4 && RelocSize != 8)) { reportWarning(" unsupported relocation in debug_info section."); continue; } uint32_t Offset = Offset64; // Mach-o uses REL relocations, the addend is at the relocation offset. uint64_t Addend = Data.getUnsigned(&Offset, RelocSize); auto Sym = Reloc.getSymbol(); if (Sym != Obj.symbol_end()) { ErrorOr<StringRef> SymbolName = Sym->getName(); if (!SymbolName) { reportWarning("error getting relocation symbol name."); continue; } if (const auto *Mapping = DMO.lookupSymbol(*SymbolName)) ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping); } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) { // Do not store the addend. The addend was the address of the // symbol in the object file, the address in the binary that is // stored in the debug map doesn't need to be offseted. ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping); } } } /// \brief Dispatch the valid relocation finding logic to the /// appropriate handler depending on the object file format. bool DwarfLinker::findValidRelocs(const object::SectionRef &Section, const object::ObjectFile &Obj, const DebugMapObject &DMO) { // Dispatch to the right handler depending on the file type. if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj)) findValidRelocsMachO(Section, *MachOObj, DMO); else reportWarning(Twine("unsupported object file type: ") + Obj.getFileName()); if (ValidRelocs.empty()) return false; // Sort the relocations by offset. We will walk the DIEs linearly in // the file, this allows us to just keep an index in the relocation // array that we advance during our walk, rather than resorting to // some associative container. See DwarfLinker::NextValidReloc. std::sort(ValidRelocs.begin(), ValidRelocs.end()); return true; } /// \brief Look for relocations in the debug_info section that match /// entries in the debug map. These relocations will drive the Dwarf /// link by indicating which DIEs refer to symbols present in the /// linked binary. /// \returns wether there are any valid relocations in the debug info. bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj, const DebugMapObject &DMO) { // Find the debug_info section. for (const object::SectionRef &Section : Obj.sections()) { StringRef SectionName; Section.getName(SectionName); SectionName = SectionName.substr(SectionName.find_first_not_of("._")); if (SectionName != "debug_info") continue; return findValidRelocs(Section, Obj, DMO); } return false; } /// \brief Checks that there is a relocation against an actual debug /// map entry between \p StartOffset and \p NextOffset. /// /// This function must be called with offsets in strictly ascending /// order because it never looks back at relocations it already 'went past'. /// \returns true and sets Info.InDebugMap if it is the case. bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset, CompileUnit::DIEInfo &Info) { assert(NextValidReloc == 0 || StartOffset > ValidRelocs[NextValidReloc - 1].Offset); if (NextValidReloc >= ValidRelocs.size()) return false; uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset; // We might need to skip some relocs that we didn't consider. For // example the high_pc of a discarded DIE might contain a reloc that // is in the list because it actually corresponds to the start of a // function that is in the debug map. while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1) RelocOffset = ValidRelocs[++NextValidReloc].Offset; if (RelocOffset < StartOffset || RelocOffset >= EndOffset) return false; const auto &ValidReloc = ValidRelocs[NextValidReloc++]; const auto &Mapping = ValidReloc.Mapping->getValue(); if (Options.Verbose) outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey() << " " << format("\t%016" PRIx64 " => %016" PRIx64, uint64_t(Mapping.ObjectAddress), uint64_t(Mapping.BinaryAddress)); Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend - Mapping.ObjectAddress; Info.InDebugMap = true; return true; } /// \brief Get the starting and ending (exclusive) offset for the /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is /// supposed to point to the position of the first attribute described /// by \p Abbrev. /// \return [StartOffset, EndOffset) as a pair. static std::pair<uint32_t, uint32_t> getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx, unsigned Offset, const DWARFUnit &Unit) { DataExtractor Data = Unit.getDebugInfoExtractor(); for (unsigned i = 0; i < Idx; ++i) DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit); uint32_t End = Offset; DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit); return std::make_pair(Offset, End); } /// \brief Check if a variable describing DIE should be kept. /// \returns updated TraversalFlags. unsigned DwarfLinker::shouldKeepVariableDIE( const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) { const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); // Global variables with constant value can always be kept. if (!(Flags & TF_InFunctionScope) && Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) { MyInfo.InDebugMap = true; return Flags | TF_Keep; } uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location); if (LocationIdx == -1U) return Flags; uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode()); const DWARFUnit &OrigUnit = Unit.getOrigUnit(); uint32_t LocationOffset, LocationEndOffset; std::tie(LocationOffset, LocationEndOffset) = getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit); // See if there is a relocation to a valid debug map entry inside // this variable's location. The order is important here. We want to // always check in the variable has a valid relocation, so that the // DIEInfo is filled. However, we don't want a static variable in a // function to force us to keep the enclosing function. if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) || (Flags & TF_InFunctionScope)) return Flags; if (Options.Verbose) DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */); return Flags | TF_Keep; } /// \brief Check if a function describing DIE should be kept. /// \returns updated TraversalFlags. unsigned DwarfLinker::shouldKeepSubprogramDIE( const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) { const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); Flags |= TF_InFunctionScope; uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc); if (LowPcIdx == -1U) return Flags; uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode()); const DWARFUnit &OrigUnit = Unit.getOrigUnit(); uint32_t LowPcOffset, LowPcEndOffset; std::tie(LowPcOffset, LowPcEndOffset) = getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit); uint64_t LowPc = DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL); assert(LowPc != -1ULL && "low_pc attribute is not an address."); if (LowPc == -1ULL || !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo)) return Flags; if (Options.Verbose) DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */); Flags |= TF_Keep; DWARFFormValue HighPcValue; if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) { reportWarning("Function without high_pc. Range will be discarded.\n", &OrigUnit, &DIE); return Flags; } uint64_t HighPc; if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) { HighPc = *HighPcValue.getAsAddress(&OrigUnit); } else { assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant)); HighPc = LowPc + *HighPcValue.getAsUnsignedConstant(); } // Replace the debug map range with a more accurate one. Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust); Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust); return Flags; } /// \brief Check if a DIE should be kept. /// \returns updated TraversalFlags. unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) { switch (DIE.getTag()) { case dwarf::DW_TAG_constant: case dwarf::DW_TAG_variable: return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags); case dwarf::DW_TAG_subprogram: return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags); case dwarf::DW_TAG_module: case dwarf::DW_TAG_imported_module: case dwarf::DW_TAG_imported_declaration: case dwarf::DW_TAG_imported_unit: // We always want to keep these. return Flags | TF_Keep; } return Flags; } /// \brief Mark the passed DIE as well as all the ones it depends on /// as kept. /// /// This function is called by lookForDIEsToKeep on DIEs that are /// newly discovered to be needed in the link. It recursively calls /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the /// TraversalFlags to inform it that it's not doing the primary DIE /// tree walk. void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE, CompileUnit::DIEInfo &MyInfo, const DebugMapObject &DMO, CompileUnit &CU, unsigned Flags) { const DWARFUnit &Unit = CU.getOrigUnit(); MyInfo.Keep = true; // First mark all the parent chain as kept. unsigned AncestorIdx = MyInfo.ParentIdx; while (!CU.getInfo(AncestorIdx).Keep) { lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU, TF_ParentWalk | TF_Keep | TF_DependencyWalk); AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx; } // Then we need to mark all the DIEs referenced by this DIE's // attributes as kept. DataExtractor Data = Unit.getDebugInfoExtractor(); const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode()); // Mark all DIEs referenced through atttributes as kept. for (const auto &AttrSpec : Abbrev->attributes()) { DWARFFormValue Val(AttrSpec.Form); if (!Val.isFormClass(DWARFFormValue::FC_Reference)) { DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit); continue; } Val.extractValue(Data, &Offset, &Unit); CompileUnit *ReferencedCU; if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU)) lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU, TF_Keep | TF_DependencyWalk); } } /// \brief Recursively walk the \p DIE tree and look for DIEs to /// keep. Store that information in \p CU's DIEInfo. /// /// This function is the entry point of the DIE selection /// algorithm. It is expected to walk the DIE tree in file order and /// (though the mediation of its helper) call hasValidRelocation() on /// each DIE that might be a 'root DIE' (See DwarfLinker class /// comment). /// While walking the dependencies of root DIEs, this function is /// also called, but during these dependency walks the file order is /// not respected. The TF_DependencyWalk flag tells us which kind of /// traversal we are currently doing. void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE, const DebugMapObject &DMO, CompileUnit &CU, unsigned Flags) { unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE); CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx); bool AlreadyKept = MyInfo.Keep; // If the Keep flag is set, we are marking a required DIE's // dependencies. If our target is already marked as kept, we're all // set. if ((Flags & TF_DependencyWalk) && AlreadyKept) return; // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies, // because it would screw up the relocation finding logic. if (!(Flags & TF_DependencyWalk)) Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags); // If it is a newly kept DIE mark it as well as all its dependencies as kept. if (!AlreadyKept && (Flags & TF_Keep)) keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags); // The TF_ParentWalk flag tells us that we are currently walking up // the parent chain of a required DIE, and we don't want to mark all // the children of the parents as kept (consider for example a // DW_TAG_namespace node in the parent chain). There are however a // set of DIE types for which we want to ignore that directive and still // walk their children. if (dieNeedsChildrenToBeMeaningful(DIE.getTag())) Flags &= ~TF_ParentWalk; if (!DIE.hasChildren() || (Flags & TF_ParentWalk)) return; for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL(); Child = Child->getSibling()) lookForDIEsToKeep(*Child, DMO, CU, Flags); } /// \brief Assign an abbreviation numer to \p Abbrev. /// /// Our DIEs get freed after every DebugMapObject has been processed, /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to /// the instances hold by the DIEs. When we encounter an abbreviation /// that we don't know, we create a permanent copy of it. void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) { // Check the set for priors. FoldingSetNodeID ID; Abbrev.Profile(ID); void *InsertToken; DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken); // If it's newly added. if (InSet) { // Assign existing abbreviation number. Abbrev.setNumber(InSet->getNumber()); } else { // Add to abbreviation list. Abbreviations.push_back( new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren())); for (const auto &Attr : Abbrev.getData()) Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm()); AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken); // Assign the unique abbreviation number. Abbrev.setNumber(Abbreviations.size()); Abbreviations.back()->setNumber(Abbreviations.size()); } } /// \brief Clone a string attribute described by \p AttrSpec and add /// it to \p Die. /// \returns the size of the new attribute. unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, const DWARFUnit &U) { // Switch everything to out of line strings. const char *String = *Val.getAsCString(&U); unsigned Offset = StringPool.getStringOffset(String); Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp, DIEInteger(Offset)); return 4; } /// \brief Clone an attribute referencing another DIE and add /// it to \p Die. /// \returns the size of the new attribute. unsigned DwarfLinker::cloneDieReferenceAttribute( DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val, CompileUnit &Unit) { uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit()); DIE *NewRefDie = nullptr; CompileUnit *RefUnit = nullptr; const DWARFDebugInfoEntryMinimal *RefDie = nullptr; if (!(RefUnit = getUnitForOffset(Ref)) || !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) { const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr); if (!AttributeString) AttributeString = "DW_AT_???"; reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString + ". Dropping.", &Unit.getOrigUnit(), &InputDIE); return 0; } unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie); CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx); if (!RefInfo.Clone) { assert(Ref > InputDIE.getOffset()); // We haven't cloned this DIE yet. Just create an empty one and // store it. It'll get really cloned when we process it. RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag())); } NewRefDie = RefInfo.Clone; if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) { // We cannot currently rely on a DIEEntry to emit ref_addr // references, because the implementation calls back to DwarfDebug // to find the unit offset. (We don't have a DwarfDebug) // FIXME: we should be able to design DIEEntry reliance on // DwarfDebug away. uint64_t Attr; if (Ref < InputDIE.getOffset()) { // We must have already cloned that DIE. uint32_t NewRefOffset = RefUnit->getStartOffset() + NewRefDie->getOffset(); Attr = NewRefOffset; Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr, DIEInteger(Attr)); } else { // A forward reference. Note and fixup later. Attr = 0xBADDEF; Unit.noteForwardReference( NewRefDie, RefUnit, Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr, DIEInteger(Attr))); } return AttrSize; } Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie)); return AttrSize; } /// \brief Clone an attribute of block form (locations, constants) and add /// it to \p Die. /// \returns the size of the new attribute. unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) { DIE *Attr; DIEValue Value; DIELoc *Loc = nullptr; DIEBlock *Block = nullptr; // Just copy the block data over. if (AttrSpec.Form == dwarf::DW_FORM_exprloc) { Loc = new (DIEAlloc) DIELoc; DIELocs.push_back(Loc); } else { Block = new (DIEAlloc) DIEBlock; DIEBlocks.push_back(Block); } Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block); if (Loc) Value = DIEValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form), Loc); else Value = DIEValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form), Block); ArrayRef<uint8_t> Bytes = *Val.getAsBlock(); for (auto Byte : Bytes) Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1, DIEInteger(Byte)); // FIXME: If DIEBlock and DIELoc just reuses the Size field of // the DIE class, this if could be replaced by // Attr->setSize(Bytes.size()). if (Streamer) { if (Loc) Loc->ComputeSize(&Streamer->getAsmPrinter()); else Block->ComputeSize(&Streamer->getAsmPrinter()); } Die.addValue(DIEAlloc, Value); return AttrSize; } /// \brief Clone an address attribute and add it to \p Die. /// \returns the size of the new attribute. unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val, const CompileUnit &Unit, AttributesInfo &Info) { uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit()); if (AttrSpec.Attr == dwarf::DW_AT_low_pc) { if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine || Die.getTag() == dwarf::DW_TAG_lexical_block) Addr += Info.PCOffset; else if (Die.getTag() == dwarf::DW_TAG_compile_unit) { Addr = Unit.getLowPc(); if (Addr == UINT64_MAX) return 0; } Info.HasLowPc = true; } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) { if (Die.getTag() == dwarf::DW_TAG_compile_unit) { if (uint64_t HighPc = Unit.getHighPc()) Addr = HighPc; else return 0; } else // If we have a high_pc recorded for the input DIE, use // it. Otherwise (when no relocations where applied) just use the // one we just decoded. Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset; } Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr), static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr)); return Unit.getOrigUnit().getAddressByteSize(); } /// \brief Clone a scalar attribute and add it to \p Die. /// \returns the size of the new attribute. unsigned DwarfLinker::cloneScalarAttribute( DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize, AttributesInfo &Info) { uint64_t Value; if (AttrSpec.Attr == dwarf::DW_AT_high_pc && Die.getTag() == dwarf::DW_TAG_compile_unit) { if (Unit.getLowPc() == -1ULL) return 0; // Dwarf >= 4 high_pc is an size, not an address. Value = Unit.getHighPc() - Unit.getLowPc(); } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset) Value = *Val.getAsSectionOffset(); else if (AttrSpec.Form == dwarf::DW_FORM_sdata) Value = *Val.getAsSignedConstant(); else if (auto OptionalValue = Val.getAsUnsignedConstant()) Value = *OptionalValue; else { reportWarning("Unsupported scalar attribute form. Dropping attribute.", &Unit.getOrigUnit(), &InputDIE); return 0; } PatchLocation Patch = Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form), DIEInteger(Value)); if (AttrSpec.Attr == dwarf::DW_AT_ranges) Unit.noteRangeAttribute(Die, Patch); // A more generic way to check for location attributes would be // nice, but it's very unlikely that any other attribute needs a // location list. else if (AttrSpec.Attr == dwarf::DW_AT_location || AttrSpec.Attr == dwarf::DW_AT_frame_base) Unit.noteLocationAttribute(Patch, Info.PCOffset); else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value) Info.IsDeclaration = true; return AttrSize; } /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with /// value \p Val, and add it to \p Die. /// \returns the size of the cloned attribute. unsigned DwarfLinker::cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit, const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info) { const DWARFUnit &U = Unit.getOrigUnit(); switch (AttrSpec.Form) { case dwarf::DW_FORM_strp: case dwarf::DW_FORM_string: return cloneStringAttribute(Die, AttrSpec, Val, U); case dwarf::DW_FORM_ref_addr: case dwarf::DW_FORM_ref1: case dwarf::DW_FORM_ref2: case dwarf::DW_FORM_ref4: case dwarf::DW_FORM_ref8: return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, Unit); case dwarf::DW_FORM_block: case dwarf::DW_FORM_block1: case dwarf::DW_FORM_block2: case dwarf::DW_FORM_block4: case dwarf::DW_FORM_exprloc: return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize); case dwarf::DW_FORM_addr: return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info); case dwarf::DW_FORM_data1: case dwarf::DW_FORM_data2: case dwarf::DW_FORM_data4: case dwarf::DW_FORM_data8: case dwarf::DW_FORM_udata: case dwarf::DW_FORM_sdata: case dwarf::DW_FORM_sec_offset: case dwarf::DW_FORM_flag: case dwarf::DW_FORM_flag_present: return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize, Info); default: reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U, &InputDIE); } return 0; } /// \brief Apply the valid relocations found by findValidRelocs() to /// the buffer \p Data, taking into account that Data is at \p BaseOffset /// in the debug_info section. /// /// Like for findValidRelocs(), this function must be called with /// monotonic \p BaseOffset values. /// /// \returns wether any reloc has been applied. bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset, bool isLittleEndian) { assert((NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) && "BaseOffset should only be increasing."); if (NextValidReloc >= ValidRelocs.size()) return false; // Skip relocs that haven't been applied. while (NextValidReloc < ValidRelocs.size() && ValidRelocs[NextValidReloc].Offset < BaseOffset) ++NextValidReloc; bool Applied = false; uint64_t EndOffset = BaseOffset + Data.size(); while (NextValidReloc < ValidRelocs.size() && ValidRelocs[NextValidReloc].Offset >= BaseOffset && ValidRelocs[NextValidReloc].Offset < EndOffset) { const auto &ValidReloc = ValidRelocs[NextValidReloc++]; assert(ValidReloc.Offset - BaseOffset < Data.size()); assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size()); char Buf[8]; uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress; Value += ValidReloc.Addend; for (unsigned i = 0; i != ValidReloc.Size; ++i) { unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1); Buf[i] = uint8_t(Value >> (Index * 8)); } assert(ValidReloc.Size <= sizeof(Buf)); memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size); Applied = true; } return Applied; } static bool isTypeTag(uint16_t Tag) { switch (Tag) { case dwarf::DW_TAG_array_type: case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_enumeration_type: case dwarf::DW_TAG_pointer_type: case dwarf::DW_TAG_reference_type: case dwarf::DW_TAG_string_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_subroutine_type: case dwarf::DW_TAG_typedef: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_ptr_to_member_type: case dwarf::DW_TAG_set_type: case dwarf::DW_TAG_subrange_type: case dwarf::DW_TAG_base_type: case dwarf::DW_TAG_const_type: case dwarf::DW_TAG_constant: case dwarf::DW_TAG_file_type: case dwarf::DW_TAG_namelist: case dwarf::DW_TAG_packed_type: case dwarf::DW_TAG_volatile_type: case dwarf::DW_TAG_restrict_type: case dwarf::DW_TAG_interface_type: case dwarf::DW_TAG_unspecified_type: case dwarf::DW_TAG_shared_type: return true; default: break; } return false; } /// \brief Recursively clone \p InputDIE's subtrees that have been /// selected to appear in the linked output. /// /// \param OutOffset is the Offset where the newly created DIE will /// lie in the linked compile unit. /// /// \returns the cloned DIE object or null if nothing was selected. DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit, int64_t PCOffset, uint32_t OutOffset) { DWARFUnit &U = Unit.getOrigUnit(); unsigned Idx = U.getDIEIndex(&InputDIE); CompileUnit::DIEInfo &Info = Unit.getInfo(Idx); // Should the DIE appear in the output? if (!Unit.getInfo(Idx).Keep) return nullptr; uint32_t Offset = InputDIE.getOffset(); // The DIE might have been already created by a forward reference // (see cloneDieReferenceAttribute()). DIE *Die = Info.Clone; if (!Die) Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag())); assert(Die->getTag() == InputDIE.getTag()); Die->setOffset(OutOffset); // Extract and clone every attribute. DataExtractor Data = U.getDebugInfoExtractor(); uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset(); AttributesInfo AttrInfo; // We could copy the data only if we need to aply a relocation to // it. After testing, it seems there is no performance downside to // doing the copy unconditionally, and it makes the code simpler. SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset)); Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize()); // Modify the copy with relocated addresses. if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) { // If we applied relocations, we store the value of high_pc that was // potentially stored in the input DIE. If high_pc is an address // (Dwarf version == 2), then it might have been relocated to a // totally unrelated value (because the end address in the object // file might be start address of another function which got moved // independantly by the linker). The computation of the actual // high_pc value is done in cloneAddressAttribute(). AttrInfo.OrigHighPc = InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0); } // Reset the Offset to 0 as we will be working on the local copy of // the data. Offset = 0; const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr(); Offset += getULEB128Size(Abbrev->getCode()); // We are entering a subprogram. Get and propagate the PCOffset. if (Die->getTag() == dwarf::DW_TAG_subprogram) PCOffset = Info.AddrAdjust; AttrInfo.PCOffset = PCOffset; for (const auto &AttrSpec : Abbrev->attributes()) { DWARFFormValue Val(AttrSpec.Form); uint32_t AttrSize = Offset; Val.extractValue(Data, &Offset, &U); AttrSize = Offset - AttrSize; OutOffset += cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo); } // Look for accelerator entries. uint16_t Tag = InputDIE.getTag(); // FIXME: This is slightly wrong. An inline_subroutine without a // low_pc, but with AT_ranges might be interesting to get into the // accelerator tables too. For now stick with dsymutil's behavior. if ((Info.InDebugMap || AttrInfo.HasLowPc) && Tag != dwarf::DW_TAG_compile_unit && getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) { if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name) Unit.addNameAccelerator(Die, AttrInfo.MangledName, AttrInfo.MangledNameOffset, Tag == dwarf::DW_TAG_inlined_subroutine); if (AttrInfo.Name) Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset, Tag == dwarf::DW_TAG_inlined_subroutine); } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration && getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) { Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset); } DIEAbbrev NewAbbrev = Die->generateAbbrev(); // If a scope DIE is kept, we must have kept at least one child. If // it's not the case, we'll just be emitting one wasteful end of // children marker, but things won't break. if (InputDIE.hasChildren()) NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes); // Assign a permanent abbrev number AssignAbbrev(NewAbbrev); Die->setAbbrevNumber(NewAbbrev.getNumber()); // Add the size of the abbreviation number to the output offset. OutOffset += getULEB128Size(Die->getAbbrevNumber()); if (!Abbrev->hasChildren()) { // Update our size. Die->setSize(OutOffset - Die->getOffset()); return Die; } // Recursively clone children. for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL(); Child = Child->getSibling()) { if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) { Die->addChild(Clone); OutOffset = Clone->getOffset() + Clone->getSize(); } } // Account for the end of children marker. OutOffset += sizeof(int8_t); // Update our size. Die->setSize(OutOffset - Die->getOffset()); return Die; } /// \brief Patch the input object file relevant debug_ranges entries /// and emit them in the output file. Update the relevant attributes /// to point at the new entries. void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit, DWARFContext &OrigDwarf) const { DWARFDebugRangeList RangeList; const auto &FunctionRanges = Unit.getFunctionRanges(); unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); DataExtractor RangeExtractor(OrigDwarf.getRangeSection(), OrigDwarf.isLittleEndian(), AddressSize); auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange; DWARFUnit &OrigUnit = Unit.getOrigUnit(); const auto *OrigUnitDie = OrigUnit.getUnitDIE(false); uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress( &OrigUnit, dwarf::DW_AT_low_pc, -1ULL); // Ranges addresses are based on the unit's low_pc. Compute the // offset we need to apply to adapt to the the new unit's low_pc. int64_t UnitPcOffset = 0; if (OrigLowPc != -1ULL) UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc(); for (const auto &RangeAttribute : Unit.getRangesAttributes()) { uint32_t Offset = RangeAttribute.get(); RangeAttribute.set(Streamer->getRangesSectionSize()); RangeList.extract(RangeExtractor, &Offset); const auto &Entries = RangeList.getEntries(); const DWARFDebugRangeList::RangeListEntry &First = Entries.front(); if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() || First.StartAddress >= CurrRange.stop()) { CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc); if (CurrRange == InvalidRange || CurrRange.start() > First.StartAddress + OrigLowPc) { reportWarning("no mapping for range."); continue; } } Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries, AddressSize); } } /// \brief Generate the debug_aranges entries for \p Unit and if the /// unit has a DW_AT_ranges attribute, also emit the debug_ranges /// contribution for this attribute. /// FIXME: this could actually be done right in patchRangesForUnit, /// but for the sake of initial bit-for-bit compatibility with legacy /// dsymutil, we have to do it in a delayed pass. void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const { auto Attr = Unit.getUnitRangesAttribute(); if (Attr) Attr->set(Streamer->getRangesSectionSize()); Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr)); } /// \brief Insert the new line info sequence \p Seq into the current /// set of already linked line info \p Rows. static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq, std::vector<DWARFDebugLine::Row> &Rows) { if (Seq.empty()) return; if (!Rows.empty() && Rows.back().Address < Seq.front().Address) { Rows.insert(Rows.end(), Seq.begin(), Seq.end()); Seq.clear(); return; } auto InsertPoint = std::lower_bound( Rows.begin(), Rows.end(), Seq.front(), [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) { return LHS.Address < RHS.Address; }); // FIXME: this only removes the unneeded end_sequence if the // sequences have been inserted in order. using a global sort like // described in patchLineTableForUnit() and delaying the end_sequene // elimination to emitLineTableForUnit() we can get rid of all of them. if (InsertPoint != Rows.end() && InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) { *InsertPoint = Seq.front(); Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end()); } else { Rows.insert(InsertPoint, Seq.begin(), Seq.end()); } Seq.clear(); } static void patchStmtList(DIE &Die, DIEInteger Offset) { for (auto &V : Die.values()) if (V.getAttribute() == dwarf::DW_AT_stmt_list) { V = DIEValue(V.getAttribute(), V.getForm(), Offset); return; } llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!"); } /// \brief Extract the line table for \p Unit from \p OrigDwarf, and /// recreate a relocated version of these for the address ranges that /// are present in the binary. void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf) { const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE(); uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset( &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL); if (StmtList == -1ULL) return; // Update the cloned DW_AT_stmt_list with the correct debug_line offset. if (auto *OutputDIE = Unit.getOutputUnitDIE()) patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize())); // Parse the original line info for the unit. DWARFDebugLine::LineTable LineTable; uint32_t StmtOffset = StmtList; StringRef LineData = OrigDwarf.getLineSection().Data; DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize()); LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs, &StmtOffset); // This vector is the output line table. std::vector<DWARFDebugLine::Row> NewRows; NewRows.reserve(LineTable.Rows.size()); // Current sequence of rows being extracted, before being inserted // in NewRows. std::vector<DWARFDebugLine::Row> Seq; const auto &FunctionRanges = Unit.getFunctionRanges(); auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange; // FIXME: This logic is meant to generate exactly the same output as // Darwin's classic dsynutil. There is a nicer way to implement this // by simply putting all the relocated line info in NewRows and simply // sorting NewRows before passing it to emitLineTableForUnit. This // should be correct as sequences for a function should stay // together in the sorted output. There are a few corner cases that // look suspicious though, and that required to implement the logic // this way. Revisit that once initial validation is finished. // Iterate over the object file line info and extract the sequences // that correspond to linked functions. for (auto &Row : LineTable.Rows) { // Check wether we stepped out of the range. The range is // half-open, but consider accept the end address of the range if // it is marked as end_sequence in the input (because in that // case, the relocation offset is accurate and that entry won't // serve as the start of another function). if (CurrRange == InvalidRange || Row.Address < CurrRange.start() || Row.Address > CurrRange.stop() || (Row.Address == CurrRange.stop() && !Row.EndSequence)) { // We just stepped out of a known range. Insert a end_sequence // corresponding to the end of the range. uint64_t StopAddress = CurrRange != InvalidRange ? CurrRange.stop() + CurrRange.value() : -1ULL; CurrRange = FunctionRanges.find(Row.Address); bool CurrRangeValid = CurrRange != InvalidRange && CurrRange.start() <= Row.Address; if (!CurrRangeValid) { CurrRange = InvalidRange; if (StopAddress != -1ULL) { // Try harder by looking in the DebugMapObject function // ranges map. There are corner cases where this finds a // valid entry. It's unclear if this is right or wrong, but // for now do as dsymutil. // FIXME: Understand exactly what cases this addresses and // potentially remove it along with the Ranges map. auto Range = Ranges.lower_bound(Row.Address); if (Range != Ranges.begin() && Range != Ranges.end()) --Range; if (Range != Ranges.end() && Range->first <= Row.Address && Range->second.first >= Row.Address) { StopAddress = Row.Address + Range->second.second; } } } if (StopAddress != -1ULL && !Seq.empty()) { // Insert end sequence row with the computed end address, but // the same line as the previous one. Seq.emplace_back(Seq.back()); Seq.back().Address = StopAddress; Seq.back().EndSequence = 1; Seq.back().PrologueEnd = 0; Seq.back().BasicBlock = 0; Seq.back().EpilogueBegin = 0; insertLineSequence(Seq, NewRows); } if (!CurrRangeValid) continue; } // Ignore empty sequences. if (Row.EndSequence && Seq.empty()) continue; // Relocate row address and add it to the current sequence. Row.Address += CurrRange.value(); Seq.emplace_back(Row); if (Row.EndSequence) insertLineSequence(Seq, NewRows); } // Finished extracting, now emit the line tables. uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength; // FIXME: LLVM hardcodes it's prologue values. We just copy the // prologue over and that works because we act as both producer and // consumer. It would be nicer to have a real configurable line // table emitter. if (LineTable.Prologue.Version != 2 || LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT || LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 || LineTable.Prologue.OpcodeBase != 13) reportWarning("line table paramters mismatch. Cannot emit."); else Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd), LineTable.Prologue.MinInstLength, NewRows, Unit.getOrigUnit().getAddressByteSize()); } void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) { Streamer->emitPubNamesForUnit(Unit); Streamer->emitPubTypesForUnit(Unit); } /// \brief Read the frame info stored in the object, and emit the /// patched frame descriptions for the linked binary. /// /// This is actually pretty easy as the data of the CIEs and FDEs can /// be considered as black boxes and moved as is. The only thing to do /// is to patch the addresses in the headers. void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO, DWARFContext &OrigDwarf, unsigned AddrSize) { StringRef FrameData = OrigDwarf.getDebugFrameSection(); if (FrameData.empty()) return; DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0); uint32_t InputOffset = 0; // Store the data of the CIEs defined in this object, keyed by their // offsets. DenseMap<uint32_t, StringRef> LocalCIES; while (Data.isValidOffset(InputOffset)) { uint32_t EntryOffset = InputOffset; uint32_t InitialLength = Data.getU32(&InputOffset); if (InitialLength == 0xFFFFFFFF) return reportWarning("Dwarf64 bits no supported"); uint32_t CIEId = Data.getU32(&InputOffset); if (CIEId == 0xFFFFFFFF) { // This is a CIE, store it. StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4); LocalCIES[EntryOffset] = CIEData; // The -4 is to account for the CIEId we just read. InputOffset += InitialLength - 4; continue; } uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize); // Some compilers seem to emit frame info that doesn't start at // the function entry point, thus we can't just lookup the address // in the debug map. Use the linker's range map to see if the FDE // describes something that we can relocate. auto Range = Ranges.upper_bound(Loc); if (Range != Ranges.begin()) --Range; if (Range == Ranges.end() || Range->first > Loc || Range->second.first <= Loc) { // The +4 is to account for the size of the InitialLength field itself. InputOffset = EntryOffset + InitialLength + 4; continue; } // This is an FDE, and we have a mapping. // Have we already emitted a corresponding CIE? StringRef CIEData = LocalCIES[CIEId]; if (CIEData.empty()) return reportWarning("Inconsistent debug_frame content. Dropping."); // Look if we already emitted a CIE that corresponds to the // referenced one (the CIE data is the key of that lookup). auto IteratorInserted = EmittedCIEs.insert( std::make_pair(CIEData, Streamer->getFrameSectionSize())); // If there is no CIE yet for this ID, emit it. if (IteratorInserted.second || // FIXME: dsymutil-classic only caches the last used CIE for // reuse. Mimic that behavior for now. Just removing that // second half of the condition and the LastCIEOffset variable // makes the code DTRT. LastCIEOffset != IteratorInserted.first->getValue()) { LastCIEOffset = Streamer->getFrameSectionSize(); IteratorInserted.first->getValue() = LastCIEOffset; Streamer->emitCIE(CIEData); } // Emit the FDE with updated address and CIE pointer. // (4 + AddrSize) is the size of the CIEId + initial_location // fields that will get reconstructed by emitFDE(). unsigned FDERemainingBytes = InitialLength - (4 + AddrSize); Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize, Loc + Range->second.second, FrameData.substr(InputOffset, FDERemainingBytes)); InputOffset += FDERemainingBytes; } } bool DwarfLinker::link(const DebugMap &Map) { if (Map.begin() == Map.end()) { errs() << "Empty debug map.\n"; return false; } if (!createStreamer(Map.getTriple(), OutputFilename)) return false; // Size of the DIEs (and headers) generated for the linked output. uint64_t OutputDebugInfoSize = 0; // A unique ID that identifies each compile unit. unsigned UnitID = 0; for (const auto &Obj : Map.objects()) { CurrentDebugObject = Obj.get(); if (Options.Verbose) outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n"; auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename()); if (std::error_code EC = ErrOrObj.getError()) { reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message()); continue; } // Look for relocations that correspond to debug map entries. if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) { if (Options.Verbose) outs() << "No valid relocations found. Skipping.\n"; continue; } // Setup access to the debug info. DWARFContextInMemory DwarfContext(*ErrOrObj); startDebugObject(DwarfContext, *Obj); // In a first phase, just read in the debug info and store the DIE // parent links that we will use during the next phase. for (const auto &CU : DwarfContext.compile_units()) { auto *CUDie = CU->getUnitDIE(false); if (Options.Verbose) { outs() << "Input compilation unit:"; CUDie->dump(outs(), CU.get(), 0); } Units.emplace_back(*CU, UnitID++); gatherDIEParents(CUDie, 0, Units.back()); } // Then mark all the DIEs that need to be present in the linked // output and collect some information about them. Note that this // loop can not be merged with the previous one becaue cross-cu // references require the ParentIdx to be setup for every CU in // the object file before calling this. for (auto &CurrentUnit : Units) lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj, CurrentUnit, 0); // The calls to applyValidRelocs inside cloneDIE will walk the // reloc array again (in the same way findValidRelocsInDebugInfo() // did). We need to reset the NextValidReloc index to the beginning. NextValidReloc = 0; // Construct the output DIE tree by cloning the DIEs we chose to // keep above. If there are no valid relocs, then there's nothing // to clone/emit. if (!ValidRelocs.empty()) for (auto &CurrentUnit : Units) { const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE(); CurrentUnit.setStartOffset(OutputDebugInfoSize); DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */, 11 /* Unit Header size */); CurrentUnit.setOutputUnitDIE(OutputDIE); OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset(); if (Options.NoOutput) continue; // FIXME: for compatibility with the classic dsymutil, we emit // an empty line table for the unit, even if the unit doesn't // actually exist in the DIE tree. patchLineTableForUnit(CurrentUnit, DwarfContext); if (!OutputDIE) continue; patchRangesForUnit(CurrentUnit, DwarfContext); Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext); emitAcceleratorEntriesForUnit(CurrentUnit); } // Emit all the compile unit's debug information. if (!ValidRelocs.empty() && !Options.NoOutput) for (auto &CurrentUnit : Units) { generateUnitRanges(CurrentUnit); CurrentUnit.fixupForwardReferences(); Streamer->emitCompileUnitHeader(CurrentUnit); if (!CurrentUnit.getOutputUnitDIE()) continue; Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE()); } if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty()) patchFrameInfoForObject(*Obj, DwarfContext, Units[0].getOrigUnit().getAddressByteSize()); // Clean-up before starting working on the next object. endDebugObject(); } // Emit everything that's global. if (!Options.NoOutput) { Streamer->emitAbbrevs(Abbreviations); Streamer->emitStrings(StringPool); } return Options.NoOutput ? true : Streamer->finish(); } } bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, const LinkOptions &Options) { DwarfLinker Linker(OutputFilename, Options); return Linker.link(DM); } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/MachODebugMapParser.cpp
//===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "DebugMap.h" #include "dsymutil.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" namespace { using namespace llvm; using namespace llvm::dsymutil; using namespace llvm::object; class MachODebugMapParser { public: MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "", bool Verbose = false) : BinaryPath(BinaryPath), PathPrefix(PathPrefix), MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose), CurrentDebugMapObject(nullptr) {} /// \brief Parses and returns the DebugMap of the input binary. /// \returns an error in case the provided BinaryPath doesn't exist /// or isn't of a supported type. ErrorOr<std::unique_ptr<DebugMap>> parse(); private: std::string BinaryPath; std::string PathPrefix; /// Owns the MemoryBuffer for the main binary. BinaryHolder MainBinaryHolder; /// Map of the binary symbol addresses. StringMap<uint64_t> MainBinarySymbolAddresses; StringRef MainBinaryStrings; /// The constructed DebugMap. std::unique_ptr<DebugMap> Result; /// Owns the MemoryBuffer for the currently handled object file. BinaryHolder CurrentObjectHolder; /// Map of the currently processed object file symbol addresses. StringMap<uint64_t> CurrentObjectAddresses; /// Element of the debug map corresponfing to the current object file. DebugMapObject *CurrentDebugMapObject; /// Holds function info while function scope processing. const char *CurrentFunctionName; uint64_t CurrentFunctionAddress; void switchToNewDebugMapObject(StringRef Filename); void resetParserState(); uint64_t getMainBinarySymbolAddress(StringRef Name); void loadMainBinarySymbols(); void loadCurrentObjectFileSymbols(); void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value); template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) { handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, STE.n_value); } }; static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; } } /// Reset the parser state coresponding to the current object /// file. This is to be called after an object file is finished /// processing. void MachODebugMapParser::resetParserState() { CurrentObjectAddresses.clear(); CurrentDebugMapObject = nullptr; } /// Create a new DebugMapObject. This function resets the state of the /// parser that was referring to the last object file and sets /// everything up to add symbols to the new one. void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) { resetParserState(); SmallString<80> Path(PathPrefix); sys::path::append(Path, Filename); auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path); if (auto Error = MachOOrError.getError()) { Warning(Twine("cannot open debug object \"") + Path.str() + "\": " + Error.message() + "\n"); return; } loadCurrentObjectFileSymbols(); CurrentDebugMapObject = &Result->addDebugMapObject(Path); } static Triple getTriple(const object::MachOObjectFile &Obj) { Triple TheTriple("unknown-unknown-unknown"); TheTriple.setArch(Triple::ArchType(Obj.getArch())); TheTriple.setObjectFormat(Triple::MachO); return TheTriple; } /// This main parsing routine tries to open the main binary and if /// successful iterates over the STAB entries. The real parsing is /// done in handleStabSymbolTableEntry. ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() { auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath); if (auto Error = MainBinOrError.getError()) return Error; const MachOObjectFile &MainBinary = *MainBinOrError; loadMainBinarySymbols(); Result = make_unique<DebugMap>(getTriple(MainBinary)); MainBinaryStrings = MainBinary.getStringTableData(); for (const SymbolRef &Symbol : MainBinary.symbols()) { const DataRefImpl &DRI = Symbol.getRawDataRefImpl(); if (MainBinary.is64Bit()) handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI)); else handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI)); } resetParserState(); return std::move(Result); } /// Interpret the STAB entries to fill the DebugMap. void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value) { if (!(Type & MachO::N_STAB)) return; const char *Name = &MainBinaryStrings.data()[StringIndex]; // An N_OSO entry represents the start of a new object file description. if (Type == MachO::N_OSO) return switchToNewDebugMapObject(Name); // If the last N_OSO object file wasn't found, // CurrentDebugMapObject will be null. Do not update anything // until we find the next valid N_OSO entry. if (!CurrentDebugMapObject) return; uint32_t Size = 0; switch (Type) { case MachO::N_GSYM: // This is a global variable. We need to query the main binary // symbol table to find its address as it might not be in the // debug map (for common symbols). Value = getMainBinarySymbolAddress(Name); break; case MachO::N_FUN: // Functions are scopes in STABS. They have an end marker that // contains the function size. if (Name[0] == '\0') { Size = Value; Value = CurrentFunctionAddress; Name = CurrentFunctionName; break; } else { CurrentFunctionName = Name; CurrentFunctionAddress = Value; return; } case MachO::N_STSYM: break; default: return; } auto ObjectSymIt = CurrentObjectAddresses.find(Name); if (ObjectSymIt == CurrentObjectAddresses.end()) return Warning("could not find object file symbol for symbol " + Twine(Name)); if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value, Size)) return Warning(Twine("failed to insert symbol '") + Name + "' in the debug map."); } /// Load the current object file symbols into CurrentObjectAddresses. void MachODebugMapParser::loadCurrentObjectFileSymbols() { CurrentObjectAddresses.clear(); for (auto Sym : CurrentObjectHolder.Get().symbols()) { uint64_t Addr = Sym.getValue(); ErrorOr<StringRef> Name = Sym.getName(); if (!Name) continue; CurrentObjectAddresses[*Name] = Addr; } } /// Lookup a symbol address in the main binary symbol table. The /// parser only needs to query common symbols, thus not every symbol's /// address is available through this function. uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) { auto Sym = MainBinarySymbolAddresses.find(Name); if (Sym == MainBinarySymbolAddresses.end()) return 0; return Sym->second; } /// Load the interesting main binary symbols' addresses into /// MainBinarySymbolAddresses. void MachODebugMapParser::loadMainBinarySymbols() { const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>(); section_iterator Section = MainBinary.section_end(); for (const auto &Sym : MainBinary.symbols()) { SymbolRef::Type Type = Sym.getType(); // Skip undefined and STAB entries. if ((Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown)) continue; // The only symbols of interest are the global variables. These // are the only ones that need to be queried because the address // of common data won't be described in the debug map. All other // addresses should be fetched for the debug map. if (!(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) || Section == MainBinary.section_end() || Section->isText()) continue; uint64_t Addr = Sym.getValue(); ErrorOr<StringRef> NameOrErr = Sym.getName(); if (!NameOrErr) continue; StringRef Name = *NameOrErr; if (Name.size() == 0 || Name[0] == '\0') continue; MainBinarySymbolAddresses[Name] = Addr; } } namespace llvm { namespace dsymutil { llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose, bool InputIsYAML) { if (!InputIsYAML) { MachODebugMapParser Parser(InputFile, PrependPath, Verbose); return Parser.parse(); } else { return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose); } } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/BinaryHolder.h
//===-- BinaryHolder.h - Utility class for accessing binaries -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that aims to be a dropin replacement for // Darwin's dsymutil. // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_DSYMUTIL_BINARYHOLDER_H #define LLVM_TOOLS_DSYMUTIL_BINARYHOLDER_H #include "llvm/Object/Archive.h" #include "llvm/Object/Error.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorOr.h" namespace llvm { namespace dsymutil { /// \brief The BinaryHolder class is responsible for creating and /// owning ObjectFile objects and their underlying MemoryBuffer. This /// is different from a simple OwningBinary in that it handles /// accessing to archive members. /// /// As an optimization, this class will reuse an already mapped and /// parsed Archive object if 2 successive requests target the same /// archive file (Which is always the case in debug maps). /// Currently it only owns one memory buffer at any given time, /// meaning that a mapping request will invalidate the previous memory /// mapping. class BinaryHolder { std::unique_ptr<object::Archive> CurrentArchive; std::unique_ptr<MemoryBuffer> CurrentMemoryBuffer; std::unique_ptr<object::ObjectFile> CurrentObjectFile; bool Verbose; /// \brief Get the MemoryBufferRef for the file specification in \p /// Filename from the current archive. /// /// This function performs no system calls, it just looks up a /// potential match for the given \p Filename in the currently /// mapped archive if there is one. ErrorOr<MemoryBufferRef> GetArchiveMemberBuffer(StringRef Filename); /// \brief Interpret Filename as an archive member specification, /// map the corresponding archive to memory and return the /// MemoryBufferRef corresponding to the described member. ErrorOr<MemoryBufferRef> MapArchiveAndGetMemberBuffer(StringRef Filename); /// \brief Return the MemoryBufferRef that holds the memory /// mapping for the given \p Filename. This function will try to /// parse archive member specifications of the form /// /path/to/archive.a(member.o). /// /// The returned MemoryBufferRef points to a buffer owned by this /// object. The buffer is valid until the next call to /// GetMemoryBufferForFile() on this object. ErrorOr<MemoryBufferRef> GetMemoryBufferForFile(StringRef Filename); public: BinaryHolder(bool Verbose) : Verbose(Verbose) {} /// \brief Get the ObjectFile designated by the \p Filename. This /// might be an archive member specification of the form /// /path/to/archive.a(member.o). /// /// Calling this function invalidates the previous mapping owned by /// the BinaryHolder. ErrorOr<const object::ObjectFile &> GetObjectFile(StringRef Filename); /// \brief Wraps GetObjectFile() to return a derived ObjectFile type. template <typename ObjectFileType> ErrorOr<const ObjectFileType &> GetFileAs(StringRef Filename) { auto ErrOrObjFile = GetObjectFile(Filename); if (auto Err = ErrOrObjFile.getError()) return Err; if (const auto *Derived = dyn_cast<ObjectFileType>(CurrentObjectFile.get())) return *Derived; return make_error_code(object::object_error::invalid_file_type); } /// \brief Access the currently owned ObjectFile. As successfull /// call to GetObjectFile() or GetFileAs() must have been performed /// before calling this. const object::ObjectFile &Get() { assert(CurrentObjectFile); return *CurrentObjectFile; } /// \brief Access to a derived version of the currently owned /// ObjectFile. The conversion must be known to be valid. template <typename ObjectFileType> const ObjectFileType &GetAs() { return cast<ObjectFileType>(*CurrentObjectFile); } }; } } #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/dsymutil/BinaryHolder.cpp
//===-- BinaryHolder.cpp --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that aims to be a dropin replacement for // Darwin's dsymutil. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace dsymutil { ErrorOr<MemoryBufferRef> BinaryHolder::GetMemoryBufferForFile(StringRef Filename) { if (Verbose) outs() << "trying to open '" << Filename << "'\n"; // Try that first as it doesn't involve any filesystem access. if (auto ErrOrArchiveMember = GetArchiveMemberBuffer(Filename)) return *ErrOrArchiveMember; // If the name ends with a closing paren, there is a huge chance // it is an archive member specification. if (Filename.endswith(")")) if (auto ErrOrArchiveMember = MapArchiveAndGetMemberBuffer(Filename)) return *ErrOrArchiveMember; // Otherwise, just try opening a standard file. If this is an // archive member specifiaction and any of the above didn't handle it // (either because the archive is not there anymore, or because the // archive doesn't contain the requested member), this will still // provide a sensible error message. auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(Filename); if (auto Err = ErrOrFile.getError()) return Err; if (Verbose) outs() << "\tloaded file.\n"; CurrentArchive.reset(); CurrentMemoryBuffer = std::move(ErrOrFile.get()); return CurrentMemoryBuffer->getMemBufferRef(); } ErrorOr<MemoryBufferRef> BinaryHolder::GetArchiveMemberBuffer(StringRef Filename) { if (!CurrentArchive) return make_error_code(errc::no_such_file_or_directory); StringRef CurArchiveName = CurrentArchive->getFileName(); if (!Filename.startswith(Twine(CurArchiveName, "(").str())) return make_error_code(errc::no_such_file_or_directory); // Remove the archive name and the parens around the archive member name. Filename = Filename.substr(CurArchiveName.size() + 1).drop_back(); for (const auto &Child : CurrentArchive->children()) { if (auto NameOrErr = Child.getName()) if (*NameOrErr == Filename) { if (Verbose) outs() << "\tfound member in current archive.\n"; return Child.getMemoryBufferRef(); } } return make_error_code(errc::no_such_file_or_directory); } ErrorOr<MemoryBufferRef> BinaryHolder::MapArchiveAndGetMemberBuffer(StringRef Filename) { StringRef ArchiveFilename = Filename.substr(0, Filename.find('(')); auto ErrOrBuff = MemoryBuffer::getFileOrSTDIN(ArchiveFilename); if (auto Err = ErrOrBuff.getError()) return Err; if (Verbose) outs() << "\topened new archive '" << ArchiveFilename << "'\n"; auto ErrOrArchive = object::Archive::create((*ErrOrBuff)->getMemBufferRef()); if (auto Err = ErrOrArchive.getError()) return Err; CurrentArchive = std::move(*ErrOrArchive); CurrentMemoryBuffer = std::move(*ErrOrBuff); return GetArchiveMemberBuffer(Filename); } ErrorOr<const object::ObjectFile &> BinaryHolder::GetObjectFile(StringRef Filename) { auto ErrOrMemBufferRef = GetMemoryBufferForFile(Filename); if (auto Err = ErrOrMemBufferRef.getError()) return Err; auto ErrOrObjectFile = object::ObjectFile::createObjectFile(*ErrOrMemBufferRef); if (auto Err = ErrOrObjectFile.getError()) return Err; CurrentObjectFile = std::move(*ErrOrObjectFile); return *CurrentObjectFile; } } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-lto/llvm-lto.cpp
//===-- llvm-lto: a simple command-line program to link modules with LTO --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes in a list of bitcode files, links them, performs link-time // optimization, and outputs an object file. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringSet.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init('2')); static cl::opt<bool> DisableInline("disable-inlining", cl::init(false), cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false), cl::desc("Do not run the GVN load PRE pass")); static cl::opt<bool> DisableLTOVectorization("disable-lto-vectorization", cl::init(false), cl::desc("Do not run loop or slp vectorization during LTO")); static cl::opt<bool> UseDiagnosticHandler("use-diagnostic-handler", cl::init(false), cl::desc("Use a diagnostic handler to test the handler interface")); static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::init(""), cl::desc("Override output filename"), cl::value_desc("filename")); static cl::list<std::string> ExportedSymbols("exported-symbol", cl::desc("Symbol to export from the resulting object file"), cl::ZeroOrMore); static cl::list<std::string> DSOSymbols("dso-symbol", cl::desc("Symbol to put in the symtab in the resulting dso"), cl::ZeroOrMore); static cl::opt<bool> ListSymbolsOnly( "list-symbols-only", cl::init(false), cl::desc("Instead of running LTO, list the symbols in each IR file")); static cl::opt<bool> SetMergedModule( "set-merged-module", cl::init(false), cl::desc("Use the first input module as the merged module")); namespace { struct ModuleInfo { std::vector<bool> CanBeHidden; }; } static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity, const char *Msg, void *) { switch (Severity) { case LTO_DS_NOTE: errs() << "note: "; break; case LTO_DS_REMARK: errs() << "remark: "; break; case LTO_DS_ERROR: errs() << "error: "; break; case LTO_DS_WARNING: errs() << "warning: "; break; } errs() << Msg << "\n"; } static std::unique_ptr<LTOModule> getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer, const TargetOptions &Options, std::string &Error) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(Path); if (std::error_code EC = BufferOrErr.getError()) { Error = EC.message(); return nullptr; } Buffer = std::move(BufferOrErr.get()); return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext( Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path)); } /// \brief List symbols in each IR file. /// /// The main point here is to provide lit-testable coverage for the LTOModule /// functionality that's exposed by the C API to list symbols. Moreover, this /// provides testing coverage for modules that have been created in their own /// contexts. static int listSymbols(StringRef Command, const TargetOptions &Options) { for (auto &Filename : InputFilenames) { std::string Error; std::unique_ptr<MemoryBuffer> Buffer; std::unique_ptr<LTOModule> Module = getLocalLTOModule(Filename, Buffer, Options, Error); if (!Module) { errs() << Command << ": error loading file '" << Filename << "': " << Error << "\n"; return 1; } // List the symbols. outs() << Filename << ":\n"; for (int I = 0, E = Module->getSymbolCount(); I != E; ++I) outs() << Module->getSymbolName(I) << "\n"; } return 0; } int __cdecl main(int argc, char **argv) { // HLSL Change - __cdecl // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n"); if (OptLevel < '0' || OptLevel > '3') { errs() << argv[0] << ": optimization level must be between 0 and 3\n"; return 1; } // Initialize the configured targets. InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); // set up the TargetOptions for the machine TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); if (ListSymbolsOnly) return listSymbols(argv[0], Options); unsigned BaseArg = 0; LTOCodeGenerator CodeGen; if (UseDiagnosticHandler) CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr); switch (RelocModel) { case Reloc::Static: CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_STATIC); break; case Reloc::PIC_: CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC); break; case Reloc::DynamicNoPIC: CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC); break; default: CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DEFAULT); } CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF); CodeGen.setTargetOptions(Options); llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet; for (unsigned i = 0; i < DSOSymbols.size(); ++i) DSOSymbolsSet.insert(DSOSymbols[i]); std::vector<std::string> KeptDSOSyms; for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) { std::string error; std::unique_ptr<LTOModule> Module( LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error)); if (!error.empty()) { errs() << argv[0] << ": error loading file '" << InputFilenames[i] << "': " << error << "\n"; return 1; } LTOModule *LTOMod = Module.get(); // We use the first input module as the destination module when // SetMergedModule is true. if (SetMergedModule && i == BaseArg) { // Transfer ownership to the code generator. CodeGen.setModule(Module.release()); } else if (!CodeGen.addModule(Module.get())) return 1; unsigned NumSyms = LTOMod->getSymbolCount(); for (unsigned I = 0; I < NumSyms; ++I) { StringRef Name = LTOMod->getSymbolName(I); if (!DSOSymbolsSet.count(Name)) continue; lto_symbol_attributes Attrs = LTOMod->getSymbolAttributes(I); unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK; if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN) KeptDSOSyms.push_back(Name); } } // Add all the exported symbols to the table of symbols to preserve. for (unsigned i = 0; i < ExportedSymbols.size(); ++i) CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str()); // Add all the dso symbols to the table of symbols to expose. for (unsigned i = 0; i < KeptDSOSyms.size(); ++i) CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str()); // Set cpu and attrs strings for the default target/subtarget. CodeGen.setCpu(MCPU.c_str()); CodeGen.setOptLevel(OptLevel - '0'); std::string attrs; for (unsigned i = 0; i < MAttrs.size(); ++i) { if (i > 0) attrs.append(","); attrs.append(MAttrs[i]); } if (!attrs.empty()) CodeGen.setAttr(attrs.c_str()); if (!OutputFilename.empty()) { std::string ErrorInfo; std::unique_ptr<MemoryBuffer> Code = CodeGen.compile( DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, ErrorInfo); if (!Code) { errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n"; return 1; } std::error_code EC; raw_fd_ostream FileStream(OutputFilename, EC, sys::fs::F_None); if (EC) { errs() << argv[0] << ": error opening the file '" << OutputFilename << "': " << EC.message() << "\n"; return 1; } FileStream.write(Code->getBufferStart(), Code->getBufferSize()); } else { std::string ErrorInfo; const char *OutputName = nullptr; if (!CodeGen.compile_to_file(&OutputName, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, ErrorInfo)) { errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n"; return 1; } outs() << "Wrote native object file '" << OutputName << "'\n"; } return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-lto/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} LTO MC Support Target ) add_llvm_tool(llvm-lto llvm-lto.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-lto/LLVMBuild.txt
;===- ./tools/llvm-lto/LLVMBuild.txt ----------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-lto parent = Tools required_libraries = LTO Support all-targets
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/macho-dump/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Object Support ) add_llvm_tool(macho-dump macho-dump.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/macho-dump/LLVMBuild.txt
;===- ./tools/macho-dump/LLVMBuild.txt -------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = macho-dump parent = Tools required_libraries = Object Support
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/macho-dump/macho-dump.cpp
//===-- macho-dump.cpp - Mach Object Dumping Tool -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a testing tool for use with the MC/Mach-O LLVM components. // //===----------------------------------------------------------------------===// #include "llvm/Object/MachO.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <system_error> using namespace llvm; using namespace llvm::object; static cl::opt<std::string> InputFile(cl::Positional, cl::desc("<input file>"), cl::init("-")); static cl::opt<bool> ShowSectionData("dump-section-data", cl::desc("Dump the contents of sections"), cl::init(false)); /// static const char *ProgramName; static void Message(const char *Type, const Twine &Msg) { errs() << ProgramName << ": " << Type << ": " << Msg << "\n"; } static int Error(const Twine &Msg) { Message("error", Msg); return 1; } static void Warning(const Twine &Msg) { Message("warning", Msg); } /// static void DumpSegmentCommandData(StringRef Name, uint64_t VMAddr, uint64_t VMSize, uint64_t FileOffset, uint64_t FileSize, uint32_t MaxProt, uint32_t InitProt, uint32_t NumSections, uint32_t Flags) { outs() << " ('segment_name', '"; outs().write_escaped(Name, /*UseHexEscapes=*/true) << "')\n"; outs() << " ('vm_addr', " << VMAddr << ")\n"; outs() << " ('vm_size', " << VMSize << ")\n"; outs() << " ('file_offset', " << FileOffset << ")\n"; outs() << " ('file_size', " << FileSize << ")\n"; outs() << " ('maxprot', " << MaxProt << ")\n"; outs() << " ('initprot', " << InitProt << ")\n"; outs() << " ('num_sections', " << NumSections << ")\n"; outs() << " ('flags', " << Flags << ")\n"; } static int DumpSectionData(const MachOObjectFile &Obj, unsigned Index, StringRef Name, StringRef SegmentName, uint64_t Address, uint64_t Size, uint32_t Offset, uint32_t Align, uint32_t RelocationTableOffset, uint32_t NumRelocationTableEntries, uint32_t Flags, uint32_t Reserved1, uint32_t Reserved2, uint64_t Reserved3 = ~0ULL) { outs() << " # Section " << Index << "\n"; outs() << " (('section_name', '"; outs().write_escaped(Name, /*UseHexEscapes=*/true) << "')\n"; outs() << " ('segment_name', '"; outs().write_escaped(SegmentName, /*UseHexEscapes=*/true) << "')\n"; outs() << " ('address', " << Address << ")\n"; outs() << " ('size', " << Size << ")\n"; outs() << " ('offset', " << Offset << ")\n"; outs() << " ('alignment', " << Align << ")\n"; outs() << " ('reloc_offset', " << RelocationTableOffset << ")\n"; outs() << " ('num_reloc', " << NumRelocationTableEntries << ")\n"; outs() << " ('flags', " << format("0x%x", Flags) << ")\n"; outs() << " ('reserved1', " << Reserved1 << ")\n"; outs() << " ('reserved2', " << Reserved2 << ")\n"; if (Reserved3 != ~0ULL) outs() << " ('reserved3', " << Reserved3 << ")\n"; outs() << " ),\n"; // Dump the relocation entries. outs() << " ('_relocations', [\n"; unsigned RelNum = 0; for (relocation_iterator I = Obj.section_rel_begin(Index), E = Obj.section_rel_end(Index); I != E; ++I, ++RelNum) { MachO::any_relocation_info RE = Obj.getRelocation(I->getRawDataRefImpl()); outs() << " # Relocation " << RelNum << "\n"; outs() << " (('word-0', " << format("0x%x", RE.r_word0) << "),\n"; outs() << " ('word-1', " << format("0x%x", RE.r_word1) << ")),\n"; } outs() << " ])\n"; // Dump the section data, if requested. if (ShowSectionData) { outs() << " ('_section_data', '"; StringRef Data = Obj.getData().substr(Offset, Size); for (unsigned i = 0; i != Data.size(); ++i) { if (i && (i % 4) == 0) outs() << ' '; outs() << hexdigit((Data[i] >> 4) & 0xF, /*LowerCase=*/true); outs() << hexdigit((Data[i] >> 0) & 0xF, /*LowerCase=*/true); } outs() << "')\n"; } return 0; } static int DumpSegmentCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::segment_command SLC = Obj.getSegmentLoadCommand(LCI); DumpSegmentCommandData(StringRef(SLC.segname, 16), SLC.vmaddr, SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, SLC.initprot, SLC.nsects, SLC.flags); // Dump the sections. outs() << " ('sections', [\n"; for (unsigned i = 0; i != SLC.nsects; ++i) { MachO::section Sect = Obj.getSection(LCI, i); DumpSectionData(Obj, i, StringRef(Sect.sectname, 16), StringRef(Sect.segname, 16), Sect.addr, Sect.size, Sect.offset, Sect.align, Sect.reloff, Sect.nreloc, Sect.flags, Sect.reserved1, Sect.reserved2); } outs() << " ])\n"; return 0; } static int DumpSegment64Command(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::segment_command_64 SLC = Obj.getSegment64LoadCommand(LCI); DumpSegmentCommandData(StringRef(SLC.segname, 16), SLC.vmaddr, SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, SLC.initprot, SLC.nsects, SLC.flags); // Dump the sections. outs() << " ('sections', [\n"; for (unsigned i = 0; i != SLC.nsects; ++i) { MachO::section_64 Sect = Obj.getSection64(LCI, i); DumpSectionData(Obj, i, StringRef(Sect.sectname, 16), StringRef(Sect.segname, 16), Sect.addr, Sect.size, Sect.offset, Sect.align, Sect.reloff, Sect.nreloc, Sect.flags, Sect.reserved1, Sect.reserved2, Sect.reserved3); } outs() << " ])\n"; return 0; } static void DumpSymbolTableEntryData(const MachOObjectFile &Obj, unsigned Index, uint32_t StringIndex, uint8_t Type, uint8_t SectionIndex, uint16_t Flags, uint64_t Value, StringRef StringTable) { const char *Name = &StringTable.data()[StringIndex]; outs() << " # Symbol " << Index << "\n"; outs() << " (('n_strx', " << StringIndex << ")\n"; outs() << " ('n_type', " << format("0x%x", Type) << ")\n"; outs() << " ('n_sect', " << uint32_t(SectionIndex) << ")\n"; outs() << " ('n_desc', " << Flags << ")\n"; outs() << " ('n_value', " << Value << ")\n"; outs() << " ('_string', '" << Name << "')\n"; outs() << " ),\n"; } static int DumpSymtabCommand(const MachOObjectFile &Obj) { MachO::symtab_command SLC = Obj.getSymtabLoadCommand(); outs() << " ('symoff', " << SLC.symoff << ")\n"; outs() << " ('nsyms', " << SLC.nsyms << ")\n"; outs() << " ('stroff', " << SLC.stroff << ")\n"; outs() << " ('strsize', " << SLC.strsize << ")\n"; // Dump the string data. outs() << " ('_string_data', '"; StringRef StringTable = Obj.getStringTableData(); outs().write_escaped(StringTable, /*UseHexEscapes=*/true) << "')\n"; // Dump the symbol table. outs() << " ('_symbols', [\n"; unsigned SymNum = 0; for (const SymbolRef &Symbol : Obj.symbols()) { DataRefImpl DRI = Symbol.getRawDataRefImpl(); if (Obj.is64Bit()) { MachO::nlist_64 STE = Obj.getSymbol64TableEntry(DRI); DumpSymbolTableEntryData(Obj, SymNum, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, STE.n_value, StringTable); } else { MachO::nlist STE = Obj.getSymbolTableEntry(DRI); DumpSymbolTableEntryData(Obj, SymNum, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, STE.n_value, StringTable); } SymNum++; } outs() << " ])\n"; return 0; } static int DumpDysymtabCommand(const MachOObjectFile &Obj) { MachO::dysymtab_command DLC = Obj.getDysymtabLoadCommand(); outs() << " ('ilocalsym', " << DLC.ilocalsym << ")\n"; outs() << " ('nlocalsym', " << DLC.nlocalsym << ")\n"; outs() << " ('iextdefsym', " << DLC.iextdefsym << ")\n"; outs() << " ('nextdefsym', " << DLC.nextdefsym << ")\n"; outs() << " ('iundefsym', " << DLC.iundefsym << ")\n"; outs() << " ('nundefsym', " << DLC.nundefsym << ")\n"; outs() << " ('tocoff', " << DLC.tocoff << ")\n"; outs() << " ('ntoc', " << DLC.ntoc << ")\n"; outs() << " ('modtaboff', " << DLC.modtaboff << ")\n"; outs() << " ('nmodtab', " << DLC.nmodtab << ")\n"; outs() << " ('extrefsymoff', " << DLC.extrefsymoff << ")\n"; outs() << " ('nextrefsyms', " << DLC.nextrefsyms << ")\n"; outs() << " ('indirectsymoff', " << DLC.indirectsymoff << ")\n"; outs() << " ('nindirectsyms', " << DLC.nindirectsyms << ")\n"; outs() << " ('extreloff', " << DLC.extreloff << ")\n"; outs() << " ('nextrel', " << DLC.nextrel << ")\n"; outs() << " ('locreloff', " << DLC.locreloff << ")\n"; outs() << " ('nlocrel', " << DLC.nlocrel << ")\n"; // Dump the indirect symbol table. outs() << " ('_indirect_symbols', [\n"; for (unsigned i = 0; i != DLC.nindirectsyms; ++i) { uint32_t ISTE = Obj.getIndirectSymbolTableEntry(DLC, i); outs() << " # Indirect Symbol " << i << "\n"; outs() << " (('symbol_index', " << format("0x%x", ISTE) << "),),\n"; } outs() << " ])\n"; return 0; } static int DumpLinkeditDataCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::linkedit_data_command LLC = Obj.getLinkeditDataLoadCommand(LCI); outs() << " ('dataoff', " << LLC.dataoff << ")\n" << " ('datasize', " << LLC.datasize << ")\n" << " ('_addresses', [\n"; SmallVector<uint64_t, 8> Addresses; Obj.ReadULEB128s(LLC.dataoff, Addresses); for (unsigned i = 0, e = Addresses.size(); i != e; ++i) outs() << " # Address " << i << '\n' << " ('address', " << format("0x%x", Addresses[i]) << "),\n"; outs() << " ])\n"; return 0; } static int DumpDataInCodeDataCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::linkedit_data_command LLC = Obj.getLinkeditDataLoadCommand(LCI); outs() << " ('dataoff', " << LLC.dataoff << ")\n" << " ('datasize', " << LLC.datasize << ")\n" << " ('_data_regions', [\n"; unsigned NumRegions = LLC.datasize / sizeof(MachO::data_in_code_entry); for (unsigned i = 0; i < NumRegions; ++i) { MachO::data_in_code_entry DICE= Obj.getDataInCodeTableEntry(LLC.dataoff, i); outs() << " # DICE " << i << "\n" << " ('offset', " << DICE.offset << ")\n" << " ('length', " << DICE.length << ")\n" << " ('kind', " << DICE.kind << ")\n"; } outs() <<" ])\n"; return 0; } static int DumpLinkerOptionsCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::linker_option_command LOLC = Obj.getLinkerOptionLoadCommand(LCI); outs() << " ('count', " << LOLC.count << ")\n" << " ('_strings', [\n"; uint64_t DataSize = LOLC.cmdsize - sizeof(MachO::linker_option_command); const char *P = LCI.Ptr + sizeof(MachO::linker_option_command); StringRef Data(P, DataSize); for (unsigned i = 0; i != LOLC.count; ++i) { std::pair<StringRef,StringRef> Split = Data.split('\0'); outs() << "\t\""; outs().write_escaped(Split.first); outs() << "\",\n"; Data = Split.second; } outs() <<" ])\n"; return 0; } static int DumpVersionMin(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::version_min_command VMLC = Obj.getVersionMinLoadCommand(LCI); outs() << " ('version, " << VMLC.version << ")\n" << " ('sdk, " << VMLC.sdk << ")\n"; return 0; } static int DumpDylibID(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { MachO::dylib_command DLLC = Obj.getDylibIDLoadCommand(LCI); outs() << " ('install_name', '" << LCI.Ptr + DLLC.dylib.name << "')\n" << " ('timestamp, " << DLLC.dylib.timestamp << ")\n" << " ('cur_version, " << DLLC.dylib.current_version << ")\n" << " ('compat_version, " << DLLC.dylib.compatibility_version << ")\n"; return 0; } static int DumpLoadCommand(const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &LCI) { switch (LCI.C.cmd) { case MachO::LC_SEGMENT: return DumpSegmentCommand(Obj, LCI); case MachO::LC_SEGMENT_64: return DumpSegment64Command(Obj, LCI); case MachO::LC_SYMTAB: return DumpSymtabCommand(Obj); case MachO::LC_DYSYMTAB: return DumpDysymtabCommand(Obj); case MachO::LC_CODE_SIGNATURE: case MachO::LC_SEGMENT_SPLIT_INFO: case MachO::LC_FUNCTION_STARTS: return DumpLinkeditDataCommand(Obj, LCI); case MachO::LC_DATA_IN_CODE: return DumpDataInCodeDataCommand(Obj, LCI); case MachO::LC_LINKER_OPTION: return DumpLinkerOptionsCommand(Obj, LCI); case MachO::LC_VERSION_MIN_IPHONEOS: case MachO::LC_VERSION_MIN_MACOSX: return DumpVersionMin(Obj, LCI); case MachO::LC_ID_DYLIB: return DumpDylibID(Obj, LCI); default: Warning("unknown load command: " + Twine(LCI.C.cmd)); return 0; } } static int DumpLoadCommand(const MachOObjectFile &Obj, unsigned Index, const MachOObjectFile::LoadCommandInfo &LCI) { outs() << " # Load Command " << Index << "\n" << " (('command', " << LCI.C.cmd << ")\n" << " ('size', " << LCI.C.cmdsize << ")\n"; int Res = DumpLoadCommand(Obj, LCI); outs() << " ),\n"; return Res; } static void printHeader(const MachOObjectFile *Obj, const MachO::mach_header &Header) { outs() << "('cputype', " << Header.cputype << ")\n"; outs() << "('cpusubtype', " << Header.cpusubtype << ")\n"; outs() << "('filetype', " << Header.filetype << ")\n"; outs() << "('num_load_commands', " << Header.ncmds << ")\n"; outs() << "('load_commands_size', " << Header.sizeofcmds << ")\n"; outs() << "('flag', " << Header.flags << ")\n"; // Print extended header if 64-bit. if (Obj->is64Bit()) { const MachO::mach_header_64 *Header64 = reinterpret_cast<const MachO::mach_header_64 *>(&Header); outs() << "('reserved', " << Header64->reserved << ")\n"; } } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { ProgramName = argv[0]; llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm Mach-O dumping tool\n"); ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFile); if (std::error_code EC = BinaryOrErr.getError()) return Error("unable to read input: '" + EC.message() + "'"); Binary &Binary = *BinaryOrErr.get().getBinary(); const MachOObjectFile *InputObject = dyn_cast<MachOObjectFile>(&Binary); if (!InputObject) return Error("Not a MachO object"); // Print the header MachO::mach_header_64 Header64; MachO::mach_header *Header = reinterpret_cast<MachO::mach_header*>(&Header64); if (InputObject->is64Bit()) Header64 = InputObject->getHeader64(); else *Header = InputObject->getHeader(); printHeader(InputObject, *Header); // Print the load commands. int Res = 0; unsigned Index = 0; outs() << "('load_commands', [\n"; for (const auto &Load : InputObject->load_commands()) { if (DumpLoadCommand(*InputObject, Index++, Load)) break; } outs() << "])\n"; return Res; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp
//===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool may be invoked in the following manner: // llvm-bcanalyzer [options] - Read LLVM bitcode from stdin // llvm-bcanalyzer [options] x.bc - Read LLVM bitcode from the x.bc file // // Options: // --help - Output information about command line switches // --dump - Dump low-level bitcode structure in readable format // // This tool provides analytical information about a bitcode file. It is // intended as an aid to developers of bitcode reading and writing software. It // produces on std::out a summary of the bitcode file that shows various // statistics about the contents of the file. By default this information is // detailed and contains information about individual bitcode blocks and the // functions in the module. // The tool is also able to print a bitcode file in a straight forward text // format that shows the containment and relationships of the information in // the bitcode file (-dump option). // //===----------------------------------------------------------------------===// #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/ADT/Optional.h" #include "llvm/Bitcode/LLVMBitCodes.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cctype> #include <map> #include <system_error> // HLSL Change Starts #include "dxc/Support/Global.h" #include "dxc/Support/WinIncludes.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MSFileSystem.h" // HLSL Change Ends using namespace llvm; static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace")); //===----------------------------------------------------------------------===// // Bitcode specific analysis. //===----------------------------------------------------------------------===// static cl::opt<bool> NoHistogram("disable-histogram", cl::desc("Do not print per-code histogram")); static cl::opt<bool> NonSymbolic("non-symbolic", cl::desc("Emit numeric info in dump even if" " symbolic info is available")); static cl::opt<std::string> BlockInfoFilename("block-info", cl::desc("Use the BLOCK_INFO from the given file")); static cl::opt<bool> ShowBinaryBlobs("show-binary-blobs", cl::desc("Print binary blobs using hex escapes")); namespace { /// CurStreamTypeType - A type for CurStreamType enum CurStreamTypeType { UnknownBitstream, LLVMIRBitstream }; } /// GetBlockName - Return a symbolic block name if known, otherwise return /// null. static const char *GetBlockName(unsigned BlockID, const BitstreamReader &StreamFile, CurStreamTypeType CurStreamType) { // Standard blocks for all bitcode files. if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) { if (BlockID == bitc::BLOCKINFO_BLOCK_ID) return "BLOCKINFO_BLOCK"; return nullptr; } // Check to see if we have a blockinfo record for this block, with a name. if (const BitstreamReader::BlockInfo *Info = StreamFile.getBlockInfo(BlockID)) { if (!Info->Name.empty()) return Info->Name.c_str(); } if (CurStreamType != LLVMIRBitstream) return nullptr; switch (BlockID) { default: return nullptr; case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK"; case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK"; case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID"; case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID"; case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK"; case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK"; case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB"; case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK"; case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK"; case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID"; } } /// GetCodeName - Return a symbolic code name if known, otherwise return /// null. static const char *GetCodeName(unsigned CodeID, unsigned BlockID, const BitstreamReader &StreamFile, CurStreamTypeType CurStreamType) { // Standard blocks for all bitcode files. if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) { if (BlockID == bitc::BLOCKINFO_BLOCK_ID) { switch (CodeID) { default: return nullptr; case bitc::BLOCKINFO_CODE_SETBID: return "SETBID"; case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME"; case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME"; } } return nullptr; } // Check to see if we have a blockinfo record for this record, with a name. if (const BitstreamReader::BlockInfo *Info = StreamFile.getBlockInfo(BlockID)) { for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i) if (Info->RecordNames[i].first == CodeID) return Info->RecordNames[i].second.c_str(); } if (CurStreamType != LLVMIRBitstream) return nullptr; #define STRINGIFY_CODE(PREFIX, CODE) \ case bitc::PREFIX##_##CODE: \ return #CODE; switch (BlockID) { default: return nullptr; case bitc::MODULE_BLOCK_ID: switch (CodeID) { default: return nullptr; STRINGIFY_CODE(MODULE_CODE, VERSION) STRINGIFY_CODE(MODULE_CODE, TRIPLE) STRINGIFY_CODE(MODULE_CODE, DATALAYOUT) STRINGIFY_CODE(MODULE_CODE, ASM) STRINGIFY_CODE(MODULE_CODE, SECTIONNAME) STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR) STRINGIFY_CODE(MODULE_CODE, FUNCTION) STRINGIFY_CODE(MODULE_CODE, ALIAS) STRINGIFY_CODE(MODULE_CODE, PURGEVALS) STRINGIFY_CODE(MODULE_CODE, GCNAME) } case bitc::PARAMATTR_BLOCK_ID: switch (CodeID) { default: return nullptr; // FIXME: Should these be different? case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY"; case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY"; case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY"; } case bitc::TYPE_BLOCK_ID_NEW: switch (CodeID) { default: return nullptr; STRINGIFY_CODE(TYPE_CODE, NUMENTRY) STRINGIFY_CODE(TYPE_CODE, VOID) STRINGIFY_CODE(TYPE_CODE, FLOAT) STRINGIFY_CODE(TYPE_CODE, DOUBLE) STRINGIFY_CODE(TYPE_CODE, LABEL) STRINGIFY_CODE(TYPE_CODE, OPAQUE) STRINGIFY_CODE(TYPE_CODE, INTEGER) STRINGIFY_CODE(TYPE_CODE, POINTER) STRINGIFY_CODE(TYPE_CODE, ARRAY) STRINGIFY_CODE(TYPE_CODE, VECTOR) STRINGIFY_CODE(TYPE_CODE, X86_FP80) STRINGIFY_CODE(TYPE_CODE, FP128) STRINGIFY_CODE(TYPE_CODE, PPC_FP128) STRINGIFY_CODE(TYPE_CODE, METADATA) STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON) STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME) STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED) STRINGIFY_CODE(TYPE_CODE, FUNCTION) } case bitc::CONSTANTS_BLOCK_ID: switch (CodeID) { default: return nullptr; STRINGIFY_CODE(CST_CODE, SETTYPE) STRINGIFY_CODE(CST_CODE, NULL) STRINGIFY_CODE(CST_CODE, UNDEF) STRINGIFY_CODE(CST_CODE, INTEGER) STRINGIFY_CODE(CST_CODE, WIDE_INTEGER) STRINGIFY_CODE(CST_CODE, FLOAT) STRINGIFY_CODE(CST_CODE, AGGREGATE) STRINGIFY_CODE(CST_CODE, STRING) STRINGIFY_CODE(CST_CODE, CSTRING) STRINGIFY_CODE(CST_CODE, CE_BINOP) STRINGIFY_CODE(CST_CODE, CE_CAST) STRINGIFY_CODE(CST_CODE, CE_GEP) STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP) STRINGIFY_CODE(CST_CODE, CE_SELECT) STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT) STRINGIFY_CODE(CST_CODE, CE_INSERTELT) STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC) STRINGIFY_CODE(CST_CODE, CE_CMP) STRINGIFY_CODE(CST_CODE, INLINEASM) STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX) case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS"; STRINGIFY_CODE(CST_CODE, DATA) } case bitc::FUNCTION_BLOCK_ID: switch (CodeID) { default: return nullptr; STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS) STRINGIFY_CODE(FUNC_CODE, INST_BINOP) STRINGIFY_CODE(FUNC_CODE, INST_CAST) STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD) STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD) STRINGIFY_CODE(FUNC_CODE, INST_SELECT) STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT) STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT) STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC) STRINGIFY_CODE(FUNC_CODE, INST_CMP) STRINGIFY_CODE(FUNC_CODE, INST_RET) STRINGIFY_CODE(FUNC_CODE, INST_BR) STRINGIFY_CODE(FUNC_CODE, INST_SWITCH) STRINGIFY_CODE(FUNC_CODE, INST_INVOKE) STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE) STRINGIFY_CODE(FUNC_CODE, INST_PHI) STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA) STRINGIFY_CODE(FUNC_CODE, INST_LOAD) STRINGIFY_CODE(FUNC_CODE, INST_VAARG) STRINGIFY_CODE(FUNC_CODE, INST_STORE) STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL) STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL) STRINGIFY_CODE(FUNC_CODE, INST_CMP2) STRINGIFY_CODE(FUNC_CODE, INST_VSELECT) STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN) STRINGIFY_CODE(FUNC_CODE, INST_CALL) STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC) STRINGIFY_CODE(FUNC_CODE, INST_GEP) } case bitc::VALUE_SYMTAB_BLOCK_ID: switch (CodeID) { default: return nullptr; STRINGIFY_CODE(VST_CODE, ENTRY) STRINGIFY_CODE(VST_CODE, BBENTRY) } case bitc::METADATA_ATTACHMENT_ID: switch(CodeID) { default:return nullptr; STRINGIFY_CODE(METADATA, ATTACHMENT) } case bitc::METADATA_BLOCK_ID: switch(CodeID) { default:return nullptr; STRINGIFY_CODE(METADATA, STRING) STRINGIFY_CODE(METADATA, NAME) STRINGIFY_CODE(METADATA, KIND) STRINGIFY_CODE(METADATA, NODE) STRINGIFY_CODE(METADATA, VALUE) STRINGIFY_CODE(METADATA, OLD_NODE) STRINGIFY_CODE(METADATA, OLD_FN_NODE) STRINGIFY_CODE(METADATA, NAMED_NODE) STRINGIFY_CODE(METADATA, DISTINCT_NODE) STRINGIFY_CODE(METADATA, LOCATION) STRINGIFY_CODE(METADATA, GENERIC_DEBUG) STRINGIFY_CODE(METADATA, SUBRANGE) STRINGIFY_CODE(METADATA, ENUMERATOR) STRINGIFY_CODE(METADATA, BASIC_TYPE) STRINGIFY_CODE(METADATA, FILE) STRINGIFY_CODE(METADATA, DERIVED_TYPE) STRINGIFY_CODE(METADATA, COMPOSITE_TYPE) STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE) STRINGIFY_CODE(METADATA, COMPILE_UNIT) STRINGIFY_CODE(METADATA, SUBPROGRAM) STRINGIFY_CODE(METADATA, LEXICAL_BLOCK) STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE) STRINGIFY_CODE(METADATA, NAMESPACE) STRINGIFY_CODE(METADATA, TEMPLATE_TYPE) STRINGIFY_CODE(METADATA, TEMPLATE_VALUE) STRINGIFY_CODE(METADATA, GLOBAL_VAR) STRINGIFY_CODE(METADATA, LOCAL_VAR) STRINGIFY_CODE(METADATA, EXPRESSION) STRINGIFY_CODE(METADATA, OBJC_PROPERTY) STRINGIFY_CODE(METADATA, IMPORTED_ENTITY) STRINGIFY_CODE(METADATA, MODULE) } case bitc::USELIST_BLOCK_ID: switch(CodeID) { default:return nullptr; case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT"; case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB"; } } #undef STRINGIFY_CODE } struct PerRecordStats { unsigned NumInstances; unsigned NumAbbrev; uint64_t TotalBits; PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {} }; struct PerBlockIDStats { /// NumInstances - This the number of times this block ID has been seen. unsigned NumInstances; /// NumBits - The total size in bits of all of these blocks. uint64_t NumBits; /// NumSubBlocks - The total number of blocks these blocks contain. unsigned NumSubBlocks; /// NumAbbrevs - The total number of abbreviations. unsigned NumAbbrevs; /// NumRecords - The total number of records these blocks contain, and the /// number that are abbreviated. unsigned NumRecords, NumAbbreviatedRecords; /// CodeFreq - Keep track of the number of times we see each code. std::vector<PerRecordStats> CodeFreq; PerBlockIDStats() : NumInstances(0), NumBits(0), NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {} }; static std::map<unsigned, PerBlockIDStats> BlockIDStats; /// Error - All bitcode analysis errors go through this function, making this a /// good place to breakpoint if debugging. static bool Error(const Twine &Err) { errs() << Err << "\n"; return true; } /// ParseBlock - Read a block, updating statistics, etc. static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID, unsigned IndentLevel, CurStreamTypeType CurStreamType) { std::string Indent(IndentLevel*2, ' '); uint64_t BlockBitStart = Stream.GetCurrentBitNo(); // Get the statistics for this BlockID. PerBlockIDStats &BlockStats = BlockIDStats[BlockID]; BlockStats.NumInstances++; // BLOCKINFO is a special part of the stream. if (BlockID == bitc::BLOCKINFO_BLOCK_ID) { if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n"; if (Stream.ReadBlockInfoBlock()) return Error("Malformed BlockInfoBlock"); uint64_t BlockBitEnd = Stream.GetCurrentBitNo(); BlockStats.NumBits += BlockBitEnd-BlockBitStart; return false; } unsigned NumWords = 0; if (Stream.EnterSubBlock(BlockID, &NumWords)) return Error("Malformed block record"); const char *BlockName = nullptr; if (Dump) { outs() << Indent << "<"; if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(), CurStreamType))) outs() << BlockName; else outs() << "UnknownBlock" << BlockID; if (NonSymbolic && BlockName) outs() << " BlockID=" << BlockID; outs() << " NumWords=" << NumWords << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n"; } SmallVector<uint64_t, 64> Record; // Read all the records for this block. while (1) { if (Stream.AtEndOfStream()) return Error("Premature end of bitstream"); uint64_t RecordStartBit = Stream.GetCurrentBitNo(); BitstreamEntry Entry = Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); switch (Entry.Kind) { case BitstreamEntry::Error: return Error("malformed bitcode file"); case BitstreamEntry::EndBlock: { uint64_t BlockBitEnd = Stream.GetCurrentBitNo(); BlockStats.NumBits += BlockBitEnd-BlockBitStart; if (Dump) { outs() << Indent << "</"; if (BlockName) outs() << BlockName << ">\n"; else outs() << "UnknownBlock" << BlockID << ">\n"; } return false; } case BitstreamEntry::SubBlock: { uint64_t SubBlockBitStart = Stream.GetCurrentBitNo(); if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType)) return true; ++BlockStats.NumSubBlocks; uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo(); // Don't include subblock sizes in the size of this block. BlockBitStart += SubBlockBitEnd-SubBlockBitStart; continue; } case BitstreamEntry::Record: // The interesting case. break; } if (Entry.ID == bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); ++BlockStats.NumAbbrevs; continue; } Record.clear(); ++BlockStats.NumRecords; StringRef Blob; unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob); // Increment the # occurrences of this code. if (BlockStats.CodeFreq.size() <= Code) BlockStats.CodeFreq.resize(Code+1); BlockStats.CodeFreq[Code].NumInstances++; BlockStats.CodeFreq[Code].TotalBits += Stream.GetCurrentBitNo()-RecordStartBit; if (Entry.ID != bitc::UNABBREV_RECORD) { BlockStats.CodeFreq[Code].NumAbbrev++; ++BlockStats.NumAbbreviatedRecords; } if (Dump) { outs() << Indent << " <"; if (const char *CodeName = GetCodeName(Code, BlockID, *Stream.getBitStreamReader(), CurStreamType)) outs() << CodeName; else outs() << "UnknownCode" << Code; if (NonSymbolic && GetCodeName(Code, BlockID, *Stream.getBitStreamReader(), CurStreamType)) outs() << " codeid=" << Code; if (Entry.ID != bitc::UNABBREV_RECORD) outs() << " abbrevid=" << Entry.ID; for (unsigned i = 0, e = Record.size(); i != e; ++i) outs() << " op" << i << "=" << (int64_t)Record[i]; outs() << "/>"; if (Blob.data()) { outs() << " blob data = "; if (ShowBinaryBlobs) { outs() << "'"; outs().write_escaped(Blob, /*hex=*/true) << "'"; } else { bool BlobIsPrintable = true; for (unsigned i = 0, e = Blob.size(); i != e; ++i) if (!isprint(static_cast<unsigned char>(Blob[i]))) { BlobIsPrintable = false; break; } if (BlobIsPrintable) outs() << "'" << Blob << "'"; else outs() << "unprintable, " << Blob.size() << " bytes."; } } outs() << "\n"; } } } static void PrintSize(double Bits) { outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32)); } static void PrintSize(uint64_t Bits) { outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits, (double)Bits/8, (unsigned long)(Bits/32)); } static bool openBitcodeFile(StringRef Path, std::unique_ptr<MemoryBuffer> &MemBuf, BitstreamReader &StreamFile, BitstreamCursor &Stream, CurStreamTypeType &CurStreamType) { // Read the input file. ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr = MemoryBuffer::getFileOrSTDIN(Path); if (std::error_code EC = MemBufOrErr.getError()) return Error(Twine("Error reading '") + Path + "': " + EC.message()); MemBuf = std::move(MemBufOrErr.get()); if (MemBuf->getBufferSize() & 3) return Error("Bitcode stream should be a multiple of 4 bytes in length"); const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart(); const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize(); // If we have a wrapper header, parse it and ignore the non-bc file contents. // The magic number is 0x0B17C0DE stored in little endian. if (isBitcodeWrapper(BufPtr, EndBufPtr)) if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true)) return Error("Invalid bitcode wrapper header"); StreamFile = BitstreamReader(BufPtr, EndBufPtr); Stream = BitstreamCursor(StreamFile); StreamFile.CollectBlockInfoNames(); // Read the stream signature. char Signature[6]; Signature[0] = Stream.Read(8); Signature[1] = Stream.Read(8); Signature[2] = Stream.Read(4); Signature[3] = Stream.Read(4); Signature[4] = Stream.Read(4); Signature[5] = Stream.Read(4); // Autodetect the file contents, if it is one we know. CurStreamType = UnknownBitstream; if (Signature[0] == 'B' && Signature[1] == 'C' && Signature[2] == 0x0 && Signature[3] == 0xC && Signature[4] == 0xE && Signature[5] == 0xD) CurStreamType = LLVMIRBitstream; return false; } /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename. static int AnalyzeBitcode() { std::unique_ptr<MemoryBuffer> StreamBuffer; BitstreamReader StreamFile; BitstreamCursor Stream; CurStreamTypeType CurStreamType; if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream, CurStreamType)) return true; // Read block info from BlockInfoFilename, if specified. // The block info must be a top-level block. if (!BlockInfoFilename.empty()) { std::unique_ptr<MemoryBuffer> BlockInfoBuffer; BitstreamReader BlockInfoFile; BitstreamCursor BlockInfoCursor; CurStreamTypeType BlockInfoStreamType; if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile, BlockInfoCursor, BlockInfoStreamType)) return true; while (!BlockInfoCursor.AtEndOfStream()) { unsigned Code = BlockInfoCursor.ReadCode(); if (Code != bitc::ENTER_SUBBLOCK) return Error("Invalid record at top-level in block info file"); unsigned BlockID = BlockInfoCursor.ReadSubBlockID(); if (BlockID == bitc::BLOCKINFO_BLOCK_ID) { if (BlockInfoCursor.ReadBlockInfoBlock()) return Error("Malformed BlockInfoBlock in block info file"); break; } BlockInfoCursor.SkipBlock(); } StreamFile.takeBlockInfo(std::move(BlockInfoFile)); } unsigned NumTopBlocks = 0; // Parse the top-level structure. We only allow blocks at the top-level. while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); if (Code != bitc::ENTER_SUBBLOCK) return Error("Invalid record at top-level"); unsigned BlockID = Stream.ReadSubBlockID(); if (ParseBlock(Stream, BlockID, 0, CurStreamType)) return true; ++NumTopBlocks; } if (Dump) outs() << "\n\n"; uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT; // Print a summary of the read file. outs() << "Summary of " << InputFilename << ":\n"; outs() << " Total size: "; PrintSize(BufferSizeBits); outs() << "\n"; outs() << " Stream type: "; switch (CurStreamType) { case UnknownBitstream: outs() << "unknown\n"; break; case LLVMIRBitstream: outs() << "LLVM IR\n"; break; } outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n"; outs() << "\n"; // Emit per-block stats. outs() << "Per-block Summary:\n"; for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(), E = BlockIDStats.end(); I != E; ++I) { outs() << " Block ID #" << I->first; if (const char *BlockName = GetBlockName(I->first, StreamFile, CurStreamType)) outs() << " (" << BlockName << ")"; outs() << ":\n"; const PerBlockIDStats &Stats = I->second; outs() << " Num Instances: " << Stats.NumInstances << "\n"; outs() << " Total Size: "; PrintSize(Stats.NumBits); outs() << "\n"; double pct = (Stats.NumBits * 100.0) / BufferSizeBits; outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n"; if (Stats.NumInstances > 1) { outs() << " Average Size: "; PrintSize(Stats.NumBits/(double)Stats.NumInstances); outs() << "\n"; outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/" << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n"; outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/" << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n"; outs() << " Tot/Avg Records: " << Stats.NumRecords << "/" << Stats.NumRecords/(double)Stats.NumInstances << "\n"; } else { outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n"; outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n"; outs() << " Num Records: " << Stats.NumRecords << "\n"; } if (Stats.NumRecords) { double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords; outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n"; } outs() << "\n"; // Print a histogram of the codes we see. if (!NoHistogram && !Stats.CodeFreq.empty()) { std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code> for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i) if (unsigned Freq = Stats.CodeFreq[i].NumInstances) FreqPairs.push_back(std::make_pair(Freq, i)); std::stable_sort(FreqPairs.begin(), FreqPairs.end()); std::reverse(FreqPairs.begin(), FreqPairs.end()); outs() << "\tRecord Histogram:\n"; outs() << "\t\t Count # Bits %% Abv Record Kind\n"; for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) { const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second]; outs() << format("\t\t%7d %9lu", RecStats.NumInstances, (unsigned long)RecStats.TotalBits); if (RecStats.NumAbbrev) outs() << format("%7.2f ", (double)RecStats.NumAbbrev/RecStats.NumInstances*100); else outs() << " "; if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first, StreamFile, CurStreamType)) outs() << CodeName << "\n"; else outs() << "UnknownCode" << FreqPairs[i].second << "\n"; } outs() << "\n"; } } return 0; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { // HLSL Change Starts #if 1 llvm::sys::fs::MSFileSystem* msfPtr; if (FAILED(CreateMSFileSystemForDisk(&msfPtr))) return 1; std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr); llvm::sys::fs::AutoPerThreadSystem pts(msf.get()); #else // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); #endif // HLSL Change Ends llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n"); return AnalyzeBitcode(); }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-bcanalyzer/CMakeLists.txt
set(LLVM_LINK_COMPONENTS BitReader Support ) add_llvm_tool(llvm-bcanalyzer llvm-bcanalyzer.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-bcanalyzer/LLVMBuild.txt
;===- ./tools/llvm-bcanalyzer/LLVMBuild.txt --------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-bcanalyzer parent = Tools required_libraries = BitReader
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/yaml2obj/yaml2elf.cpp
//===- yaml2elf - Convert YAML to a ELF object file -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief The ELF component of yaml2obj. /// //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/MC/StringTableBuilder.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ELFYAML.h" #include "llvm/Support/ELF.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; // This class is used to build up a contiguous binary blob while keeping // track of an offset in the output (which notionally begins at // `InitialOffset`). namespace { class ContiguousBlobAccumulator { const uint64_t InitialOffset; SmallVector<char, 128> Buf; raw_svector_ostream OS; /// \returns The new offset. uint64_t padToAlignment(unsigned Align) { if (Align == 0) Align = 1; uint64_t CurrentOffset = InitialOffset + OS.tell(); uint64_t AlignedOffset = RoundUpToAlignment(CurrentOffset, Align); for (; CurrentOffset != AlignedOffset; ++CurrentOffset) OS.write('\0'); return AlignedOffset; // == CurrentOffset; } public: ContiguousBlobAccumulator(uint64_t InitialOffset_) : InitialOffset(InitialOffset_), Buf(), OS(Buf) {} template <class Integer> raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align) { Offset = padToAlignment(Align); return OS; } void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); } }; } // end anonymous namespace // Used to keep track of section and symbol names, so that in the YAML file // sections and symbols can be referenced by name instead of by index. namespace { class NameToIdxMap { StringMap<int> Map; public: /// \returns true if name is already present in the map. bool addName(StringRef Name, unsigned i) { return !Map.insert(std::make_pair(Name, (int)i)).second; } /// \returns true if name is not present in the map bool lookup(StringRef Name, unsigned &Idx) const { StringMap<int>::const_iterator I = Map.find(Name); if (I == Map.end()) return true; Idx = I->getValue(); return false; } }; } // end anonymous namespace template <class T> static size_t arrayDataSize(ArrayRef<T> A) { return A.size() * sizeof(T); } template <class T> static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) { OS.write((const char *)A.data(), arrayDataSize(A)); } template <class T> static void zero(T &Obj) { memset(&Obj, 0, sizeof(Obj)); } namespace { /// \brief "Single point of truth" for the ELF file construction. /// TODO: This class still has a ways to go before it is truly a "single /// point of truth". template <class ELFT> class ELFState { typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr; typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr; typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym; typedef typename object::ELFFile<ELFT>::Elf_Rel Elf_Rel; typedef typename object::ELFFile<ELFT>::Elf_Rela Elf_Rela; /// \brief The future ".strtab" section. StringTableBuilder DotStrtab; /// \brief The future ".shstrtab" section. StringTableBuilder DotShStrtab; NameToIdxMap SN2I; NameToIdxMap SymN2I; const ELFYAML::Object &Doc; bool buildSectionIndex(); bool buildSymbolIndex(std::size_t &StartIndex, const std::vector<ELFYAML::Symbol> &Symbols); void initELFHeader(Elf_Ehdr &Header); bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders, ContiguousBlobAccumulator &CBA); void initSymtabSectionHeader(Elf_Shdr &SHeader, ContiguousBlobAccumulator &CBA); void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name, StringTableBuilder &STB, ContiguousBlobAccumulator &CBA); void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols, std::vector<Elf_Sym> &Syms, unsigned SymbolBinding); void writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section, ContiguousBlobAccumulator &CBA); bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section, ContiguousBlobAccumulator &CBA); bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Group, ContiguousBlobAccumulator &CBA); bool writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::MipsABIFlags &Section, ContiguousBlobAccumulator &CBA); // - SHT_NULL entry (placed first, i.e. 0'th entry) // - symbol table (.symtab) (placed third to last) // - string table (.strtab) (placed second to last) // - section header string table (.shstrtab) (placed last) unsigned getDotSymTabSecNo() const { return Doc.Sections.size() + 1; } unsigned getDotStrTabSecNo() const { return Doc.Sections.size() + 2; } unsigned getDotShStrTabSecNo() const { return Doc.Sections.size() + 3; } unsigned getSectionCount() const { return Doc.Sections.size() + 4; } ELFState(const ELFYAML::Object &D) : Doc(D) {} public: static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc); }; } // end anonymous namespace template <class ELFT> void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) { using namespace llvm::ELF; zero(Header); Header.e_ident[EI_MAG0] = 0x7f; Header.e_ident[EI_MAG1] = 'E'; Header.e_ident[EI_MAG2] = 'L'; Header.e_ident[EI_MAG3] = 'F'; Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; bool IsLittleEndian = ELFT::TargetEndianness == support::little; Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB; Header.e_ident[EI_VERSION] = EV_CURRENT; Header.e_ident[EI_OSABI] = Doc.Header.OSABI; Header.e_ident[EI_ABIVERSION] = 0; Header.e_type = Doc.Header.Type; Header.e_machine = Doc.Header.Machine; Header.e_version = EV_CURRENT; Header.e_entry = Doc.Header.Entry; Header.e_flags = Doc.Header.Flags; Header.e_ehsize = sizeof(Elf_Ehdr); Header.e_shentsize = sizeof(Elf_Shdr); // Immediately following the ELF header. Header.e_shoff = sizeof(Header); Header.e_shnum = getSectionCount(); Header.e_shstrndx = getDotShStrTabSecNo(); } template <class ELFT> bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders, ContiguousBlobAccumulator &CBA) { // Ensure SHN_UNDEF entry is present. An all-zero section header is a // valid SHN_UNDEF entry since SHT_NULL == 0. Elf_Shdr SHeader; zero(SHeader); SHeaders.push_back(SHeader); for (const auto &Sec : Doc.Sections) DotShStrtab.add(Sec->Name); DotShStrtab.finalize(StringTableBuilder::ELF); for (const auto &Sec : Doc.Sections) { zero(SHeader); SHeader.sh_name = DotShStrtab.getOffset(Sec->Name); SHeader.sh_type = Sec->Type; SHeader.sh_flags = Sec->Flags; SHeader.sh_addr = Sec->Address; SHeader.sh_addralign = Sec->AddressAlign; if (!Sec->Link.empty()) { unsigned Index; if (SN2I.lookup(Sec->Link, Index)) { errs() << "error: Unknown section referenced: '" << Sec->Link << "' at YAML section '" << Sec->Name << "'.\n"; return false; } SHeader.sh_link = Index; } if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get())) writeSectionContent(SHeader, *S, CBA); else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) { if (S->Link.empty()) // For relocation section set link to .symtab by default. SHeader.sh_link = getDotSymTabSecNo(); unsigned Index; if (SN2I.lookup(S->Info, Index)) { errs() << "error: Unknown section referenced: '" << S->Info << "' at YAML section '" << S->Name << "'.\n"; return false; } SHeader.sh_info = Index; if (!writeSectionContent(SHeader, *S, CBA)) return false; } else if (auto S = dyn_cast<ELFYAML::Group>(Sec.get())) { unsigned SymIdx; if (SymN2I.lookup(S->Info, SymIdx)) { errs() << "error: Unknown symbol referenced: '" << S->Info << "' at YAML section '" << S->Name << "'.\n"; return false; } SHeader.sh_info = SymIdx; if (!writeSectionContent(SHeader, *S, CBA)) return false; } else if (auto S = dyn_cast<ELFYAML::MipsABIFlags>(Sec.get())) { if (!writeSectionContent(SHeader, *S, CBA)) return false; } else if (auto S = dyn_cast<ELFYAML::NoBitsSection>(Sec.get())) { SHeader.sh_entsize = 0; SHeader.sh_size = S->Size; // SHT_NOBITS section does not have content // so just to setup the section offset. CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign); } else llvm_unreachable("Unknown section type"); SHeaders.push_back(SHeader); } return true; } template <class ELFT> void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader, ContiguousBlobAccumulator &CBA) { zero(SHeader); SHeader.sh_name = DotShStrtab.getOffset(".symtab"); SHeader.sh_type = ELF::SHT_SYMTAB; SHeader.sh_link = getDotStrTabSecNo(); // One greater than symbol table index of the last local symbol. SHeader.sh_info = Doc.Symbols.Local.size() + 1; SHeader.sh_entsize = sizeof(Elf_Sym); SHeader.sh_addralign = 8; std::vector<Elf_Sym> Syms; { // Ensure STN_UNDEF is present Elf_Sym Sym; zero(Sym); Syms.push_back(Sym); } // Add symbol names to .strtab. for (const auto &Sym : Doc.Symbols.Local) DotStrtab.add(Sym.Name); for (const auto &Sym : Doc.Symbols.Global) DotStrtab.add(Sym.Name); for (const auto &Sym : Doc.Symbols.Weak) DotStrtab.add(Sym.Name); DotStrtab.finalize(StringTableBuilder::ELF); addSymbols(Doc.Symbols.Local, Syms, ELF::STB_LOCAL); addSymbols(Doc.Symbols.Global, Syms, ELF::STB_GLOBAL); addSymbols(Doc.Symbols.Weak, Syms, ELF::STB_WEAK); writeArrayData( CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign), makeArrayRef(Syms)); SHeader.sh_size = arrayDataSize(makeArrayRef(Syms)); } template <class ELFT> void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name, StringTableBuilder &STB, ContiguousBlobAccumulator &CBA) { zero(SHeader); SHeader.sh_name = DotShStrtab.getOffset(Name); SHeader.sh_type = ELF::SHT_STRTAB; CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign) << STB.data(); SHeader.sh_size = STB.data().size(); SHeader.sh_addralign = 1; } template <class ELFT> void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols, std::vector<Elf_Sym> &Syms, unsigned SymbolBinding) { for (const auto &Sym : Symbols) { Elf_Sym Symbol; zero(Symbol); if (!Sym.Name.empty()) Symbol.st_name = DotStrtab.getOffset(Sym.Name); Symbol.setBindingAndType(SymbolBinding, Sym.Type); if (!Sym.Section.empty()) { unsigned Index; if (SN2I.lookup(Sym.Section, Index)) { errs() << "error: Unknown section referenced: '" << Sym.Section << "' by YAML symbol " << Sym.Name << ".\n"; exit(1); } Symbol.st_shndx = Index; } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier. Symbol.st_value = Sym.Value; Symbol.st_other = Sym.Other; Symbol.st_size = Sym.Size; Syms.push_back(Symbol); } } template <class ELFT> void ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::RawContentSection &Section, ContiguousBlobAccumulator &CBA) { assert(Section.Size >= Section.Content.binary_size() && "Section size and section content are inconsistent"); raw_ostream &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign); Section.Content.writeAsBinary(OS); for (auto i = Section.Content.binary_size(); i < Section.Size; ++i) OS.write(0); SHeader.sh_entsize = 0; SHeader.sh_size = Section.Size; } static bool isMips64EL(const ELFYAML::Object &Doc) { return Doc.Header.Machine == ELFYAML::ELF_EM(llvm::ELF::EM_MIPS) && Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64) && Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB); } template <class ELFT> bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::RelocationSection &Section, ContiguousBlobAccumulator &CBA) { assert((Section.Type == llvm::ELF::SHT_REL || Section.Type == llvm::ELF::SHT_RELA) && "Section type is not SHT_REL nor SHT_RELA"); bool IsRela = Section.Type == llvm::ELF::SHT_RELA; SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size(); auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign); for (const auto &Rel : Section.Relocations) { unsigned SymIdx = 0; // Some special relocation, R_ARM_v4BX for instance, does not have // an external reference. So it ignores the return value of lookup() // here. SymN2I.lookup(Rel.Symbol, SymIdx); if (IsRela) { Elf_Rela REntry; zero(REntry); REntry.r_offset = Rel.Offset; REntry.r_addend = Rel.Addend; REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc)); OS.write((const char *)&REntry, sizeof(REntry)); } else { Elf_Rel REntry; zero(REntry); REntry.r_offset = Rel.Offset; REntry.setSymbolAndType(SymIdx, Rel.Type, isMips64EL(Doc)); OS.write((const char *)&REntry, sizeof(REntry)); } } return true; } template <class ELFT> bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::Group &Section, ContiguousBlobAccumulator &CBA) { typedef typename object::ELFFile<ELFT>::Elf_Word Elf_Word; assert(Section.Type == llvm::ELF::SHT_GROUP && "Section type is not SHT_GROUP"); SHeader.sh_entsize = sizeof(Elf_Word); SHeader.sh_size = SHeader.sh_entsize * Section.Members.size(); auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign); for (auto member : Section.Members) { Elf_Word SIdx; unsigned int sectionIndex = 0; if (member.sectionNameOrType == "GRP_COMDAT") sectionIndex = llvm::ELF::GRP_COMDAT; else if (SN2I.lookup(member.sectionNameOrType, sectionIndex)) { errs() << "error: Unknown section referenced: '" << member.sectionNameOrType << "' at YAML section' " << Section.Name << "\n"; return false; } SIdx = sectionIndex; OS.write((const char *)&SIdx, sizeof(SIdx)); } return true; } template <class ELFT> bool ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader, const ELFYAML::MipsABIFlags &Section, ContiguousBlobAccumulator &CBA) { assert(Section.Type == llvm::ELF::SHT_MIPS_ABIFLAGS && "Section type is not SHT_MIPS_ABIFLAGS"); object::Elf_Mips_ABIFlags<ELFT> Flags; zero(Flags); SHeader.sh_entsize = sizeof(Flags); SHeader.sh_size = SHeader.sh_entsize; auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset, SHeader.sh_addralign); Flags.version = Section.Version; Flags.isa_level = Section.ISALevel; Flags.isa_rev = Section.ISARevision; Flags.gpr_size = Section.GPRSize; Flags.cpr1_size = Section.CPR1Size; Flags.cpr2_size = Section.CPR2Size; Flags.fp_abi = Section.FpABI; Flags.isa_ext = Section.ISAExtension; Flags.ases = Section.ASEs; Flags.flags1 = Section.Flags1; Flags.flags2 = Section.Flags2; OS.write((const char *)&Flags, sizeof(Flags)); return true; } template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() { SN2I.addName(".symtab", getDotSymTabSecNo()); SN2I.addName(".strtab", getDotStrTabSecNo()); SN2I.addName(".shstrtab", getDotShStrTabSecNo()); for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) { StringRef Name = Doc.Sections[i]->Name; if (Name.empty()) continue; // "+ 1" to take into account the SHT_NULL entry. if (SN2I.addName(Name, i + 1)) { errs() << "error: Repeated section name: '" << Name << "' at YAML section number " << i << ".\n"; return false; } } return true; } template <class ELFT> bool ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex, const std::vector<ELFYAML::Symbol> &Symbols) { for (const auto &Sym : Symbols) { ++StartIndex; if (Sym.Name.empty()) continue; if (SymN2I.addName(Sym.Name, StartIndex)) { errs() << "error: Repeated symbol name: '" << Sym.Name << "'.\n"; return false; } } return true; } template <class ELFT> int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) { ELFState<ELFT> State(Doc); if (!State.buildSectionIndex()) return 1; std::size_t StartSymIndex = 0; if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) || !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) || !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak)) return 1; Elf_Ehdr Header; State.initELFHeader(Header); // TODO: Flesh out section header support. // TODO: Program headers. // XXX: This offset is tightly coupled with the order that we write // things to `OS`. const size_t SectionContentBeginOffset = Header.e_ehsize + Header.e_shentsize * Header.e_shnum; ContiguousBlobAccumulator CBA(SectionContentBeginOffset); // Doc might not contain .symtab, .strtab and .shstrtab sections, // but we will emit them, so make sure to add them to ShStrTabSHeader. State.DotShStrtab.add(".symtab"); State.DotShStrtab.add(".strtab"); State.DotShStrtab.add(".shstrtab"); std::vector<Elf_Shdr> SHeaders; if(!State.initSectionHeaders(SHeaders, CBA)) return 1; // .symtab section. Elf_Shdr SymtabSHeader; State.initSymtabSectionHeader(SymtabSHeader, CBA); SHeaders.push_back(SymtabSHeader); // .strtab string table header. Elf_Shdr DotStrTabSHeader; State.initStrtabSectionHeader(DotStrTabSHeader, ".strtab", State.DotStrtab, CBA); SHeaders.push_back(DotStrTabSHeader); // .shstrtab string table header. Elf_Shdr ShStrTabSHeader; State.initStrtabSectionHeader(ShStrTabSHeader, ".shstrtab", State.DotShStrtab, CBA); SHeaders.push_back(ShStrTabSHeader); OS.write((const char *)&Header, sizeof(Header)); writeArrayData(OS, makeArrayRef(SHeaders)); CBA.writeBlobToStream(OS); return 0; } static bool is64Bit(const ELFYAML::Object &Doc) { return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64); } static bool isLittleEndian(const ELFYAML::Object &Doc) { return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB); } int yaml2elf(yaml::Input &YIn, raw_ostream &Out) { ELFYAML::Object Doc; YIn >> Doc; if (YIn.error()) { errs() << "yaml2obj: Failed to parse YAML file!\n"; return 1; } using object::ELFType; typedef ELFType<support::little, true> LE64; typedef ELFType<support::big, true> BE64; typedef ELFType<support::little, false> LE32; typedef ELFType<support::big, false> BE32; if (is64Bit(Doc)) { if (isLittleEndian(Doc)) return ELFState<LE64>::writeELF(Out, Doc); else return ELFState<BE64>::writeELF(Out, Doc); } else { if (isLittleEndian(Doc)) return ELFState<LE32>::writeELF(Out, Doc); else return ELFState<BE32>::writeELF(Out, Doc); } }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/yaml2obj/yaml2obj.cpp
//===- yaml2obj - Convert YAML to a binary object file --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes a YAML description of an object file and outputs the // binary equivalent. // // This is used for writing tests that require binary files. // //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include <system_error> using namespace llvm; static cl::opt<std::string> Input(cl::Positional, cl::desc("<input>"), cl::init("-")); // TODO: The "right" way to tell what kind of object file a given YAML file // corresponds to is to look at YAML "tags" (e.g. `!Foo`). Then, different // tags (`!ELF`, `!COFF`, etc.) would be used to discriminate between them. // Interpreting the tags is needed eventually for when writing test cases, // so that we can e.g. have `!Archive` contain a sequence of `!ELF`, and // just Do The Right Thing. However, interpreting these tags and acting on // them appropriately requires some work in the YAML parser and the YAMLIO // library. enum YAMLObjectFormat { YOF_COFF, YOF_ELF }; cl::opt<YAMLObjectFormat> Format( "format", cl::desc("Interpret input as this type of object file"), cl::values( clEnumValN(YOF_COFF, "coff", "COFF object file format"), clEnumValN(YOF_ELF, "elf", "ELF object file format"), clEnumValEnd)); cl::opt<unsigned> DocNum("docnum", cl::init(1), cl::desc("Read specified document from input (default = 1)")); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); typedef int (*ConvertFuncPtr)(yaml::Input & YIn, raw_ostream &Out); static int convertYAML(yaml::Input &YIn, raw_ostream &Out, ConvertFuncPtr Convert) { unsigned CurDocNum = 0; do { if (++CurDocNum == DocNum) return Convert(YIn, Out); } while (YIn.nextDocument()); errs() << "yaml2obj: Cannot find the " << DocNum << llvm::getOrdinalSuffix(DocNum) << " document\n"; return 1; } // HLSL Change: changed calling convention to __cdecl int __cdecl main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. if (OutputFilename.empty()) OutputFilename = "-"; std::error_code EC; std::unique_ptr<tool_output_file> Out( new tool_output_file(OutputFilename, EC, sys::fs::F_None)); if (EC) { errs() << EC.message() << '\n'; return 1; } ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFileOrSTDIN(Input); if (!Buf) return 1; ConvertFuncPtr Convert = nullptr; if (Format == YOF_COFF) Convert = yaml2coff; else if (Format == YOF_ELF) Convert = yaml2elf; else { errs() << "Not yet implemented\n"; return 1; } yaml::Input YIn(Buf.get()->getBuffer()); int Res = convertYAML(YIn, Out->os(), Convert); if (Res == 0) Out->keep(); return Res; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/yaml2obj/CMakeLists.txt
set(LLVM_LINK_COMPONENTS MC Object Support ) add_llvm_tool(yaml2obj yaml2obj.cpp yaml2coff.cpp yaml2elf.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/yaml2obj/yaml2coff.cpp
//===- yaml2coff - Convert YAML to a COFF object file ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief The COFF component of yaml2obj. /// //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Object/COFF.h" #include "llvm/Object/COFFYAML.h" #include "llvm/Support/Endian.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include <vector> using namespace llvm; /// This parses a yaml stream that represents a COFF object file. /// See docs/yaml2obj for the yaml scheema. struct COFFParser { COFFParser(COFFYAML::Object &Obj) : Obj(Obj), SectionTableStart(0), SectionTableSize(0) { // A COFF string table always starts with a 4 byte size field. Offsets into // it include this size, so allocate it now. StringTable.append(4, char(0)); } bool useBigObj() const { return static_cast<int32_t>(Obj.Sections.size()) > COFF::MaxNumberOfSections16; } bool isPE() const { return Obj.OptionalHeader.hasValue(); } bool is64Bit() const { return Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64; } uint32_t getFileAlignment() const { return Obj.OptionalHeader->Header.FileAlignment; } unsigned getHeaderSize() const { return useBigObj() ? COFF::Header32Size : COFF::Header16Size; } unsigned getSymbolSize() const { return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size; } bool parseSections() { for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(), e = Obj.Sections.end(); i != e; ++i) { COFFYAML::Section &Sec = *i; // If the name is less than 8 bytes, store it in place, otherwise // store it in the string table. StringRef Name = Sec.Name; if (Name.size() <= COFF::NameSize) { std::copy(Name.begin(), Name.end(), Sec.Header.Name); } else { // Add string to the string table and format the index for output. unsigned Index = getStringIndex(Name); std::string str = utostr(Index); if (str.size() > 7) { errs() << "String table got too large"; return false; } Sec.Header.Name[0] = '/'; std::copy(str.begin(), str.end(), Sec.Header.Name + 1); } Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20; } return true; } bool parseSymbols() { for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(), e = Obj.Symbols.end(); i != e; ++i) { COFFYAML::Symbol &Sym = *i; // If the name is less than 8 bytes, store it in place, otherwise // store it in the string table. StringRef Name = Sym.Name; if (Name.size() <= COFF::NameSize) { std::copy(Name.begin(), Name.end(), Sym.Header.Name); } else { // Add string to the string table and format the index for output. unsigned Index = getStringIndex(Name); *reinterpret_cast<support::aligned_ulittle32_t*>( Sym.Header.Name + 4) = Index; } Sym.Header.Type = Sym.SimpleType; Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT; } return true; } bool parse() { if (!parseSections()) return false; if (!parseSymbols()) return false; return true; } unsigned getStringIndex(StringRef Str) { StringMap<unsigned>::iterator i = StringTableMap.find(Str); if (i == StringTableMap.end()) { unsigned Index = StringTable.size(); StringTable.append(Str.begin(), Str.end()); StringTable.push_back(0); StringTableMap[Str] = Index; return Index; } return i->second; } COFFYAML::Object &Obj; StringMap<unsigned> StringTableMap; std::string StringTable; uint32_t SectionTableStart; uint32_t SectionTableSize; }; // Take a CP and assign addresses and sizes to everything. Returns false if the // layout is not valid to do. static bool layoutOptionalHeader(COFFParser &CP) { if (!CP.isPE()) return true; unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header) : sizeof(object::pe32_header); CP.Obj.Header.SizeOfOptionalHeader = PEHeaderSize + sizeof(object::data_directory) * (COFF::NUM_DATA_DIRECTORIES + 1); return true; } namespace { enum { DOSStubSize = 128 }; } // Take a CP and assign addresses and sizes to everything. Returns false if the // layout is not valid to do. static bool layoutCOFF(COFFParser &CP) { // The section table starts immediately after the header, including the // optional header. CP.SectionTableStart = CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader; if (CP.isPE()) CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic); CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size(); uint32_t CurrentSectionDataOffset = CP.SectionTableStart + CP.SectionTableSize; // Assign each section data address consecutively. for (COFFYAML::Section &S : CP.Obj.Sections) { if (S.SectionData.binary_size() > 0) { CurrentSectionDataOffset = RoundUpToAlignment( CurrentSectionDataOffset, CP.isPE() ? CP.getFileAlignment() : 4); S.Header.SizeOfRawData = S.SectionData.binary_size(); if (CP.isPE()) S.Header.SizeOfRawData = RoundUpToAlignment(S.Header.SizeOfRawData, CP.getFileAlignment()); S.Header.PointerToRawData = CurrentSectionDataOffset; CurrentSectionDataOffset += S.Header.SizeOfRawData; if (!S.Relocations.empty()) { S.Header.PointerToRelocations = CurrentSectionDataOffset; S.Header.NumberOfRelocations = S.Relocations.size(); CurrentSectionDataOffset += S.Header.NumberOfRelocations * COFF::RelocationSize; } } else { S.Header.SizeOfRawData = 0; S.Header.PointerToRawData = 0; } } uint32_t SymbolTableStart = CurrentSectionDataOffset; // Calculate number of symbols. uint32_t NumberOfSymbols = 0; for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(), e = CP.Obj.Symbols.end(); i != e; ++i) { uint32_t NumberOfAuxSymbols = 0; if (i->FunctionDefinition) NumberOfAuxSymbols += 1; if (i->bfAndefSymbol) NumberOfAuxSymbols += 1; if (i->WeakExternal) NumberOfAuxSymbols += 1; if (!i->File.empty()) NumberOfAuxSymbols += (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize(); if (i->SectionDefinition) NumberOfAuxSymbols += 1; if (i->CLRToken) NumberOfAuxSymbols += 1; i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols; NumberOfSymbols += 1 + NumberOfAuxSymbols; } // Store all the allocated start addresses in the header. CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size(); CP.Obj.Header.NumberOfSymbols = NumberOfSymbols; if (NumberOfSymbols > 0 || CP.StringTable.size() > 4) CP.Obj.Header.PointerToSymbolTable = SymbolTableStart; else CP.Obj.Header.PointerToSymbolTable = 0; *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0]) = CP.StringTable.size(); return true; } template <typename value_type> struct binary_le_impl { value_type Value; binary_le_impl(value_type V) : Value(V) {} }; template <typename value_type> raw_ostream &operator <<( raw_ostream &OS , const binary_le_impl<value_type> &BLE) { char Buffer[sizeof(BLE.Value)]; support::endian::write<value_type, support::little, support::unaligned>( Buffer, BLE.Value); OS.write(Buffer, sizeof(BLE.Value)); return OS; } template <typename value_type> binary_le_impl<value_type> binary_le(value_type V) { return binary_le_impl<value_type>(V); } template <size_t NumBytes> struct zeros_impl {}; template <size_t NumBytes> raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) { char Buffer[NumBytes]; memset(Buffer, 0, sizeof(Buffer)); OS.write(Buffer, sizeof(Buffer)); return OS; } template <typename T> zeros_impl<sizeof(T)> zeros(const T &) { return zeros_impl<sizeof(T)>(); } struct num_zeros_impl { size_t N; num_zeros_impl(size_t N) : N(N) {} }; raw_ostream &operator<<(raw_ostream &OS, const num_zeros_impl &NZI) { for (size_t I = 0; I != NZI.N; ++I) OS.write(0); return OS; } static num_zeros_impl num_zeros(size_t N) { num_zeros_impl NZI(N); return NZI; } template <typename T> static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header) { memset(Header, 0, sizeof(*Header)); Header->Magic = Magic; Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment; Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment; uint32_t SizeOfCode = 0, SizeOfInitializedData = 0, SizeOfUninitializedData = 0; uint32_t SizeOfHeaders = RoundUpToAlignment( CP.SectionTableStart + CP.SectionTableSize, Header->FileAlignment); uint32_t SizeOfImage = RoundUpToAlignment(SizeOfHeaders, Header->SectionAlignment); uint32_t BaseOfData = 0; for (const COFFYAML::Section &S : CP.Obj.Sections) { if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE) SizeOfCode += S.Header.SizeOfRawData; if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) SizeOfInitializedData += S.Header.SizeOfRawData; if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) SizeOfUninitializedData += S.Header.SizeOfRawData; if (S.Name.equals(".text")) Header->BaseOfCode = S.Header.VirtualAddress; // RVA else if (S.Name.equals(".data")) BaseOfData = S.Header.VirtualAddress; // RVA if (S.Header.VirtualAddress) SizeOfImage += RoundUpToAlignment(S.Header.VirtualSize, Header->SectionAlignment); } Header->SizeOfCode = SizeOfCode; Header->SizeOfInitializedData = SizeOfInitializedData; Header->SizeOfUninitializedData = SizeOfUninitializedData; Header->AddressOfEntryPoint = CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase; Header->MajorOperatingSystemVersion = CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion; Header->MinorOperatingSystemVersion = CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion; Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion; Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion; Header->MajorSubsystemVersion = CP.Obj.OptionalHeader->Header.MajorSubsystemVersion; Header->MinorSubsystemVersion = CP.Obj.OptionalHeader->Header.MinorSubsystemVersion; Header->SizeOfImage = SizeOfImage; Header->SizeOfHeaders = SizeOfHeaders; Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem; Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics; Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve; Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit; Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve; Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit; Header->NumberOfRvaAndSize = COFF::NUM_DATA_DIRECTORIES + 1; return BaseOfData; } static bool writeCOFF(COFFParser &CP, raw_ostream &OS) { if (CP.isPE()) { // PE files start with a DOS stub. object::dos_header DH; memset(&DH, 0, sizeof(DH)); // DOS EXEs start with "MZ" magic. DH.Magic[0] = 'M'; DH.Magic[1] = 'Z'; // Initializing the AddressOfRelocationTable is strictly optional but // mollifies certain tools which expect it to have a value greater than // 0x40. DH.AddressOfRelocationTable = sizeof(DH); // This is the address of the PE signature. DH.AddressOfNewExeHeader = DOSStubSize; // Write out our DOS stub. OS.write(reinterpret_cast<char *>(&DH), sizeof(DH)); // Write padding until we reach the position of where our PE signature // should live. OS << num_zeros(DOSStubSize - sizeof(DH)); // Write out the PE signature. OS.write(COFF::PEMagic, sizeof(COFF::PEMagic)); } if (CP.useBigObj()) { OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN)) << binary_le(static_cast<uint16_t>(0xffff)) << binary_le(static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion)) << binary_le(CP.Obj.Header.Machine) << binary_le(CP.Obj.Header.TimeDateStamp); OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)); OS << zeros(uint32_t(0)) << zeros(uint32_t(0)) << zeros(uint32_t(0)) << zeros(uint32_t(0)) << binary_le(CP.Obj.Header.NumberOfSections) << binary_le(CP.Obj.Header.PointerToSymbolTable) << binary_le(CP.Obj.Header.NumberOfSymbols); } else { OS << binary_le(CP.Obj.Header.Machine) << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections)) << binary_le(CP.Obj.Header.TimeDateStamp) << binary_le(CP.Obj.Header.PointerToSymbolTable) << binary_le(CP.Obj.Header.NumberOfSymbols) << binary_le(CP.Obj.Header.SizeOfOptionalHeader) << binary_le(CP.Obj.Header.Characteristics); } if (CP.isPE()) { if (CP.is64Bit()) { object::pe32plus_header PEH; initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH); OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH)); } else { object::pe32_header PEH; uint32_t BaseOfData = initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH); PEH.BaseOfData = BaseOfData; OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH)); } for (const Optional<COFF::DataDirectory> &DD : CP.Obj.OptionalHeader->DataDirectories) { if (!DD.hasValue()) { OS << zeros(uint32_t(0)); OS << zeros(uint32_t(0)); } else { OS << binary_le(DD->RelativeVirtualAddress); OS << binary_le(DD->Size); } } OS << zeros(uint32_t(0)); OS << zeros(uint32_t(0)); } assert(OS.tell() == CP.SectionTableStart); // Output section table. for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(), e = CP.Obj.Sections.end(); i != e; ++i) { OS.write(i->Header.Name, COFF::NameSize); OS << binary_le(i->Header.VirtualSize) << binary_le(i->Header.VirtualAddress) << binary_le(i->Header.SizeOfRawData) << binary_le(i->Header.PointerToRawData) << binary_le(i->Header.PointerToRelocations) << binary_le(i->Header.PointerToLineNumbers) << binary_le(i->Header.NumberOfRelocations) << binary_le(i->Header.NumberOfLineNumbers) << binary_le(i->Header.Characteristics); } assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize); unsigned CurSymbol = 0; StringMap<unsigned> SymbolTableIndexMap; for (std::vector<COFFYAML::Symbol>::iterator I = CP.Obj.Symbols.begin(), E = CP.Obj.Symbols.end(); I != E; ++I) { SymbolTableIndexMap[I->Name] = CurSymbol; CurSymbol += 1 + I->Header.NumberOfAuxSymbols; } // Output section data. for (const COFFYAML::Section &S : CP.Obj.Sections) { if (!S.Header.SizeOfRawData) continue; assert(S.Header.PointerToRawData >= OS.tell()); OS << num_zeros(S.Header.PointerToRawData - OS.tell()); S.SectionData.writeAsBinary(OS); assert(S.Header.SizeOfRawData >= S.SectionData.binary_size()); OS << num_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size()); for (const COFFYAML::Relocation &R : S.Relocations) { uint32_t SymbolTableIndex = SymbolTableIndexMap[R.SymbolName]; OS << binary_le(R.VirtualAddress) << binary_le(SymbolTableIndex) << binary_le(R.Type); } } // Output symbol table. for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(), e = CP.Obj.Symbols.end(); i != e; ++i) { OS.write(i->Header.Name, COFF::NameSize); OS << binary_le(i->Header.Value); if (CP.useBigObj()) OS << binary_le(i->Header.SectionNumber); else OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber)); OS << binary_le(i->Header.Type) << binary_le(i->Header.StorageClass) << binary_le(i->Header.NumberOfAuxSymbols); if (i->FunctionDefinition) OS << binary_le(i->FunctionDefinition->TagIndex) << binary_le(i->FunctionDefinition->TotalSize) << binary_le(i->FunctionDefinition->PointerToLinenumber) << binary_le(i->FunctionDefinition->PointerToNextFunction) << zeros(i->FunctionDefinition->unused) << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size); if (i->bfAndefSymbol) OS << zeros(i->bfAndefSymbol->unused1) << binary_le(i->bfAndefSymbol->Linenumber) << zeros(i->bfAndefSymbol->unused2) << binary_le(i->bfAndefSymbol->PointerToNextFunction) << zeros(i->bfAndefSymbol->unused3) << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size); if (i->WeakExternal) OS << binary_le(i->WeakExternal->TagIndex) << binary_le(i->WeakExternal->Characteristics) << zeros(i->WeakExternal->unused) << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size); if (!i->File.empty()) { unsigned SymbolSize = CP.getSymbolSize(); uint32_t NumberOfAuxRecords = (i->File.size() + SymbolSize - 1) / SymbolSize; uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize; uint32_t NumZeros = NumberOfAuxBytes - i->File.size(); OS.write(i->File.data(), i->File.size()); OS << num_zeros(NumZeros); } if (i->SectionDefinition) OS << binary_le(i->SectionDefinition->Length) << binary_le(i->SectionDefinition->NumberOfRelocations) << binary_le(i->SectionDefinition->NumberOfLinenumbers) << binary_le(i->SectionDefinition->CheckSum) << binary_le(static_cast<int16_t>(i->SectionDefinition->Number)) << binary_le(i->SectionDefinition->Selection) << zeros(i->SectionDefinition->unused) << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16)) << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size); if (i->CLRToken) OS << binary_le(i->CLRToken->AuxType) << zeros(i->CLRToken->unused1) << binary_le(i->CLRToken->SymbolTableIndex) << zeros(i->CLRToken->unused2) << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size); } // Output string table. if (CP.Obj.Header.PointerToSymbolTable) OS.write(&CP.StringTable[0], CP.StringTable.size()); return true; } int yaml2coff(yaml::Input &YIn, raw_ostream &Out) { COFFYAML::Object Doc; YIn >> Doc; if (YIn.error()) { errs() << "yaml2obj: Failed to parse YAML file!\n"; return 1; } COFFParser CP(Doc); if (!CP.parse()) { errs() << "yaml2obj: Failed to parse YAML file!\n"; return 1; } if (!layoutOptionalHeader(CP)) { errs() << "yaml2obj: Failed to layout optional header for COFF file!\n"; return 1; } if (!layoutCOFF(CP)) { errs() << "yaml2obj: Failed to layout COFF file!\n"; return 1; } if (!writeCOFF(CP, Out)) { errs() << "yaml2obj: Failed to write COFF file!\n"; return 1; } return 0; }
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/yaml2obj/yaml2obj.h
//===--- yaml2obj.h - -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief Common declarations for yaml2obj //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_YAML2OBJ_YAML2OBJ_H #define LLVM_TOOLS_YAML2OBJ_YAML2OBJ_H namespace llvm { class raw_ostream; namespace yaml { class Input; } } int yaml2coff(llvm::yaml::Input &YIn, llvm::raw_ostream &Out); int yaml2elf(llvm::yaml::Input &YIn, llvm::raw_ostream &Out); #endif
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-extract/CMakeLists.txt
set(LLVM_LINK_COMPONENTS BitWriter Core IPO IRReader Support ) add_llvm_tool(llvm-extract llvm-extract.cpp )
0
repos/DirectXShaderCompiler/tools
repos/DirectXShaderCompiler/tools/llvm-extract/LLVMBuild.txt
;===- ./tools/llvm-extract/LLVMBuild.txt -----------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Tool name = llvm-extract parent = Tools required_libraries = AsmParser BitReader BitWriter IRReader IPO