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:
MachODebugMapParser(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,StringRef BinaryPath,ArrayRef<std::string> Archs,StringRef PathPrefix="",bool PaperTrailWarnings=false,bool Verbose=false)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 
handleStabDebugMapEntry(const STEType & STE)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>
dumpSymTabEntry(raw_ostream & OS,uint64_t Index,const STEType & STE)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 
Warning(const Twine & Msg,StringRef File=StringRef ())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.
resetParserState()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).
addCommonSymbols()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.
switchToNewDebugMapObject(StringRef Filename,sys::TimePoint<std::chrono::seconds> Timestamp)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 
getArchName(const object::MachOObjectFile & Obj)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>
parseOneBinary(const MachOObjectFile & MainBinary,StringRef BinaryPath)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 
getDarwinStabString(uint8_t NType)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 
dumpSymTabHeader(raw_ostream & OS,StringRef Arch)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 
dumpSymTabEntry(raw_ostream & OS,uint64_t Index,uint32_t StringIndex,uint8_t Type,uint8_t SectionIndex,uint16_t Flags,uint64_t Value)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 
dumpOneBinaryStab(const MachOObjectFile & MainBinary,StringRef BinaryPath)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 
shouldLinkArch(SmallVectorImpl<StringRef> & Archs,StringRef Arch)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 
dumpStab()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.
parse()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.
handleStabSymbolTableEntry(uint32_t StringIndex,uint8_t Type,uint8_t SectionIndex,uint16_t Flags,uint64_t Value)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   if (ObjectSymIt == CurrentObjectAddresses.end()) {
466     Warning("could not find object file symbol for symbol " + Twine(Name));
467     return;
468   }
469 
470   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
471                                         Size)) {
472     Warning(Twine("failed to insert symbol '") + Name + "' in the debug map.");
473     return;
474   }
475 }
476 
477 /// Load the current object file symbols into CurrentObjectAddresses.
loadCurrentObjectFileSymbols(const object::MachOObjectFile & Obj)478 void MachODebugMapParser::loadCurrentObjectFileSymbols(
479     const object::MachOObjectFile &Obj) {
480   CurrentObjectAddresses.clear();
481 
482   for (auto Sym : Obj.symbols()) {
483     uint64_t Addr = cantFail(Sym.getValue());
484     Expected<StringRef> Name = Sym.getName();
485     if (!Name) {
486       // TODO: Actually report errors helpfully.
487       consumeError(Name.takeError());
488       continue;
489     }
490     // The value of some categories of symbols isn't meaningful. For
491     // example common symbols store their size in the value field, not
492     // their address. Absolute symbols have a fixed address that can
493     // conflict with standard symbols. These symbols (especially the
494     // common ones), might still be referenced by relocations. These
495     // relocations will use the symbol itself, and won't need an
496     // object file address. The object file address field is optional
497     // in the DebugMap, leave it unassigned for these symbols.
498     uint32_t Flags = cantFail(Sym.getFlags());
499     if (Flags & SymbolRef::SF_Absolute) {
500       CurrentObjectAddresses[*Name] = None;
501     } else if (Flags & SymbolRef::SF_Common) {
502       CurrentObjectAddresses[*Name] = None;
503       CommonSymbols.push_back(std::string(*Name));
504     } else {
505       CurrentObjectAddresses[*Name] = Addr;
506     }
507   }
508 }
509 
510 /// Lookup a symbol address in the main binary symbol table. The
511 /// parser only needs to query common symbols, thus not every symbol's
512 /// address is available through this function.
getMainBinarySymbolAddress(StringRef Name)513 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
514   auto Sym = MainBinarySymbolAddresses.find(Name);
515   if (Sym == MainBinarySymbolAddresses.end())
516     return 0;
517   return Sym->second;
518 }
519 
520 /// Get all symbol names in the main binary for the given value.
521 std::vector<StringRef>
getMainBinarySymbolNames(uint64_t Value)522 MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
523   std::vector<StringRef> Names;
524   for (const auto &Entry : MainBinarySymbolAddresses) {
525     if (Entry.second == Value)
526       Names.push_back(Entry.first());
527   }
528   return Names;
529 }
530 
531 /// Load the interesting main binary symbols' addresses into
532 /// MainBinarySymbolAddresses.
loadMainBinarySymbols(const MachOObjectFile & MainBinary)533 void MachODebugMapParser::loadMainBinarySymbols(
534     const MachOObjectFile &MainBinary) {
535   section_iterator Section = MainBinary.section_end();
536   MainBinarySymbolAddresses.clear();
537   for (const auto &Sym : MainBinary.symbols()) {
538     Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
539     if (!TypeOrErr) {
540       // TODO: Actually report errors helpfully.
541       consumeError(TypeOrErr.takeError());
542       continue;
543     }
544     SymbolRef::Type Type = *TypeOrErr;
545     // Skip undefined and STAB entries.
546     if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
547       continue;
548     // In theory, the only symbols of interest are the global variables. These
549     // are the only ones that need to be queried because the address of common
550     // data won't be described in the debug map. All other addresses should be
551     // fetched for the debug map. In reality, by playing with 'ld -r' and
552     // export lists, you can get symbols described as N_GSYM in the debug map,
553     // but associated with a local symbol. Gather all the symbols, but prefer
554     // the global ones.
555     uint8_t SymType =
556         MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
557     bool Extern = SymType & (MachO::N_EXT | MachO::N_PEXT);
558     Expected<section_iterator> SectionOrErr = Sym.getSection();
559     if (!SectionOrErr) {
560       // TODO: Actually report errors helpfully.
561       consumeError(SectionOrErr.takeError());
562       continue;
563     }
564     Section = *SectionOrErr;
565     if ((Section == MainBinary.section_end() || Section->isText()) &&
566         !(SymType &
567           MachO::N_PEXT)) // Alias to non-external (was a private external)
568       continue;
569     uint64_t Addr = cantFail(Sym.getValue());
570     Expected<StringRef> NameOrErr = Sym.getName();
571     if (!NameOrErr) {
572       // TODO: Actually report errors helpfully.
573       consumeError(NameOrErr.takeError());
574       continue;
575     }
576     StringRef Name = *NameOrErr;
577     if (Name.size() == 0 || Name[0] == '\0')
578       continue;
579     // Override only if the new key is global.
580     if (Extern)
581       MainBinarySymbolAddresses[Name] = Addr;
582     else
583       MainBinarySymbolAddresses.try_emplace(Name, Addr);
584   }
585 }
586 
587 namespace llvm {
588 namespace dsymutil {
589 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
parseDebugMap(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,StringRef InputFile,ArrayRef<std::string> Archs,StringRef PrependPath,bool PaperTrailWarnings,bool Verbose,bool InputIsYAML)590 parseDebugMap(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
591               StringRef InputFile, ArrayRef<std::string> Archs,
592               StringRef PrependPath, bool PaperTrailWarnings, bool Verbose,
593               bool InputIsYAML) {
594   if (InputIsYAML)
595     return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
596 
597   MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath,
598                              PaperTrailWarnings, Verbose);
599   return Parser.parse();
600 }
601 
dumpStab(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,StringRef InputFile,ArrayRef<std::string> Archs,StringRef PrependPath)602 bool dumpStab(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
603               StringRef InputFile, ArrayRef<std::string> Archs,
604               StringRef PrependPath) {
605   MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath, false);
606   return Parser.dumpStab();
607 }
608 } // namespace dsymutil
609 } // namespace llvm
610