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) {}
26 /// \brief Parses and returns the DebugMap of the input binary.
27 /// \returns an error in case the provided BinaryPath doesn't exist
28 /// or isn't of a supported type.
29 ErrorOr<std::unique_ptr<DebugMap>> parse();
32 std::string BinaryPath;
33 std::string PathPrefix;
35 /// OwningBinary constructed from the BinaryPath.
36 object::OwningBinary<object::MachOObjectFile> MainOwningBinary;
37 /// Map of the binary symbol addresses.
38 StringMap<uint64_t> MainBinarySymbolAddresses;
39 StringRef MainBinaryStrings;
40 /// The constructed DebugMap.
41 std::unique_ptr<DebugMap> Result;
43 /// Handle to the currently processed object file.
44 object::OwningBinary<object::MachOObjectFile> CurrentObjectFile;
45 /// Map of the currently processed object file symbol addresses.
46 StringMap<uint64_t> CurrentObjectAddresses;
47 /// Element of the debug map corresponfing to the current object file.
48 DebugMapObject *CurrentDebugMapObject;
50 void switchToNewDebugMapObject(StringRef Filename);
51 void resetParserState();
52 uint64_t getMainBinarySymbolAddress(StringRef Name);
53 void loadMainBinarySymbols();
54 void loadCurrentObjectFileSymbols();
55 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
56 uint8_t SectionIndex, uint16_t Flags,
59 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
60 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
65 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
68 static ErrorOr<OwningBinary<MachOObjectFile>>
69 createMachOBinary(StringRef File) {
70 auto MemBufOrErr = MemoryBuffer::getFile(File);
71 if (auto Error = MemBufOrErr.getError())
74 MemoryBufferRef BufRef = (*MemBufOrErr)->getMemBufferRef();
75 auto MachOOrErr = ObjectFile::createMachOObjectFile(BufRef);
76 if (auto Error = MachOOrErr.getError())
79 return OwningBinary<MachOObjectFile>(std::move(*MachOOrErr),
80 std::move(*MemBufOrErr));
83 /// Reset the parser state coresponding to the current object
84 /// file. This is to be called after an object file is finished
86 void MachODebugMapParser::resetParserState() {
87 CurrentObjectFile = OwningBinary<object::MachOObjectFile>();
88 CurrentObjectAddresses.clear();
89 CurrentDebugMapObject = nullptr;
92 /// Create a new DebugMapObject. This function resets the state of the
93 /// parser that was referring to the last object file and sets
94 /// everything up to add symbols to the new one.
95 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
98 SmallString<80> Path(PathPrefix);
99 sys::path::append(Path, Filename);
101 auto MachOOrError = createMachOBinary(Path);
102 if (auto Error = MachOOrError.getError()) {
103 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
104 Error.message() + "\n");
108 CurrentObjectFile = std::move(*MachOOrError);
109 loadCurrentObjectFileSymbols();
110 CurrentDebugMapObject = &Result->addDebugMapObject(Path);
113 /// This main parsing routine tries to open the main binary and if
114 /// successful iterates over the STAB entries. The real parsing is
115 /// done in handleStabSymbolTableEntry.
116 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
117 auto MainBinaryOrError = createMachOBinary(BinaryPath);
118 if (auto Error = MainBinaryOrError.getError())
121 MainOwningBinary = std::move(*MainBinaryOrError);
122 loadMainBinarySymbols();
123 Result = make_unique<DebugMap>();
124 const auto &MainBinary = *MainOwningBinary.getBinary();
125 MainBinaryStrings = MainBinary.getStringTableData();
126 for (const SymbolRef &Symbol : MainBinary.symbols()) {
127 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
128 if (MainBinary.is64Bit())
129 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
131 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
135 return std::move(Result);
138 /// Interpret the STAB entries to fill the DebugMap.
139 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
141 uint8_t SectionIndex,
144 if (!(Type & MachO::N_STAB))
147 const char *Name = &MainBinaryStrings.data()[StringIndex];
149 // An N_OSO entry represents the start of a new object file description.
150 if (Type == MachO::N_OSO)
151 return switchToNewDebugMapObject(Name);
153 // If the last N_OSO object file wasn't found,
154 // CurrentDebugMapObject will be null. Do not update anything
155 // until we find the next valid N_OSO entry.
156 if (!CurrentDebugMapObject)
161 // This is a global variable. We need to query the main binary
162 // symbol table to find its address as it might not be in the
163 // debug map (for common symbols).
164 Value = getMainBinarySymbolAddress(Name);
165 if (Value == UnknownAddressOrSize)
169 // Functions are scopes in STABS. They have an end marker that we
180 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
181 if (ObjectSymIt == CurrentObjectAddresses.end())
182 return Warning("could not find object file symbol for symbol " +
184 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
185 return Warning(Twine("failed to insert symbol '") + Name +
186 "' in the debug map.");
189 /// Load the current object file symbols into CurrentObjectAddresses.
190 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
191 CurrentObjectAddresses.clear();
192 const auto &Binary = *CurrentObjectFile.getBinary();
194 for (auto Sym : Binary.symbols()) {
197 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
200 CurrentObjectAddresses[Name] = Addr;
204 /// Lookup a symbol address in the main binary symbol table. The
205 /// parser only needs to query common symbols, thus not every symbol's
206 /// address is available through this function.
207 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
208 auto Sym = MainBinarySymbolAddresses.find(Name);
209 if (Sym == MainBinarySymbolAddresses.end())
210 return UnknownAddressOrSize;
214 /// Load the interesting main binary symbols' addresses into
215 /// MainBinarySymbolAddresses.
216 void MachODebugMapParser::loadMainBinarySymbols() {
217 const MachOObjectFile &Binary = *MainOwningBinary.getBinary();
218 section_iterator Section = Binary.section_end();
219 for (const auto &Sym : Binary.symbols()) {
220 SymbolRef::Type Type;
221 // Skip undefined and STAB entries.
222 if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
223 (Type & SymbolRef::ST_Unknown))
227 // The only symbols of interest are the global variables. These
228 // are the only ones that need to be queried because the address
229 // of common data won't be described in the debug map. All other
230 // addresses should be fetched for the debug map.
231 if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
232 !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
233 Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
236 MainBinarySymbolAddresses[Name] = Addr;
242 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
243 StringRef PrependPath) {
244 MachODebugMapParser Parser(InputFile, PrependPath);
245 return Parser.parse();