xref: /llvm-project/llvm/tools/dsymutil/MachODebugMapParser.cpp (revision b468fd64f9aa12d60b20ccfb576dbec470585026)
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 =
139       &Result->addDebugMapObject(Path, Timestamp, MachO::N_OSO);
140   loadCurrentObjectFileSymbols(*ErrOrAchObj);
141 }
142 
143 static std::string getArchName(const object::MachOObjectFile &Obj) {
144   Triple T = Obj.getArchTriple();
145   return T.getArchName();
146 }
147 
148 std::unique_ptr<DebugMap>
149 MachODebugMapParser::parseOneBinary(const MachOObjectFile &MainBinary,
150                                     StringRef BinaryPath) {
151   loadMainBinarySymbols(MainBinary);
152   Result = make_unique<DebugMap>(MainBinary.getArchTriple(), BinaryPath);
153   MainBinaryStrings = MainBinary.getStringTableData();
154   for (const SymbolRef &Symbol : MainBinary.symbols()) {
155     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
156     if (MainBinary.is64Bit())
157       handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
158     else
159       handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
160   }
161 
162   resetParserState();
163   return std::move(Result);
164 }
165 
166 // Table that maps Darwin's Mach-O stab constants to strings to allow printing.
167 // llvm-nm has very similar code, the strings used here are however slightly
168 // different and part of the interface of dsymutil (some project's build-systems
169 // parse the ouptut of dsymutil -s), thus they shouldn't be changed.
170 struct DarwinStabName {
171   uint8_t NType;
172   const char *Name;
173 };
174 
175 static const struct DarwinStabName DarwinStabNames[] = {
176     {MachO::N_GSYM, "N_GSYM"},    {MachO::N_FNAME, "N_FNAME"},
177     {MachO::N_FUN, "N_FUN"},      {MachO::N_STSYM, "N_STSYM"},
178     {MachO::N_LCSYM, "N_LCSYM"},  {MachO::N_BNSYM, "N_BNSYM"},
179     {MachO::N_PC, "N_PC"},        {MachO::N_AST, "N_AST"},
180     {MachO::N_OPT, "N_OPT"},      {MachO::N_RSYM, "N_RSYM"},
181     {MachO::N_SLINE, "N_SLINE"},  {MachO::N_ENSYM, "N_ENSYM"},
182     {MachO::N_SSYM, "N_SSYM"},    {MachO::N_SO, "N_SO"},
183     {MachO::N_OSO, "N_OSO"},      {MachO::N_LSYM, "N_LSYM"},
184     {MachO::N_BINCL, "N_BINCL"},  {MachO::N_SOL, "N_SOL"},
185     {MachO::N_PARAMS, "N_PARAM"}, {MachO::N_VERSION, "N_VERS"},
186     {MachO::N_OLEVEL, "N_OLEV"},  {MachO::N_PSYM, "N_PSYM"},
187     {MachO::N_EINCL, "N_EINCL"},  {MachO::N_ENTRY, "N_ENTRY"},
188     {MachO::N_LBRAC, "N_LBRAC"},  {MachO::N_EXCL, "N_EXCL"},
189     {MachO::N_RBRAC, "N_RBRAC"},  {MachO::N_BCOMM, "N_BCOMM"},
190     {MachO::N_ECOMM, "N_ECOMM"},  {MachO::N_ECOML, "N_ECOML"},
191     {MachO::N_LENG, "N_LENG"},    {0, nullptr}};
192 
193 static const char *getDarwinStabString(uint8_t NType) {
194   for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
195     if (DarwinStabNames[i].NType == NType)
196       return DarwinStabNames[i].Name;
197   }
198   return nullptr;
199 }
200 
201 void MachODebugMapParser::dumpSymTabHeader(raw_ostream &OS, StringRef Arch) {
202   OS << "-----------------------------------"
203         "-----------------------------------\n";
204   OS << "Symbol table for: '" << BinaryPath << "' (" << Arch.data() << ")\n";
205   OS << "-----------------------------------"
206         "-----------------------------------\n";
207   OS << "Index    n_strx   n_type             n_sect n_desc n_value\n";
208   OS << "======== -------- ------------------ ------ ------ ----------------\n";
209 }
210 
211 void MachODebugMapParser::dumpSymTabEntry(raw_ostream &OS, uint64_t Index,
212                                           uint32_t StringIndex, uint8_t Type,
213                                           uint8_t SectionIndex, uint16_t Flags,
214                                           uint64_t Value) {
215   // Index
216   OS << '[' << format_decimal(Index, 6) << "] "
217      // n_strx
218      << format_hex_no_prefix(StringIndex, 8) << ' '
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      // n_desc
259      << format_hex_no_prefix(Flags, 4) << "   "
260      // n_value
261      << format_hex_no_prefix(Value, 16);
262 
263   const char *Name = &MainBinaryStrings.data()[StringIndex];
264   if (Name && Name[0])
265     OS << " '" << Name << "'";
266 
267   OS << "\n";
268 }
269 
270 void MachODebugMapParser::dumpOneBinaryStab(const MachOObjectFile &MainBinary,
271                                             StringRef BinaryPath) {
272   loadMainBinarySymbols(MainBinary);
273   MainBinaryStrings = MainBinary.getStringTableData();
274   raw_ostream &OS(llvm::outs());
275 
276   dumpSymTabHeader(OS, getArchName(MainBinary));
277   uint64_t Idx = 0;
278   for (const SymbolRef &Symbol : MainBinary.symbols()) {
279     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
280     if (MainBinary.is64Bit())
281       dumpSymTabEntry(OS, Idx, MainBinary.getSymbol64TableEntry(DRI));
282     else
283       dumpSymTabEntry(OS, Idx, MainBinary.getSymbolTableEntry(DRI));
284     Idx++;
285   }
286 
287   OS << "\n\n";
288   resetParserState();
289 }
290 
291 static bool shouldLinkArch(SmallVectorImpl<StringRef> &Archs, StringRef Arch) {
292   if (Archs.empty() || is_contained(Archs, "all") || is_contained(Archs, "*"))
293     return true;
294 
295   if (Arch.startswith("arm") && Arch != "arm64" && is_contained(Archs, "arm"))
296     return true;
297 
298   SmallString<16> ArchName = Arch;
299   if (Arch.startswith("thumb"))
300     ArchName = ("arm" + Arch.substr(5)).str();
301 
302   return is_contained(Archs, ArchName);
303 }
304 
305 bool MachODebugMapParser::dumpStab() {
306   auto MainBinOrError =
307       MainBinaryHolder.GetFilesAs<MachOObjectFile>(BinaryPath);
308   if (auto Error = MainBinOrError.getError()) {
309     llvm::errs() << "Cannot get '" << BinaryPath
310                  << "' as MachO file: " << Error.message() << "\n";
311     return false;
312   }
313 
314   for (const auto *Binary : *MainBinOrError)
315     if (shouldLinkArch(Archs, Binary->getArchTriple().getArchName()))
316       dumpOneBinaryStab(*Binary, BinaryPath);
317 
318   return true;
319 }
320 
321 /// This main parsing routine tries to open the main binary and if
322 /// successful iterates over the STAB entries. The real parsing is
323 /// done in handleStabSymbolTableEntry.
324 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> MachODebugMapParser::parse() {
325   auto MainBinOrError =
326       MainBinaryHolder.GetFilesAs<MachOObjectFile>(BinaryPath);
327   if (auto Error = MainBinOrError.getError())
328     return Error;
329 
330   std::vector<std::unique_ptr<DebugMap>> Results;
331   for (const auto *Binary : *MainBinOrError)
332     if (shouldLinkArch(Archs, Binary->getArchTriple().getArchName()))
333       Results.push_back(parseOneBinary(*Binary, BinaryPath));
334 
335   return std::move(Results);
336 }
337 
338 /// Interpret the STAB entries to fill the DebugMap.
339 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
340                                                      uint8_t Type,
341                                                      uint8_t SectionIndex,
342                                                      uint16_t Flags,
343                                                      uint64_t Value) {
344   if (!(Type & MachO::N_STAB))
345     return;
346 
347   const char *Name = &MainBinaryStrings.data()[StringIndex];
348 
349   // An N_OSO entry represents the start of a new object file description.
350   if (Type == MachO::N_OSO)
351     return switchToNewDebugMapObject(Name, sys::toTimePoint(Value));
352 
353   if (Type == MachO::N_AST) {
354     SmallString<80> Path(PathPrefix);
355     sys::path::append(Path, Name);
356     Result->addDebugMapObject(Path, sys::toTimePoint(Value), Type);
357     return;
358   }
359 
360   // If the last N_OSO object file wasn't found,
361   // CurrentDebugMapObject will be null. Do not update anything
362   // until we find the next valid N_OSO entry.
363   if (!CurrentDebugMapObject)
364     return;
365 
366   uint32_t Size = 0;
367   switch (Type) {
368   case MachO::N_GSYM:
369     // This is a global variable. We need to query the main binary
370     // symbol table to find its address as it might not be in the
371     // debug map (for common symbols).
372     Value = getMainBinarySymbolAddress(Name);
373     break;
374   case MachO::N_FUN:
375     // Functions are scopes in STABS. They have an end marker that
376     // contains the function size.
377     if (Name[0] == '\0') {
378       Size = Value;
379       Value = CurrentFunctionAddress;
380       Name = CurrentFunctionName;
381       break;
382     } else {
383       CurrentFunctionName = Name;
384       CurrentFunctionAddress = Value;
385       return;
386     }
387   case MachO::N_STSYM:
388     break;
389   default:
390     return;
391   }
392 
393   auto ObjectSymIt = CurrentObjectAddresses.find(Name);
394 
395   // If the name of a (non-static) symbol is not in the current object, we
396   // check all its aliases from the main binary.
397   if (ObjectSymIt == CurrentObjectAddresses.end() && Type != MachO::N_STSYM) {
398     for (const auto &Alias : getMainBinarySymbolNames(Value)) {
399       ObjectSymIt = CurrentObjectAddresses.find(Alias);
400       if (ObjectSymIt != CurrentObjectAddresses.end())
401         break;
402     }
403   }
404 
405   if (ObjectSymIt == CurrentObjectAddresses.end())
406     return Warning("could not find object file symbol for symbol " +
407                    Twine(Name));
408 
409   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
410                                         Size))
411     return Warning(Twine("failed to insert symbol '") + Name +
412                    "' in the debug map.");
413 }
414 
415 /// Load the current object file symbols into CurrentObjectAddresses.
416 void MachODebugMapParser::loadCurrentObjectFileSymbols(
417     const object::MachOObjectFile &Obj) {
418   CurrentObjectAddresses.clear();
419 
420   for (auto Sym : Obj.symbols()) {
421     uint64_t Addr = Sym.getValue();
422     Expected<StringRef> Name = Sym.getName();
423     if (!Name) {
424       // TODO: Actually report errors helpfully.
425       consumeError(Name.takeError());
426       continue;
427     }
428     // The value of some categories of symbols isn't meaningful. For
429     // example common symbols store their size in the value field, not
430     // their address. Absolute symbols have a fixed address that can
431     // conflict with standard symbols. These symbols (especially the
432     // common ones), might still be referenced by relocations. These
433     // relocations will use the symbol itself, and won't need an
434     // object file address. The object file address field is optional
435     // in the DebugMap, leave it unassigned for these symbols.
436     if (Sym.getFlags() & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))
437       CurrentObjectAddresses[*Name] = None;
438     else
439       CurrentObjectAddresses[*Name] = Addr;
440   }
441 }
442 
443 /// Lookup a symbol address in the main binary symbol table. The
444 /// parser only needs to query common symbols, thus not every symbol's
445 /// address is available through this function.
446 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
447   auto Sym = MainBinarySymbolAddresses.find(Name);
448   if (Sym == MainBinarySymbolAddresses.end())
449     return 0;
450   return Sym->second;
451 }
452 
453 /// Get all symbol names in the main binary for the given value.
454 std::vector<StringRef>
455 MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
456   std::vector<StringRef> Names;
457   for (const auto &Entry : MainBinarySymbolAddresses) {
458     if (Entry.second == Value)
459       Names.push_back(Entry.first());
460   }
461   return Names;
462 }
463 
464 /// Load the interesting main binary symbols' addresses into
465 /// MainBinarySymbolAddresses.
466 void MachODebugMapParser::loadMainBinarySymbols(
467     const MachOObjectFile &MainBinary) {
468   section_iterator Section = MainBinary.section_end();
469   MainBinarySymbolAddresses.clear();
470   for (const auto &Sym : MainBinary.symbols()) {
471     Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
472     if (!TypeOrErr) {
473       // TODO: Actually report errors helpfully.
474       consumeError(TypeOrErr.takeError());
475       continue;
476     }
477     SymbolRef::Type Type = *TypeOrErr;
478     // Skip undefined and STAB entries.
479     if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
480       continue;
481     // The only symbols of interest are the global variables. These
482     // are the only ones that need to be queried because the address
483     // of common data won't be described in the debug map. All other
484     // addresses should be fetched for the debug map.
485     uint8_t SymType =
486         MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
487     if (!(SymType & (MachO::N_EXT | MachO::N_PEXT)))
488       continue;
489     Expected<section_iterator> SectionOrErr = Sym.getSection();
490     if (!SectionOrErr) {
491       // TODO: Actually report errors helpfully.
492       consumeError(SectionOrErr.takeError());
493       continue;
494     }
495     Section = *SectionOrErr;
496     if (Section == MainBinary.section_end() || Section->isText())
497       continue;
498     uint64_t Addr = Sym.getValue();
499     Expected<StringRef> NameOrErr = Sym.getName();
500     if (!NameOrErr) {
501       // TODO: Actually report errors helpfully.
502       consumeError(NameOrErr.takeError());
503       continue;
504     }
505     StringRef Name = *NameOrErr;
506     if (Name.size() == 0 || Name[0] == '\0')
507       continue;
508     MainBinarySymbolAddresses[Name] = Addr;
509   }
510 }
511 
512 namespace llvm {
513 namespace dsymutil {
514 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
515 parseDebugMap(StringRef InputFile, ArrayRef<std::string> Archs,
516               StringRef PrependPath, bool Verbose, bool InputIsYAML) {
517   if (!InputIsYAML) {
518     MachODebugMapParser Parser(InputFile, Archs, PrependPath, Verbose);
519     return Parser.parse();
520   } else {
521     return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
522   }
523 }
524 
525 bool dumpStab(StringRef InputFile, ArrayRef<std::string> Archs,
526               StringRef PrependPath) {
527   MachODebugMapParser Parser(InputFile, Archs, PrependPath, false);
528   return Parser.dumpStab();
529 }
530 } // namespace dsymutil
531 } // namespace llvm
532