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"
12 #include "MachOUtils.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/Object/MachO.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/WithColor.h"
17 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm::dsymutil;
22 using namespace llvm::object;
24 class MachODebugMapParser {
26 MachODebugMapParser(StringRef BinaryPath, ArrayRef<std::string> Archs,
27 StringRef PathPrefix = "",
28 bool PaperTrailWarnings = false, bool Verbose = false)
29 : BinaryPath(BinaryPath), Archs(Archs.begin(), Archs.end()),
30 PathPrefix(PathPrefix), PaperTrailWarnings(PaperTrailWarnings),
31 MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose),
32 CurrentDebugMapObject(nullptr) {}
34 /// Parses and returns the DebugMaps of the input binary. The binary contains
35 /// multiple maps in case it is a universal binary.
36 /// \returns an error in case the provided BinaryPath doesn't exist
37 /// or isn't of a supported type.
38 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> parse();
40 /// Walk the symbol table and dump it.
44 std::string BinaryPath;
45 SmallVector<StringRef, 1> Archs;
46 std::string PathPrefix;
47 bool PaperTrailWarnings;
49 /// Owns the MemoryBuffer for the main binary.
50 BinaryHolder MainBinaryHolder;
51 /// Map of the binary symbol addresses.
52 StringMap<uint64_t> MainBinarySymbolAddresses;
53 StringRef MainBinaryStrings;
54 /// The constructed DebugMap.
55 std::unique_ptr<DebugMap> Result;
57 /// Owns the MemoryBuffer for the currently handled object file.
58 BinaryHolder CurrentObjectHolder;
59 /// Map of the currently processed object file symbol addresses.
60 StringMap<Optional<uint64_t>> CurrentObjectAddresses;
61 /// Element of the debug map corresponding to the current object file.
62 DebugMapObject *CurrentDebugMapObject;
64 /// Holds function info while function scope processing.
65 const char *CurrentFunctionName;
66 uint64_t CurrentFunctionAddress;
68 std::unique_ptr<DebugMap> parseOneBinary(const MachOObjectFile &MainBinary,
69 StringRef BinaryPath);
72 switchToNewDebugMapObject(StringRef Filename,
73 sys::TimePoint<std::chrono::seconds> Timestamp);
74 void resetParserState();
75 uint64_t getMainBinarySymbolAddress(StringRef Name);
76 std::vector<StringRef> getMainBinarySymbolNames(uint64_t Value);
77 void loadMainBinarySymbols(const MachOObjectFile &MainBinary);
78 void loadCurrentObjectFileSymbols(const object::MachOObjectFile &Obj);
79 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
80 uint8_t SectionIndex, uint16_t Flags,
83 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
84 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
88 /// Dump the symbol table output header.
89 void dumpSymTabHeader(raw_ostream &OS, StringRef Arch);
91 /// Dump the contents of nlist entries.
92 void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, uint32_t StringIndex,
93 uint8_t Type, uint8_t SectionIndex, uint16_t Flags,
96 template <typename STEType>
97 void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, const STEType &STE) {
98 dumpSymTabEntry(OS, Index, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
101 void dumpOneBinaryStab(const MachOObjectFile &MainBinary,
102 StringRef BinaryPath);
104 void Warning(const Twine &Msg, StringRef File = StringRef()) {
105 WithColor::warning() << "("
106 << MachOUtils::getArchName(
107 Result->getTriple().getArchName())
108 << ") " << File << " " << Msg << "\n";
110 if (PaperTrailWarnings) {
112 Result->addDebugMapObject(File, sys::TimePoint<std::chrono::seconds>());
113 if (Result->end() != Result->begin())
114 (*--Result->end())->addWarning(Msg.str());
119 } // anonymous namespace
121 /// Reset the parser state corresponding to the current object
122 /// file. This is to be called after an object file is finished
124 void MachODebugMapParser::resetParserState() {
125 CurrentObjectAddresses.clear();
126 CurrentDebugMapObject = nullptr;
129 /// Create a new DebugMapObject. This function resets the state of the
130 /// parser that was referring to the last object file and sets
131 /// everything up to add symbols to the new one.
132 void MachODebugMapParser::switchToNewDebugMapObject(
133 StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) {
136 SmallString<80> Path(PathPrefix);
137 sys::path::append(Path, Filename);
140 CurrentObjectHolder.GetFilesAs<MachOObjectFile>(Path, Timestamp);
141 if (auto Error = MachOOrError.getError()) {
142 Warning("unable to open object file: " + Error.message(), Path.str());
147 CurrentObjectHolder.GetAs<MachOObjectFile>(Result->getTriple());
148 if (auto Error = ErrOrAchObj.getError()) {
149 Warning("unable to open object file: " + Error.message(), Path.str());
153 CurrentDebugMapObject =
154 &Result->addDebugMapObject(Path, Timestamp, MachO::N_OSO);
155 loadCurrentObjectFileSymbols(*ErrOrAchObj);
158 static std::string getArchName(const object::MachOObjectFile &Obj) {
159 Triple T = Obj.getArchTriple();
160 return T.getArchName();
163 std::unique_ptr<DebugMap>
164 MachODebugMapParser::parseOneBinary(const MachOObjectFile &MainBinary,
165 StringRef BinaryPath) {
166 loadMainBinarySymbols(MainBinary);
167 Result = make_unique<DebugMap>(MainBinary.getArchTriple(), BinaryPath);
168 MainBinaryStrings = MainBinary.getStringTableData();
169 for (const SymbolRef &Symbol : MainBinary.symbols()) {
170 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
171 if (MainBinary.is64Bit())
172 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
174 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
178 return std::move(Result);
181 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
182 // llvm-nm has very similar code, the strings used here are however slightly
183 // different and part of the interface of dsymutil (some project's build-systems
184 // parse the ouptut of dsymutil -s), thus they shouldn't be changed.
185 struct DarwinStabName {
190 static const struct DarwinStabName DarwinStabNames[] = {
191 {MachO::N_GSYM, "N_GSYM"}, {MachO::N_FNAME, "N_FNAME"},
192 {MachO::N_FUN, "N_FUN"}, {MachO::N_STSYM, "N_STSYM"},
193 {MachO::N_LCSYM, "N_LCSYM"}, {MachO::N_BNSYM, "N_BNSYM"},
194 {MachO::N_PC, "N_PC"}, {MachO::N_AST, "N_AST"},
195 {MachO::N_OPT, "N_OPT"}, {MachO::N_RSYM, "N_RSYM"},
196 {MachO::N_SLINE, "N_SLINE"}, {MachO::N_ENSYM, "N_ENSYM"},
197 {MachO::N_SSYM, "N_SSYM"}, {MachO::N_SO, "N_SO"},
198 {MachO::N_OSO, "N_OSO"}, {MachO::N_LSYM, "N_LSYM"},
199 {MachO::N_BINCL, "N_BINCL"}, {MachO::N_SOL, "N_SOL"},
200 {MachO::N_PARAMS, "N_PARAM"}, {MachO::N_VERSION, "N_VERS"},
201 {MachO::N_OLEVEL, "N_OLEV"}, {MachO::N_PSYM, "N_PSYM"},
202 {MachO::N_EINCL, "N_EINCL"}, {MachO::N_ENTRY, "N_ENTRY"},
203 {MachO::N_LBRAC, "N_LBRAC"}, {MachO::N_EXCL, "N_EXCL"},
204 {MachO::N_RBRAC, "N_RBRAC"}, {MachO::N_BCOMM, "N_BCOMM"},
205 {MachO::N_ECOMM, "N_ECOMM"}, {MachO::N_ECOML, "N_ECOML"},
206 {MachO::N_LENG, "N_LENG"}, {0, nullptr}};
208 static const char *getDarwinStabString(uint8_t NType) {
209 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
210 if (DarwinStabNames[i].NType == NType)
211 return DarwinStabNames[i].Name;
216 void MachODebugMapParser::dumpSymTabHeader(raw_ostream &OS, StringRef Arch) {
217 OS << "-----------------------------------"
218 "-----------------------------------\n";
219 OS << "Symbol table for: '" << BinaryPath << "' (" << Arch.data() << ")\n";
220 OS << "-----------------------------------"
221 "-----------------------------------\n";
222 OS << "Index n_strx n_type n_sect n_desc n_value\n";
223 OS << "======== -------- ------------------ ------ ------ ----------------\n";
226 void MachODebugMapParser::dumpSymTabEntry(raw_ostream &OS, uint64_t Index,
227 uint32_t StringIndex, uint8_t Type,
228 uint8_t SectionIndex, uint16_t Flags,
231 OS << '[' << format_decimal(Index, 6)
234 << format_hex_no_prefix(StringIndex, 8)
237 << format_hex_no_prefix(Type, 2) << " (";
239 if (Type & MachO::N_STAB)
240 OS << left_justify(getDarwinStabString(Type), 13);
242 if (Type & MachO::N_PEXT)
246 switch (Type & MachO::N_TYPE) {
247 case MachO::N_UNDF: // 0x0 undefined, n_sect == NO_SECT
250 case MachO::N_ABS: // 0x2 absolute, n_sect == NO_SECT
253 case MachO::N_SECT: // 0xe defined in section number n_sect
256 case MachO::N_PBUD: // 0xc prebound undefined (defined in a dylib)
259 case MachO::N_INDR: // 0xa indirect
263 OS << format_hex_no_prefix(Type, 2) << " ";
266 if (Type & MachO::N_EXT)
274 << format_hex_no_prefix(SectionIndex, 2)
277 << format_hex_no_prefix(Flags, 4)
280 << format_hex_no_prefix(Value, 16);
282 const char *Name = &MainBinaryStrings.data()[StringIndex];
284 OS << " '" << Name << "'";
289 void MachODebugMapParser::dumpOneBinaryStab(const MachOObjectFile &MainBinary,
290 StringRef BinaryPath) {
291 loadMainBinarySymbols(MainBinary);
292 MainBinaryStrings = MainBinary.getStringTableData();
293 raw_ostream &OS(llvm::outs());
295 dumpSymTabHeader(OS, getArchName(MainBinary));
297 for (const SymbolRef &Symbol : MainBinary.symbols()) {
298 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
299 if (MainBinary.is64Bit())
300 dumpSymTabEntry(OS, Idx, MainBinary.getSymbol64TableEntry(DRI));
302 dumpSymTabEntry(OS, Idx, MainBinary.getSymbolTableEntry(DRI));
310 static bool shouldLinkArch(SmallVectorImpl<StringRef> &Archs, StringRef Arch) {
311 if (Archs.empty() || is_contained(Archs, "all") || is_contained(Archs, "*"))
314 if (Arch.startswith("arm") && Arch != "arm64" && is_contained(Archs, "arm"))
317 SmallString<16> ArchName = Arch;
318 if (Arch.startswith("thumb"))
319 ArchName = ("arm" + Arch.substr(5)).str();
321 return is_contained(Archs, ArchName);
324 bool MachODebugMapParser::dumpStab() {
325 auto MainBinOrError =
326 MainBinaryHolder.GetFilesAs<MachOObjectFile>(BinaryPath);
327 if (auto Error = MainBinOrError.getError()) {
328 llvm::errs() << "Cannot get '" << BinaryPath
329 << "' as MachO file: " << Error.message() << "\n";
333 for (const auto *Binary : *MainBinOrError)
334 if (shouldLinkArch(Archs, Binary->getArchTriple().getArchName()))
335 dumpOneBinaryStab(*Binary, BinaryPath);
340 /// This main parsing routine tries to open the main binary and if
341 /// successful iterates over the STAB entries. The real parsing is
342 /// done in handleStabSymbolTableEntry.
343 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> MachODebugMapParser::parse() {
344 auto MainBinOrError =
345 MainBinaryHolder.GetFilesAs<MachOObjectFile>(BinaryPath);
346 if (auto Error = MainBinOrError.getError())
349 std::vector<std::unique_ptr<DebugMap>> Results;
350 for (const auto *Binary : *MainBinOrError)
351 if (shouldLinkArch(Archs, Binary->getArchTriple().getArchName()))
352 Results.push_back(parseOneBinary(*Binary, BinaryPath));
354 return std::move(Results);
357 /// Interpret the STAB entries to fill the DebugMap.
358 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
360 uint8_t SectionIndex,
363 if (!(Type & MachO::N_STAB))
366 const char *Name = &MainBinaryStrings.data()[StringIndex];
368 // An N_OSO entry represents the start of a new object file description.
369 if (Type == MachO::N_OSO)
370 return switchToNewDebugMapObject(Name, sys::toTimePoint(Value));
372 if (Type == MachO::N_AST) {
373 SmallString<80> Path(PathPrefix);
374 sys::path::append(Path, Name);
375 Result->addDebugMapObject(Path, sys::toTimePoint(Value), Type);
379 // If the last N_OSO object file wasn't found, CurrentDebugMapObject will be
380 // null. Do not update anything until we find the next valid N_OSO entry.
381 if (!CurrentDebugMapObject)
387 // This is a global variable. We need to query the main binary
388 // symbol table to find its address as it might not be in the
389 // debug map (for common symbols).
390 Value = getMainBinarySymbolAddress(Name);
393 // Functions are scopes in STABS. They have an end marker that
394 // contains the function size.
395 if (Name[0] == '\0') {
397 Value = CurrentFunctionAddress;
398 Name = CurrentFunctionName;
401 CurrentFunctionName = Name;
402 CurrentFunctionAddress = Value;
411 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
413 // If the name of a (non-static) symbol is not in the current object, we
414 // check all its aliases from the main binary.
415 if (ObjectSymIt == CurrentObjectAddresses.end() && Type != MachO::N_STSYM) {
416 for (const auto &Alias : getMainBinarySymbolNames(Value)) {
417 ObjectSymIt = CurrentObjectAddresses.find(Alias);
418 if (ObjectSymIt != CurrentObjectAddresses.end())
423 if (ObjectSymIt == CurrentObjectAddresses.end()) {
424 Warning("could not find object file symbol for symbol " + Twine(Name));
428 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
430 Warning(Twine("failed to insert symbol '") + Name + "' in the debug map.");
435 /// Load the current object file symbols into CurrentObjectAddresses.
436 void MachODebugMapParser::loadCurrentObjectFileSymbols(
437 const object::MachOObjectFile &Obj) {
438 CurrentObjectAddresses.clear();
440 for (auto Sym : Obj.symbols()) {
441 uint64_t Addr = Sym.getValue();
442 Expected<StringRef> Name = Sym.getName();
444 // TODO: Actually report errors helpfully.
445 consumeError(Name.takeError());
448 // The value of some categories of symbols isn't meaningful. For
449 // example common symbols store their size in the value field, not
450 // their address. Absolute symbols have a fixed address that can
451 // conflict with standard symbols. These symbols (especially the
452 // common ones), might still be referenced by relocations. These
453 // relocations will use the symbol itself, and won't need an
454 // object file address. The object file address field is optional
455 // in the DebugMap, leave it unassigned for these symbols.
456 if (Sym.getFlags() & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))
457 CurrentObjectAddresses[*Name] = None;
459 CurrentObjectAddresses[*Name] = Addr;
463 /// Lookup a symbol address in the main binary symbol table. The
464 /// parser only needs to query common symbols, thus not every symbol's
465 /// address is available through this function.
466 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
467 auto Sym = MainBinarySymbolAddresses.find(Name);
468 if (Sym == MainBinarySymbolAddresses.end())
473 /// Get all symbol names in the main binary for the given value.
474 std::vector<StringRef>
475 MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
476 std::vector<StringRef> Names;
477 for (const auto &Entry : MainBinarySymbolAddresses) {
478 if (Entry.second == Value)
479 Names.push_back(Entry.first());
484 /// Load the interesting main binary symbols' addresses into
485 /// MainBinarySymbolAddresses.
486 void MachODebugMapParser::loadMainBinarySymbols(
487 const MachOObjectFile &MainBinary) {
488 section_iterator Section = MainBinary.section_end();
489 MainBinarySymbolAddresses.clear();
490 for (const auto &Sym : MainBinary.symbols()) {
491 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
493 // TODO: Actually report errors helpfully.
494 consumeError(TypeOrErr.takeError());
497 SymbolRef::Type Type = *TypeOrErr;
498 // Skip undefined and STAB entries.
499 if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
501 // The only symbols of interest are the global variables. These
502 // are the only ones that need to be queried because the address
503 // of common data won't be described in the debug map. All other
504 // addresses should be fetched for the debug map.
506 MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
507 if (!(SymType & (MachO::N_EXT | MachO::N_PEXT)))
509 Expected<section_iterator> SectionOrErr = Sym.getSection();
511 // TODO: Actually report errors helpfully.
512 consumeError(SectionOrErr.takeError());
515 Section = *SectionOrErr;
516 if (Section == MainBinary.section_end() || Section->isText())
518 uint64_t Addr = Sym.getValue();
519 Expected<StringRef> NameOrErr = Sym.getName();
521 // TODO: Actually report errors helpfully.
522 consumeError(NameOrErr.takeError());
525 StringRef Name = *NameOrErr;
526 if (Name.size() == 0 || Name[0] == '\0')
528 MainBinarySymbolAddresses[Name] = Addr;
534 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
535 parseDebugMap(StringRef InputFile, ArrayRef<std::string> Archs,
536 StringRef PrependPath, bool PaperTrailWarnings, bool Verbose,
539 return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
541 MachODebugMapParser Parser(InputFile, Archs, PrependPath, PaperTrailWarnings,
543 return Parser.parse();
546 bool dumpStab(StringRef InputFile, ArrayRef<std::string> Archs,
547 StringRef PrependPath) {
548 MachODebugMapParser Parser(InputFile, Archs, PrependPath, false);
549 return Parser.dumpStab();
551 } // namespace dsymutil