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) {}
29 /// \brief Parses and returns the DebugMap of the input binary.
30 /// \returns an error in case the provided BinaryPath doesn't exist
31 /// or isn't of a supported type.
32 ErrorOr<std::unique_ptr<DebugMap>> parse();
35 std::string BinaryPath;
36 std::string PathPrefix;
38 /// Owns the MemoryBuffer for the main binary.
39 BinaryHolder MainBinaryHolder;
40 /// Map of the binary symbol addresses.
41 StringMap<uint64_t> MainBinarySymbolAddresses;
42 StringRef MainBinaryStrings;
43 /// The constructed DebugMap.
44 std::unique_ptr<DebugMap> Result;
46 /// Owns the MemoryBuffer for the currently handled object file.
47 BinaryHolder CurrentObjectHolder;
48 /// Map of the currently processed object file symbol addresses.
49 StringMap<uint64_t> CurrentObjectAddresses;
50 /// Element of the debug map corresponfing to the current object file.
51 DebugMapObject *CurrentDebugMapObject;
53 void switchToNewDebugMapObject(StringRef Filename);
54 void resetParserState();
55 uint64_t getMainBinarySymbolAddress(StringRef Name);
56 void loadMainBinarySymbols();
57 void loadCurrentObjectFileSymbols();
58 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
59 uint8_t SectionIndex, uint16_t Flags,
62 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
63 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
68 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
71 /// Reset the parser state coresponding to the current object
72 /// file. This is to be called after an object file is finished
74 void MachODebugMapParser::resetParserState() {
75 CurrentObjectAddresses.clear();
76 CurrentDebugMapObject = nullptr;
79 /// Create a new DebugMapObject. This function resets the state of the
80 /// parser that was referring to the last object file and sets
81 /// everything up to add symbols to the new one.
82 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
85 SmallString<80> Path(PathPrefix);
86 sys::path::append(Path, Filename);
88 auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
89 if (auto Error = MachOOrError.getError()) {
90 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
91 Error.message() + "\n");
95 loadCurrentObjectFileSymbols();
96 CurrentDebugMapObject = &Result->addDebugMapObject(Path);
99 /// This main parsing routine tries to open the main binary and if
100 /// successful iterates over the STAB entries. The real parsing is
101 /// done in handleStabSymbolTableEntry.
102 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
103 auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
104 if (auto Error = MainBinOrError.getError())
107 const MachOObjectFile &MainBinary = *MainBinOrError;
108 loadMainBinarySymbols();
109 Result = make_unique<DebugMap>();
110 MainBinaryStrings = MainBinary.getStringTableData();
111 for (const SymbolRef &Symbol : MainBinary.symbols()) {
112 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
113 if (MainBinary.is64Bit())
114 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
116 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
120 return std::move(Result);
123 /// Interpret the STAB entries to fill the DebugMap.
124 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
126 uint8_t SectionIndex,
129 if (!(Type & MachO::N_STAB))
132 const char *Name = &MainBinaryStrings.data()[StringIndex];
134 // An N_OSO entry represents the start of a new object file description.
135 if (Type == MachO::N_OSO)
136 return switchToNewDebugMapObject(Name);
138 // If the last N_OSO object file wasn't found,
139 // CurrentDebugMapObject will be null. Do not update anything
140 // until we find the next valid N_OSO entry.
141 if (!CurrentDebugMapObject)
146 // This is a global variable. We need to query the main binary
147 // symbol table to find its address as it might not be in the
148 // debug map (for common symbols).
149 Value = getMainBinarySymbolAddress(Name);
150 if (Value == UnknownAddressOrSize)
154 // Functions are scopes in STABS. They have an end marker that we
165 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
166 if (ObjectSymIt == CurrentObjectAddresses.end())
167 return Warning("could not find object file symbol for symbol " +
169 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
170 return Warning(Twine("failed to insert symbol '") + Name +
171 "' in the debug map.");
174 /// Load the current object file symbols into CurrentObjectAddresses.
175 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
176 CurrentObjectAddresses.clear();
178 for (auto Sym : CurrentObjectHolder.Get().symbols()) {
181 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
184 CurrentObjectAddresses[Name] = Addr;
188 /// Lookup a symbol address in the main binary symbol table. The
189 /// parser only needs to query common symbols, thus not every symbol's
190 /// address is available through this function.
191 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
192 auto Sym = MainBinarySymbolAddresses.find(Name);
193 if (Sym == MainBinarySymbolAddresses.end())
194 return UnknownAddressOrSize;
198 /// Load the interesting main binary symbols' addresses into
199 /// MainBinarySymbolAddresses.
200 void MachODebugMapParser::loadMainBinarySymbols() {
201 const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
202 section_iterator Section = MainBinary.section_end();
203 for (const auto &Sym : MainBinary.symbols()) {
204 SymbolRef::Type Type;
205 // Skip undefined and STAB entries.
206 if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
207 (Type & SymbolRef::ST_Unknown))
211 // The only symbols of interest are the global variables. These
212 // are the only ones that need to be queried because the address
213 // of common data won't be described in the debug map. All other
214 // addresses should be fetched for the debug map.
215 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
216 !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
217 Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
220 MainBinarySymbolAddresses[Name] = Addr;
226 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
227 StringRef PrependPath,
229 MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
230 return Parser.parse();