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