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