Home | History | Annotate | Line # | Download | only in dsymutil
      1 //===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 
      9 #include "BinaryHolder.h"
     10 #include "DebugMap.h"
     11 #include "MachOUtils.h"
     12 #include "llvm/ADT/Optional.h"
     13 #include "llvm/Object/MachO.h"
     14 #include "llvm/Support/Path.h"
     15 #include "llvm/Support/WithColor.h"
     16 #include "llvm/Support/raw_ostream.h"
     17 #include <vector>
     18 
     19 namespace {
     20 using namespace llvm;
     21 using namespace llvm::dsymutil;
     22 using namespace llvm::object;
     23 
     24 class MachODebugMapParser {
     25 public:
     26   MachODebugMapParser(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
     27                       StringRef BinaryPath, ArrayRef<std::string> Archs,
     28                       StringRef PathPrefix = "",
     29                       bool PaperTrailWarnings = false, bool Verbose = false)
     30       : BinaryPath(std::string(BinaryPath)), Archs(Archs.begin(), Archs.end()),
     31         PathPrefix(std::string(PathPrefix)),
     32         PaperTrailWarnings(PaperTrailWarnings), BinHolder(VFS, Verbose),
     33         CurrentDebugMapObject(nullptr) {}
     34 
     35   /// Parses and returns the DebugMaps of the input binary. The binary contains
     36   /// multiple maps in case it is a universal binary.
     37   /// \returns an error in case the provided BinaryPath doesn't exist
     38   /// or isn't of a supported type.
     39   ErrorOr<std::vector<std::unique_ptr<DebugMap>>> parse();
     40 
     41   /// Walk the symbol table and dump it.
     42   bool dumpStab();
     43 
     44 private:
     45   std::string BinaryPath;
     46   SmallVector<StringRef, 1> Archs;
     47   std::string PathPrefix;
     48   bool PaperTrailWarnings;
     49 
     50   /// Owns the MemoryBuffer for the main binary.
     51   BinaryHolder BinHolder;
     52   /// Map of the binary symbol addresses.
     53   StringMap<uint64_t> MainBinarySymbolAddresses;
     54   StringRef MainBinaryStrings;
     55   /// The constructed DebugMap.
     56   std::unique_ptr<DebugMap> Result;
     57   /// List of common symbols that need to be added to the debug map.
     58   std::vector<std::string> CommonSymbols;
     59 
     60   /// Map of the currently processed object file symbol addresses.
     61   StringMap<Optional<uint64_t>> CurrentObjectAddresses;
     62   /// Element of the debug map corresponding to the current object file.
     63   DebugMapObject *CurrentDebugMapObject;
     64 
     65   /// Holds function info while function scope processing.
     66   const char *CurrentFunctionName;
     67   uint64_t CurrentFunctionAddress;
     68 
     69   std::unique_ptr<DebugMap> parseOneBinary(const MachOObjectFile &MainBinary,
     70                                            StringRef BinaryPath);
     71 
     72   void
     73   switchToNewDebugMapObject(StringRef Filename,
     74                             sys::TimePoint<std::chrono::seconds> Timestamp);
     75   void resetParserState();
     76   uint64_t getMainBinarySymbolAddress(StringRef Name);
     77   std::vector<StringRef> getMainBinarySymbolNames(uint64_t Value);
     78   void loadMainBinarySymbols(const MachOObjectFile &MainBinary);
     79   void loadCurrentObjectFileSymbols(const object::MachOObjectFile &Obj);
     80   void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
     81                                   uint8_t SectionIndex, uint16_t Flags,
     82                                   uint64_t Value);
     83 
     84   template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
     85     handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
     86                                STE.n_value);
     87   }
     88 
     89   void addCommonSymbols();
     90 
     91   /// Dump the symbol table output header.
     92   void dumpSymTabHeader(raw_ostream &OS, StringRef Arch);
     93 
     94   /// Dump the contents of nlist entries.
     95   void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, uint32_t StringIndex,
     96                        uint8_t Type, uint8_t SectionIndex, uint16_t Flags,
     97                        uint64_t Value);
     98 
     99   template <typename STEType>
    100   void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, const STEType &STE) {
    101     dumpSymTabEntry(OS, Index, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
    102                     STE.n_value);
    103   }
    104   void dumpOneBinaryStab(const MachOObjectFile &MainBinary,
    105                          StringRef BinaryPath);
    106 
    107   void Warning(const Twine &Msg, StringRef File = StringRef()) {
    108     WithColor::warning() << "("
    109                          << MachOUtils::getArchName(
    110                                 Result->getTriple().getArchName())
    111                          << ") " << File << " " << Msg << "\n";
    112 
    113     if (PaperTrailWarnings) {
    114       if (!File.empty())
    115         Result->addDebugMapObject(File, sys::TimePoint<std::chrono::seconds>());
    116       if (Result->end() != Result->begin())
    117         (*--Result->end())->addWarning(Msg.str());
    118     }
    119   }
    120 };
    121 
    122 } // anonymous namespace
    123 
    124 /// Reset the parser state corresponding to the current object
    125 /// file. This is to be called after an object file is finished
    126 /// processing.
    127 void MachODebugMapParser::resetParserState() {
    128   CommonSymbols.clear();
    129   CurrentObjectAddresses.clear();
    130   CurrentDebugMapObject = nullptr;
    131 }
    132 
    133 /// Commons symbols won't show up in the symbol map but might need to be
    134 /// relocated. We can add them to the symbol table ourselves by combining the
    135 /// information in the object file (the symbol name) and the main binary (the
    136 /// address).
    137 void MachODebugMapParser::addCommonSymbols() {
    138   for (auto &CommonSymbol : CommonSymbols) {
    139     uint64_t CommonAddr = getMainBinarySymbolAddress(CommonSymbol);
    140     if (CommonAddr == 0) {
    141       // The main binary doesn't have an address for the given symbol.
    142       continue;
    143     }
    144     if (!CurrentDebugMapObject->addSymbol(CommonSymbol, None /*ObjectAddress*/,
    145                                           CommonAddr, 0 /*size*/)) {
    146       // The symbol is already present.
    147       continue;
    148     }
    149   }
    150 }
    151 
    152 /// Create a new DebugMapObject. This function resets the state of the
    153 /// parser that was referring to the last object file and sets
    154 /// everything up to add symbols to the new one.
    155 void MachODebugMapParser::switchToNewDebugMapObject(
    156     StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) {
    157   addCommonSymbols();
    158   resetParserState();
    159 
    160   SmallString<80> Path(PathPrefix);
    161   sys::path::append(Path, Filename);
    162 
    163   auto ObjectEntry = BinHolder.getObjectEntry(Path, Timestamp);
    164   if (!ObjectEntry) {
    165     auto Err = ObjectEntry.takeError();
    166     Warning("unable to open object file: " + toString(std::move(Err)),
    167             Path.str());
    168     return;
    169   }
    170 
    171   auto Object = ObjectEntry->getObjectAs<MachOObjectFile>(Result->getTriple());
    172   if (!Object) {
    173     auto Err = Object.takeError();
    174     Warning("unable to open object file: " + toString(std::move(Err)),
    175             Path.str());
    176     return;
    177   }
    178 
    179   CurrentDebugMapObject =
    180       &Result->addDebugMapObject(Path, Timestamp, MachO::N_OSO);
    181   loadCurrentObjectFileSymbols(*Object);
    182 }
    183 
    184 static std::string getArchName(const object::MachOObjectFile &Obj) {
    185   Triple T = Obj.getArchTriple();
    186   return std::string(T.getArchName());
    187 }
    188 
    189 std::unique_ptr<DebugMap>
    190 MachODebugMapParser::parseOneBinary(const MachOObjectFile &MainBinary,
    191                                     StringRef BinaryPath) {
    192   loadMainBinarySymbols(MainBinary);
    193   ArrayRef<uint8_t> UUID = MainBinary.getUuid();
    194   Result =
    195       std::make_unique<DebugMap>(MainBinary.getArchTriple(), BinaryPath, UUID);
    196   MainBinaryStrings = MainBinary.getStringTableData();
    197   for (const SymbolRef &Symbol : MainBinary.symbols()) {
    198     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
    199     if (MainBinary.is64Bit())
    200       handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
    201     else
    202       handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
    203   }
    204 
    205   resetParserState();
    206   return std::move(Result);
    207 }
    208 
    209 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
    210 // llvm-nm has very similar code, the strings used here are however slightly
    211 // different and part of the interface of dsymutil (some project's build-systems
    212 // parse the ouptut of dsymutil -s), thus they shouldn't be changed.
    213 struct DarwinStabName {
    214   uint8_t NType;
    215   const char *Name;
    216 };
    217 
    218 static const struct DarwinStabName DarwinStabNames[] = {
    219     {MachO::N_GSYM, "N_GSYM"},    {MachO::N_FNAME, "N_FNAME"},
    220     {MachO::N_FUN, "N_FUN"},      {MachO::N_STSYM, "N_STSYM"},
    221     {MachO::N_LCSYM, "N_LCSYM"},  {MachO::N_BNSYM, "N_BNSYM"},
    222     {MachO::N_PC, "N_PC"},        {MachO::N_AST, "N_AST"},
    223     {MachO::N_OPT, "N_OPT"},      {MachO::N_RSYM, "N_RSYM"},
    224     {MachO::N_SLINE, "N_SLINE"},  {MachO::N_ENSYM, "N_ENSYM"},
    225     {MachO::N_SSYM, "N_SSYM"},    {MachO::N_SO, "N_SO"},
    226     {MachO::N_OSO, "N_OSO"},      {MachO::N_LSYM, "N_LSYM"},
    227     {MachO::N_BINCL, "N_BINCL"},  {MachO::N_SOL, "N_SOL"},
    228     {MachO::N_PARAMS, "N_PARAM"}, {MachO::N_VERSION, "N_VERS"},
    229     {MachO::N_OLEVEL, "N_OLEV"},  {MachO::N_PSYM, "N_PSYM"},
    230     {MachO::N_EINCL, "N_EINCL"},  {MachO::N_ENTRY, "N_ENTRY"},
    231     {MachO::N_LBRAC, "N_LBRAC"},  {MachO::N_EXCL, "N_EXCL"},
    232     {MachO::N_RBRAC, "N_RBRAC"},  {MachO::N_BCOMM, "N_BCOMM"},
    233     {MachO::N_ECOMM, "N_ECOMM"},  {MachO::N_ECOML, "N_ECOML"},
    234     {MachO::N_LENG, "N_LENG"},    {0, nullptr}};
    235 
    236 static const char *getDarwinStabString(uint8_t NType) {
    237   for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
    238     if (DarwinStabNames[i].NType == NType)
    239       return DarwinStabNames[i].Name;
    240   }
    241   return nullptr;
    242 }
    243 
    244 void MachODebugMapParser::dumpSymTabHeader(raw_ostream &OS, StringRef Arch) {
    245   OS << "-----------------------------------"
    246         "-----------------------------------\n";
    247   OS << "Symbol table for: '" << BinaryPath << "' (" << Arch.data() << ")\n";
    248   OS << "-----------------------------------"
    249         "-----------------------------------\n";
    250   OS << "Index    n_strx   n_type             n_sect n_desc n_value\n";
    251   OS << "======== -------- ------------------ ------ ------ ----------------\n";
    252 }
    253 
    254 void MachODebugMapParser::dumpSymTabEntry(raw_ostream &OS, uint64_t Index,
    255                                           uint32_t StringIndex, uint8_t Type,
    256                                           uint8_t SectionIndex, uint16_t Flags,
    257                                           uint64_t Value) {
    258   // Index
    259   OS << '[' << format_decimal(Index, 6)
    260      << "] "
    261      // n_strx
    262      << format_hex_no_prefix(StringIndex, 8)
    263      << ' '
    264      // n_type...
    265      << format_hex_no_prefix(Type, 2) << " (";
    266 
    267   if (Type & MachO::N_STAB)
    268     OS << left_justify(getDarwinStabString(Type), 13);
    269   else {
    270     if (Type & MachO::N_PEXT)
    271       OS << "PEXT ";
    272     else
    273       OS << "     ";
    274     switch (Type & MachO::N_TYPE) {
    275     case MachO::N_UNDF: // 0x0 undefined, n_sect == NO_SECT
    276       OS << "UNDF";
    277       break;
    278     case MachO::N_ABS: // 0x2 absolute, n_sect == NO_SECT
    279       OS << "ABS ";
    280       break;
    281     case MachO::N_SECT: // 0xe defined in section number n_sect
    282       OS << "SECT";
    283       break;
    284     case MachO::N_PBUD: // 0xc prebound undefined (defined in a dylib)
    285       OS << "PBUD";
    286       break;
    287     case MachO::N_INDR: // 0xa indirect
    288       OS << "INDR";
    289       break;
    290     default:
    291       OS << format_hex_no_prefix(Type, 2) << "    ";
    292       break;
    293     }
    294     if (Type & MachO::N_EXT)
    295       OS << " EXT";
    296     else
    297       OS << "    ";
    298   }
    299 
    300   OS << ") "
    301      // n_sect
    302      << format_hex_no_prefix(SectionIndex, 2)
    303      << "     "
    304      // n_desc
    305      << format_hex_no_prefix(Flags, 4)
    306      << "   "
    307      // n_value
    308      << format_hex_no_prefix(Value, 16);
    309 
    310   const char *Name = &MainBinaryStrings.data()[StringIndex];
    311   if (Name && Name[0])
    312     OS << " '" << Name << "'";
    313 
    314   OS << "\n";
    315 }
    316 
    317 void MachODebugMapParser::dumpOneBinaryStab(const MachOObjectFile &MainBinary,
    318                                             StringRef BinaryPath) {
    319   loadMainBinarySymbols(MainBinary);
    320   MainBinaryStrings = MainBinary.getStringTableData();
    321   raw_ostream &OS(llvm::outs());
    322 
    323   dumpSymTabHeader(OS, getArchName(MainBinary));
    324   uint64_t Idx = 0;
    325   for (const SymbolRef &Symbol : MainBinary.symbols()) {
    326     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
    327     if (MainBinary.is64Bit())
    328       dumpSymTabEntry(OS, Idx, MainBinary.getSymbol64TableEntry(DRI));
    329     else
    330       dumpSymTabEntry(OS, Idx, MainBinary.getSymbolTableEntry(DRI));
    331     Idx++;
    332   }
    333 
    334   OS << "\n\n";
    335   resetParserState();
    336 }
    337 
    338 static bool shouldLinkArch(SmallVectorImpl<StringRef> &Archs, StringRef Arch) {
    339   if (Archs.empty() || is_contained(Archs, "all") || is_contained(Archs, "*"))
    340     return true;
    341 
    342   if (Arch.startswith("arm") && Arch != "arm64" && is_contained(Archs, "arm"))
    343     return true;
    344 
    345   SmallString<16> ArchName = Arch;
    346   if (Arch.startswith("thumb"))
    347     ArchName = ("arm" + Arch.substr(5)).str();
    348 
    349   return is_contained(Archs, ArchName);
    350 }
    351 
    352 bool MachODebugMapParser::dumpStab() {
    353   auto ObjectEntry = BinHolder.getObjectEntry(BinaryPath);
    354   if (!ObjectEntry) {
    355     auto Err = ObjectEntry.takeError();
    356     WithColor::error() << "cannot load '" << BinaryPath
    357                        << "': " << toString(std::move(Err)) << '\n';
    358     return false;
    359   }
    360 
    361   auto Objects = ObjectEntry->getObjectsAs<MachOObjectFile>();
    362   if (!Objects) {
    363     auto Err = Objects.takeError();
    364     WithColor::error() << "cannot get '" << BinaryPath
    365                        << "' as MachO file: " << toString(std::move(Err))
    366                        << "\n";
    367     return false;
    368   }
    369 
    370   for (const auto *Object : *Objects)
    371     if (shouldLinkArch(Archs, Object->getArchTriple().getArchName()))
    372       dumpOneBinaryStab(*Object, BinaryPath);
    373 
    374   return true;
    375 }
    376 
    377 /// This main parsing routine tries to open the main binary and if
    378 /// successful iterates over the STAB entries. The real parsing is
    379 /// done in handleStabSymbolTableEntry.
    380 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> MachODebugMapParser::parse() {
    381   auto ObjectEntry = BinHolder.getObjectEntry(BinaryPath);
    382   if (!ObjectEntry) {
    383     return errorToErrorCode(ObjectEntry.takeError());
    384   }
    385 
    386   auto Objects = ObjectEntry->getObjectsAs<MachOObjectFile>();
    387   if (!Objects) {
    388     return errorToErrorCode(Objects.takeError());
    389   }
    390 
    391   std::vector<std::unique_ptr<DebugMap>> Results;
    392   for (const auto *Object : *Objects)
    393     if (shouldLinkArch(Archs, Object->getArchTriple().getArchName()))
    394       Results.push_back(parseOneBinary(*Object, BinaryPath));
    395 
    396   return std::move(Results);
    397 }
    398 
    399 /// Interpret the STAB entries to fill the DebugMap.
    400 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
    401                                                      uint8_t Type,
    402                                                      uint8_t SectionIndex,
    403                                                      uint16_t Flags,
    404                                                      uint64_t Value) {
    405   if (!(Type & MachO::N_STAB))
    406     return;
    407 
    408   const char *Name = &MainBinaryStrings.data()[StringIndex];
    409 
    410   // An N_OSO entry represents the start of a new object file description.
    411   if (Type == MachO::N_OSO)
    412     return switchToNewDebugMapObject(Name, sys::toTimePoint(Value));
    413 
    414   if (Type == MachO::N_AST) {
    415     SmallString<80> Path(PathPrefix);
    416     sys::path::append(Path, Name);
    417     Result->addDebugMapObject(Path, sys::toTimePoint(Value), Type);
    418     return;
    419   }
    420 
    421   // If the last N_OSO object file wasn't found, CurrentDebugMapObject will be
    422   // null. Do not update anything until we find the next valid N_OSO entry.
    423   if (!CurrentDebugMapObject)
    424     return;
    425 
    426   uint32_t Size = 0;
    427   switch (Type) {
    428   case MachO::N_GSYM:
    429     // This is a global variable. We need to query the main binary
    430     // symbol table to find its address as it might not be in the
    431     // debug map (for common symbols).
    432     Value = getMainBinarySymbolAddress(Name);
    433     break;
    434   case MachO::N_FUN:
    435     // Functions are scopes in STABS. They have an end marker that
    436     // contains the function size.
    437     if (Name[0] == '\0') {
    438       Size = Value;
    439       Value = CurrentFunctionAddress;
    440       Name = CurrentFunctionName;
    441       break;
    442     } else {
    443       CurrentFunctionName = Name;
    444       CurrentFunctionAddress = Value;
    445       return;
    446     }
    447   case MachO::N_STSYM:
    448     break;
    449   default:
    450     return;
    451   }
    452 
    453   auto ObjectSymIt = CurrentObjectAddresses.find(Name);
    454 
    455   // If the name of a (non-static) symbol is not in the current object, we
    456   // check all its aliases from the main binary.
    457   if (ObjectSymIt == CurrentObjectAddresses.end() && Type != MachO::N_STSYM) {
    458     for (const auto &Alias : getMainBinarySymbolNames(Value)) {
    459       ObjectSymIt = CurrentObjectAddresses.find(Alias);
    460       if (ObjectSymIt != CurrentObjectAddresses.end())
    461         break;
    462     }
    463   }
    464 
    465   // ThinLTO adds a unique suffix to exported private symbols.
    466   if (ObjectSymIt == CurrentObjectAddresses.end()) {
    467     for (auto Iter = CurrentObjectAddresses.begin();
    468          Iter != CurrentObjectAddresses.end(); ++Iter) {
    469       llvm::StringRef SymbolName = Iter->getKey();
    470       auto Pos = SymbolName.rfind(".llvm.");
    471       if (Pos != llvm::StringRef::npos && SymbolName.substr(0, Pos) == Name) {
    472         ObjectSymIt = Iter;
    473         break;
    474       }
    475     }
    476   }
    477 
    478   if (ObjectSymIt == CurrentObjectAddresses.end()) {
    479     Warning("could not find object file symbol for symbol " + Twine(Name));
    480     return;
    481   }
    482 
    483   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
    484                                         Size)) {
    485     Warning(Twine("failed to insert symbol '") + Name + "' in the debug map.");
    486     return;
    487   }
    488 }
    489 
    490 /// Load the current object file symbols into CurrentObjectAddresses.
    491 void MachODebugMapParser::loadCurrentObjectFileSymbols(
    492     const object::MachOObjectFile &Obj) {
    493   CurrentObjectAddresses.clear();
    494 
    495   for (auto Sym : Obj.symbols()) {
    496     uint64_t Addr = cantFail(Sym.getValue());
    497     Expected<StringRef> Name = Sym.getName();
    498     if (!Name) {
    499       // TODO: Actually report errors helpfully.
    500       consumeError(Name.takeError());
    501       continue;
    502     }
    503     // The value of some categories of symbols isn't meaningful. For
    504     // example common symbols store their size in the value field, not
    505     // their address. Absolute symbols have a fixed address that can
    506     // conflict with standard symbols. These symbols (especially the
    507     // common ones), might still be referenced by relocations. These
    508     // relocations will use the symbol itself, and won't need an
    509     // object file address. The object file address field is optional
    510     // in the DebugMap, leave it unassigned for these symbols.
    511     uint32_t Flags = cantFail(Sym.getFlags());
    512     if (Flags & SymbolRef::SF_Absolute) {
    513       CurrentObjectAddresses[*Name] = None;
    514     } else if (Flags & SymbolRef::SF_Common) {
    515       CurrentObjectAddresses[*Name] = None;
    516       CommonSymbols.push_back(std::string(*Name));
    517     } else {
    518       CurrentObjectAddresses[*Name] = Addr;
    519     }
    520   }
    521 }
    522 
    523 /// Lookup a symbol address in the main binary symbol table. The
    524 /// parser only needs to query common symbols, thus not every symbol's
    525 /// address is available through this function.
    526 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
    527   auto Sym = MainBinarySymbolAddresses.find(Name);
    528   if (Sym == MainBinarySymbolAddresses.end())
    529     return 0;
    530   return Sym->second;
    531 }
    532 
    533 /// Get all symbol names in the main binary for the given value.
    534 std::vector<StringRef>
    535 MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
    536   std::vector<StringRef> Names;
    537   for (const auto &Entry : MainBinarySymbolAddresses) {
    538     if (Entry.second == Value)
    539       Names.push_back(Entry.first());
    540   }
    541   return Names;
    542 }
    543 
    544 /// Load the interesting main binary symbols' addresses into
    545 /// MainBinarySymbolAddresses.
    546 void MachODebugMapParser::loadMainBinarySymbols(
    547     const MachOObjectFile &MainBinary) {
    548   section_iterator Section = MainBinary.section_end();
    549   MainBinarySymbolAddresses.clear();
    550   for (const auto &Sym : MainBinary.symbols()) {
    551     Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
    552     if (!TypeOrErr) {
    553       // TODO: Actually report errors helpfully.
    554       consumeError(TypeOrErr.takeError());
    555       continue;
    556     }
    557     SymbolRef::Type Type = *TypeOrErr;
    558     // Skip undefined and STAB entries.
    559     if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
    560       continue;
    561     // In theory, the only symbols of interest are the global variables. These
    562     // are the only ones that need to be queried because the address of common
    563     // data won't be described in the debug map. All other addresses should be
    564     // fetched for the debug map. In reality, by playing with 'ld -r' and
    565     // export lists, you can get symbols described as N_GSYM in the debug map,
    566     // but associated with a local symbol. Gather all the symbols, but prefer
    567     // the global ones.
    568     uint8_t SymType =
    569         MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
    570     bool Extern = SymType & (MachO::N_EXT | MachO::N_PEXT);
    571     Expected<section_iterator> SectionOrErr = Sym.getSection();
    572     if (!SectionOrErr) {
    573       // TODO: Actually report errors helpfully.
    574       consumeError(SectionOrErr.takeError());
    575       continue;
    576     }
    577     Section = *SectionOrErr;
    578     if ((Section == MainBinary.section_end() || Section->isText()) && !Extern)
    579       continue;
    580     uint64_t Addr = cantFail(Sym.getValue());
    581     Expected<StringRef> NameOrErr = Sym.getName();
    582     if (!NameOrErr) {
    583       // TODO: Actually report errors helpfully.
    584       consumeError(NameOrErr.takeError());
    585       continue;
    586     }
    587     StringRef Name = *NameOrErr;
    588     if (Name.size() == 0 || Name[0] == '\0')
    589       continue;
    590     // Override only if the new key is global.
    591     if (Extern)
    592       MainBinarySymbolAddresses[Name] = Addr;
    593     else
    594       MainBinarySymbolAddresses.try_emplace(Name, Addr);
    595   }
    596 }
    597 
    598 namespace llvm {
    599 namespace dsymutil {
    600 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
    601 parseDebugMap(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
    602               StringRef InputFile, ArrayRef<std::string> Archs,
    603               StringRef PrependPath, bool PaperTrailWarnings, bool Verbose,
    604               bool InputIsYAML) {
    605   if (InputIsYAML)
    606     return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
    607 
    608   MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath,
    609                              PaperTrailWarnings, Verbose);
    610   return Parser.parse();
    611 }
    612 
    613 bool dumpStab(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
    614               StringRef InputFile, ArrayRef<std::string> Archs,
    615               StringRef PrependPath) {
    616   MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath, false);
    617   return Parser.dumpStab();
    618 }
    619 } // namespace dsymutil
    620 } // namespace llvm
    621