1 //===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "llvm/Object/MachO.h"
14 #include "llvm/Support/Path.h"
15 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm::dsymutil;
20 using namespace llvm::object;
22 class MachODebugMapParser {
24 MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "",
26 : BinaryPath(BinaryPath), PathPrefix(PathPrefix),
27 MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose),
28 CurrentDebugMapObject(nullptr) {}
30 /// \brief Parses and returns the DebugMap of the input binary.
31 /// \returns an error in case the provided BinaryPath doesn't exist
32 /// or isn't of a supported type.
33 ErrorOr<std::unique_ptr<DebugMap>> parse();
36 std::string BinaryPath;
37 std::string PathPrefix;
39 /// Owns the MemoryBuffer for the main binary.
40 BinaryHolder MainBinaryHolder;
41 /// Map of the binary symbol addresses.
42 StringMap<uint64_t> MainBinarySymbolAddresses;
43 StringRef MainBinaryStrings;
44 /// The constructed DebugMap.
45 std::unique_ptr<DebugMap> Result;
47 /// Owns the MemoryBuffer for the currently handled object file.
48 BinaryHolder CurrentObjectHolder;
49 /// Map of the currently processed object file symbol addresses.
50 StringMap<uint64_t> CurrentObjectAddresses;
51 /// Element of the debug map corresponfing to the current object file.
52 DebugMapObject *CurrentDebugMapObject;
54 void switchToNewDebugMapObject(StringRef Filename);
55 void resetParserState();
56 uint64_t getMainBinarySymbolAddress(StringRef Name);
57 void loadMainBinarySymbols();
58 void loadCurrentObjectFileSymbols();
59 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
60 uint8_t SectionIndex, uint16_t Flags,
63 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
64 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
69 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
72 /// Reset the parser state coresponding to the current object
73 /// file. This is to be called after an object file is finished
75 void MachODebugMapParser::resetParserState() {
76 CurrentObjectAddresses.clear();
77 CurrentDebugMapObject = nullptr;
80 /// Create a new DebugMapObject. This function resets the state of the
81 /// parser that was referring to the last object file and sets
82 /// everything up to add symbols to the new one.
83 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
86 SmallString<80> Path(PathPrefix);
87 sys::path::append(Path, Filename);
89 auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
90 if (auto Error = MachOOrError.getError()) {
91 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
92 Error.message() + "\n");
96 loadCurrentObjectFileSymbols();
97 CurrentDebugMapObject = &Result->addDebugMapObject(Path);
100 static Triple getTriple(const object::MachOObjectFile &Obj) {
101 Triple TheTriple("unknown-unknown-unknown");
102 TheTriple.setArch(Triple::ArchType(Obj.getArch()));
103 TheTriple.setObjectFormat(Triple::MachO);
107 /// This main parsing routine tries to open the main binary and if
108 /// successful iterates over the STAB entries. The real parsing is
109 /// done in handleStabSymbolTableEntry.
110 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
111 auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
112 if (auto Error = MainBinOrError.getError())
115 const MachOObjectFile &MainBinary = *MainBinOrError;
116 loadMainBinarySymbols();
117 Result = make_unique<DebugMap>(getTriple(MainBinary));
118 MainBinaryStrings = MainBinary.getStringTableData();
119 for (const SymbolRef &Symbol : MainBinary.symbols()) {
120 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
121 if (MainBinary.is64Bit())
122 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
124 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
128 return std::move(Result);
131 /// Interpret the STAB entries to fill the DebugMap.
132 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
134 uint8_t SectionIndex,
137 if (!(Type & MachO::N_STAB))
140 const char *Name = &MainBinaryStrings.data()[StringIndex];
142 // An N_OSO entry represents the start of a new object file description.
143 if (Type == MachO::N_OSO)
144 return switchToNewDebugMapObject(Name);
146 // If the last N_OSO object file wasn't found,
147 // CurrentDebugMapObject will be null. Do not update anything
148 // until we find the next valid N_OSO entry.
149 if (!CurrentDebugMapObject)
154 // This is a global variable. We need to query the main binary
155 // symbol table to find its address as it might not be in the
156 // debug map (for common symbols).
157 Value = getMainBinarySymbolAddress(Name);
158 if (Value == UnknownAddressOrSize)
162 // Functions are scopes in STABS. They have an end marker that we
173 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
174 if (ObjectSymIt == CurrentObjectAddresses.end())
175 return Warning("could not find object file symbol for symbol " +
177 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
178 return Warning(Twine("failed to insert symbol '") + Name +
179 "' in the debug map.");
182 /// Load the current object file symbols into CurrentObjectAddresses.
183 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
184 CurrentObjectAddresses.clear();
186 for (auto Sym : CurrentObjectHolder.Get().symbols()) {
189 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
192 CurrentObjectAddresses[Name] = Addr;
196 /// Lookup a symbol address in the main binary symbol table. The
197 /// parser only needs to query common symbols, thus not every symbol's
198 /// address is available through this function.
199 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
200 auto Sym = MainBinarySymbolAddresses.find(Name);
201 if (Sym == MainBinarySymbolAddresses.end())
202 return UnknownAddressOrSize;
206 /// Load the interesting main binary symbols' addresses into
207 /// MainBinarySymbolAddresses.
208 void MachODebugMapParser::loadMainBinarySymbols() {
209 const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
210 section_iterator Section = MainBinary.section_end();
211 for (const auto &Sym : MainBinary.symbols()) {
212 SymbolRef::Type Type;
213 // Skip undefined and STAB entries.
214 if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
215 (Type & SymbolRef::ST_Unknown))
219 // The only symbols of interest are the global variables. These
220 // are the only ones that need to be queried because the address
221 // of common data won't be described in the debug map. All other
222 // addresses should be fetched for the debug map.
223 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
224 !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
225 Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
228 MainBinarySymbolAddresses[Name] = Addr;
234 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
235 StringRef PrependPath,
237 MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
238 return Parser.parse();