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 //===----------------------------------------------------------------------===//
12 #include "llvm/Object/MachO.h"
13 #include "llvm/Support/Path.h"
14 #include "llvm/Support/raw_ostream.h"
18 using namespace llvm::dsymutil;
19 using namespace llvm::object;
21 class MachODebugMapParser {
23 MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "")
24 : BinaryPath(BinaryPath), PathPrefix(PathPrefix),
25 CurrentDebugMapObject(nullptr) {}
27 /// \brief Parses and returns the DebugMap of the input binary.
28 /// \returns an error in case the provided BinaryPath doesn't exist
29 /// or isn't of a supported type.
30 ErrorOr<std::unique_ptr<DebugMap>> parse();
33 std::string BinaryPath;
34 std::string PathPrefix;
36 /// OwningBinary constructed from the BinaryPath.
37 object::OwningBinary<object::MachOObjectFile> MainOwningBinary;
38 /// Map of the binary symbol addresses.
39 StringMap<uint64_t> MainBinarySymbolAddresses;
40 StringRef MainBinaryStrings;
41 /// The constructed DebugMap.
42 std::unique_ptr<DebugMap> Result;
44 /// Handle to the currently processed object file.
45 object::OwningBinary<object::MachOObjectFile> CurrentObjectFile;
46 /// Map of the currently processed object file symbol addresses.
47 StringMap<uint64_t> CurrentObjectAddresses;
48 /// Element of the debug map corresponfing to the current object file.
49 DebugMapObject *CurrentDebugMapObject;
51 void switchToNewDebugMapObject(StringRef Filename);
52 void resetParserState();
53 uint64_t getMainBinarySymbolAddress(StringRef Name);
54 void loadMainBinarySymbols();
55 void loadCurrentObjectFileSymbols();
56 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
57 uint8_t SectionIndex, uint16_t Flags,
60 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
61 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
66 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
69 static ErrorOr<OwningBinary<MachOObjectFile>>
70 createMachOBinary(StringRef File) {
71 auto MemBufOrErr = MemoryBuffer::getFile(File);
72 if (auto Error = MemBufOrErr.getError())
75 MemoryBufferRef BufRef = (*MemBufOrErr)->getMemBufferRef();
76 auto MachOOrErr = ObjectFile::createMachOObjectFile(BufRef);
77 if (auto Error = MachOOrErr.getError())
80 return OwningBinary<MachOObjectFile>(std::move(*MachOOrErr),
81 std::move(*MemBufOrErr));
84 /// Reset the parser state coresponding to the current object
85 /// file. This is to be called after an object file is finished
87 void MachODebugMapParser::resetParserState() {
88 CurrentObjectFile = OwningBinary<object::MachOObjectFile>();
89 CurrentObjectAddresses.clear();
90 CurrentDebugMapObject = nullptr;
93 /// Create a new DebugMapObject. This function resets the state of the
94 /// parser that was referring to the last object file and sets
95 /// everything up to add symbols to the new one.
96 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
99 SmallString<80> Path(PathPrefix);
100 sys::path::append(Path, Filename);
102 auto MachOOrError = createMachOBinary(Path);
103 if (auto Error = MachOOrError.getError()) {
104 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
105 Error.message() + "\n");
109 CurrentObjectFile = std::move(*MachOOrError);
110 loadCurrentObjectFileSymbols();
111 CurrentDebugMapObject = &Result->addDebugMapObject(Path);
114 /// This main parsing routine tries to open the main binary and if
115 /// successful iterates over the STAB entries. The real parsing is
116 /// done in handleStabSymbolTableEntry.
117 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
118 auto MainBinaryOrError = createMachOBinary(BinaryPath);
119 if (auto Error = MainBinaryOrError.getError())
122 MainOwningBinary = std::move(*MainBinaryOrError);
123 loadMainBinarySymbols();
124 Result = make_unique<DebugMap>();
125 const auto &MainBinary = *MainOwningBinary.getBinary();
126 MainBinaryStrings = MainBinary.getStringTableData();
127 for (const SymbolRef &Symbol : MainBinary.symbols()) {
128 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
129 if (MainBinary.is64Bit())
130 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
132 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
136 return std::move(Result);
139 /// Interpret the STAB entries to fill the DebugMap.
140 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
142 uint8_t SectionIndex,
145 if (!(Type & MachO::N_STAB))
148 const char *Name = &MainBinaryStrings.data()[StringIndex];
150 // An N_OSO entry represents the start of a new object file description.
151 if (Type == MachO::N_OSO)
152 return switchToNewDebugMapObject(Name);
154 // If the last N_OSO object file wasn't found,
155 // CurrentDebugMapObject will be null. Do not update anything
156 // until we find the next valid N_OSO entry.
157 if (!CurrentDebugMapObject)
162 // This is a global variable. We need to query the main binary
163 // symbol table to find its address as it might not be in the
164 // debug map (for common symbols).
165 Value = getMainBinarySymbolAddress(Name);
166 if (Value == UnknownAddressOrSize)
170 // Functions are scopes in STABS. They have an end marker that we
181 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
182 if (ObjectSymIt == CurrentObjectAddresses.end())
183 return Warning("could not find object file symbol for symbol " +
185 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
186 return Warning(Twine("failed to insert symbol '") + Name +
187 "' in the debug map.");
190 /// Load the current object file symbols into CurrentObjectAddresses.
191 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
192 CurrentObjectAddresses.clear();
193 const auto &Binary = *CurrentObjectFile.getBinary();
195 for (auto Sym : Binary.symbols()) {
198 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
201 CurrentObjectAddresses[Name] = Addr;
205 /// Lookup a symbol address in the main binary symbol table. The
206 /// parser only needs to query common symbols, thus not every symbol's
207 /// address is available through this function.
208 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
209 auto Sym = MainBinarySymbolAddresses.find(Name);
210 if (Sym == MainBinarySymbolAddresses.end())
211 return UnknownAddressOrSize;
215 /// Load the interesting main binary symbols' addresses into
216 /// MainBinarySymbolAddresses.
217 void MachODebugMapParser::loadMainBinarySymbols() {
218 const MachOObjectFile &Binary = *MainOwningBinary.getBinary();
219 section_iterator Section = Binary.section_end();
220 for (const auto &Sym : Binary.symbols()) {
221 SymbolRef::Type Type;
222 // Skip undefined and STAB entries.
223 if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
224 (Type & SymbolRef::ST_Unknown))
228 // The only symbols of interest are the global variables. These
229 // are the only ones that need to be queried because the address
230 // of common data won't be described in the debug map. All other
231 // addresses should be fetched for the debug map.
232 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
233 !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
234 Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
237 MainBinarySymbolAddresses[Name] = Addr;
243 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
244 StringRef PrependPath,
246 MachODebugMapParser Parser(InputFile, PrependPath);
247 return Parser.parse();