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   /// \brief Parses and returns the DebugMaps of the input binary.
31   /// The binary contains multiple maps in case it is a universal
32   /// binary.
33   /// \returns an error in case the provided BinaryPath doesn't exist
34   /// or isn't of a supported type.
35   ErrorOr<std::vector<std::unique_ptr<DebugMap>>> parse();
36 
37   /// Walk the symbol table and dump it.
38   bool dumpStab();
39 
40 private:
41   std::string BinaryPath;
42   SmallVector<StringRef, 1> Archs;
43   std::string PathPrefix;
44 
45   /// Owns the MemoryBuffer for the main binary.
46   BinaryHolder MainBinaryHolder;
47   /// Map of the binary symbol addresses.
48   StringMap<uint64_t> MainBinarySymbolAddresses;
49   StringRef MainBinaryStrings;
50   /// The constructed DebugMap.
51   std::unique_ptr<DebugMap> Result;
52 
53   /// Owns the MemoryBuffer for the currently handled object file.
54   BinaryHolder CurrentObjectHolder;
55   /// Map of the currently processed object file symbol addresses.
56   StringMap<Optional<uint64_t>> CurrentObjectAddresses;
57   /// Element of the debug map corresponfing to the current object file.
58   DebugMapObject *CurrentDebugMapObject;
59 
60   /// Holds function info while function scope processing.
61   const char *CurrentFunctionName;
62   uint64_t CurrentFunctionAddress;
63 
64   std::unique_ptr<DebugMap> parseOneBinary(const MachOObjectFile &MainBinary,
65                                            StringRef BinaryPath);
66 
67   void
68   switchToNewDebugMapObject(StringRef Filename,
69                             sys::TimePoint<std::chrono::seconds> Timestamp);
70   void resetParserState();
71   uint64_t getMainBinarySymbolAddress(StringRef Name);
72   std::vector<StringRef> getMainBinarySymbolNames(uint64_t Value);
73   void loadMainBinarySymbols(const MachOObjectFile &MainBinary);
74   void loadCurrentObjectFileSymbols(const object::MachOObjectFile &Obj);
75   void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
76                                   uint8_t SectionIndex, uint16_t Flags,
77                                   uint64_t Value);
78 
79   template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
80     handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
81                                STE.n_value);
82   }
83 
84   /// Dump the symbol table output header.
85   void dumpSymTabHeader(raw_ostream &OS, StringRef Arch);
86 
87   /// Dump the contents of nlist entries.
88   void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, uint32_t StringIndex,
89                        uint8_t Type, uint8_t SectionIndex, uint16_t Flags,
90                        uint64_t Value);
91 
92   template <typename STEType>
93   void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, const STEType &STE) {
94     dumpSymTabEntry(OS, Index, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
95                     STE.n_value);
96   }
97   void dumpOneBinaryStab(const MachOObjectFile &MainBinary,
98                          StringRef BinaryPath);
99 };
100 
101 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
102 } // anonymous namespace
103 
104 /// Reset the parser state coresponding to the current object
105 /// file. This is to be called after an object file is finished
106 /// processing.
107 void MachODebugMapParser::resetParserState() {
108   CurrentObjectAddresses.clear();
109   CurrentDebugMapObject = nullptr;
110 }
111 
112 /// Create a new DebugMapObject. This function resets the state of the
113 /// parser that was referring to the last object file and sets
114 /// everything up to add symbols to the new one.
115 void MachODebugMapParser::switchToNewDebugMapObject(
116     StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) {
117   resetParserState();
118 
119   SmallString<80> Path(PathPrefix);
120   sys::path::append(Path, Filename);
121 
122   auto MachOOrError =
123       CurrentObjectHolder.GetFilesAs<MachOObjectFile>(Path, Timestamp);
124   if (auto Error = MachOOrError.getError()) {
125     Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
126             Error.message() + "\n");
127     return;
128   }
129 
130   auto ErrOrAchObj =
131       CurrentObjectHolder.GetAs<MachOObjectFile>(Result->getTriple());
132   if (auto Err = ErrOrAchObj.getError()) {
133     return Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
134                    Err.message() + "\n");
135   }
136 
137   CurrentDebugMapObject =
138       &Result->addDebugMapObject(Path, Timestamp, MachO::N_OSO);
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 (Type == MachO::N_AST) {
353     SmallString<80> Path(PathPrefix);
354     sys::path::append(Path, Name);
355     Result->addDebugMapObject(Path, sys::toTimePoint(Value), Type);
356     return;
357   }
358 
359   // If the last N_OSO object file wasn't found,
360   // CurrentDebugMapObject will be null. Do not update anything
361   // until we find the next valid N_OSO entry.
362   if (!CurrentDebugMapObject)
363     return;
364 
365   uint32_t Size = 0;
366   switch (Type) {
367   case MachO::N_GSYM:
368     // This is a global variable. We need to query the main binary
369     // symbol table to find its address as it might not be in the
370     // debug map (for common symbols).
371     Value = getMainBinarySymbolAddress(Name);
372     break;
373   case MachO::N_FUN:
374     // Functions are scopes in STABS. They have an end marker that
375     // contains the function size.
376     if (Name[0] == '\0') {
377       Size = Value;
378       Value = CurrentFunctionAddress;
379       Name = CurrentFunctionName;
380       break;
381     } else {
382       CurrentFunctionName = Name;
383       CurrentFunctionAddress = Value;
384       return;
385     }
386   case MachO::N_STSYM:
387     break;
388   default:
389     return;
390   }
391 
392   auto ObjectSymIt = CurrentObjectAddresses.find(Name);
393 
394   // If the name of a (non-static) symbol is not in the current object, we
395   // check all its aliases from the main binary.
396   if (ObjectSymIt == CurrentObjectAddresses.end() && Type != MachO::N_STSYM) {
397     for (const auto &Alias : getMainBinarySymbolNames(Value)) {
398       ObjectSymIt = CurrentObjectAddresses.find(Alias);
399       if (ObjectSymIt != CurrentObjectAddresses.end())
400         break;
401     }
402   }
403 
404   if (ObjectSymIt == CurrentObjectAddresses.end())
405     return Warning("could not find object file symbol for symbol " +
406                    Twine(Name));
407 
408   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
409                                         Size))
410     return Warning(Twine("failed to insert symbol '") + Name +
411                    "' in the debug map.");
412 }
413 
414 /// Load the current object file symbols into CurrentObjectAddresses.
415 void MachODebugMapParser::loadCurrentObjectFileSymbols(
416     const object::MachOObjectFile &Obj) {
417   CurrentObjectAddresses.clear();
418 
419   for (auto Sym : Obj.symbols()) {
420     uint64_t Addr = Sym.getValue();
421     Expected<StringRef> Name = Sym.getName();
422     if (!Name) {
423       // TODO: Actually report errors helpfully.
424       consumeError(Name.takeError());
425       continue;
426     }
427     // The value of some categories of symbols isn't meaningful. For
428     // example common symbols store their size in the value field, not
429     // their address. Absolute symbols have a fixed address that can
430     // conflict with standard symbols. These symbols (especially the
431     // common ones), might still be referenced by relocations. These
432     // relocations will use the symbol itself, and won't need an
433     // object file address. The object file address field is optional
434     // in the DebugMap, leave it unassigned for these symbols.
435     if (Sym.getFlags() & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))
436       CurrentObjectAddresses[*Name] = None;
437     else
438       CurrentObjectAddresses[*Name] = Addr;
439   }
440 }
441 
442 /// Lookup a symbol address in the main binary symbol table. The
443 /// parser only needs to query common symbols, thus not every symbol's
444 /// address is available through this function.
445 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
446   auto Sym = MainBinarySymbolAddresses.find(Name);
447   if (Sym == MainBinarySymbolAddresses.end())
448     return 0;
449   return Sym->second;
450 }
451 
452 /// Get all symbol names in the main binary for the given value.
453 std::vector<StringRef>
454 MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
455   std::vector<StringRef> Names;
456   for (const auto &Entry : MainBinarySymbolAddresses) {
457     if (Entry.second == Value)
458       Names.push_back(Entry.first());
459   }
460   return Names;
461 }
462 
463 /// Load the interesting main binary symbols' addresses into
464 /// MainBinarySymbolAddresses.
465 void MachODebugMapParser::loadMainBinarySymbols(
466     const MachOObjectFile &MainBinary) {
467   section_iterator Section = MainBinary.section_end();
468   MainBinarySymbolAddresses.clear();
469   for (const auto &Sym : MainBinary.symbols()) {
470     Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
471     if (!TypeOrErr) {
472       // TODO: Actually report errors helpfully.
473       consumeError(TypeOrErr.takeError());
474       continue;
475     }
476     SymbolRef::Type Type = *TypeOrErr;
477     // Skip undefined and STAB entries.
478     if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
479       continue;
480     // The only symbols of interest are the global variables. These
481     // are the only ones that need to be queried because the address
482     // of common data won't be described in the debug map. All other
483     // addresses should be fetched for the debug map.
484     uint8_t SymType =
485         MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
486     if (!(SymType & (MachO::N_EXT | MachO::N_PEXT)))
487       continue;
488     Expected<section_iterator> SectionOrErr = Sym.getSection();
489     if (!SectionOrErr) {
490       // TODO: Actually report errors helpfully.
491       consumeError(SectionOrErr.takeError());
492       continue;
493     }
494     Section = *SectionOrErr;
495     if (Section == MainBinary.section_end() || Section->isText())
496       continue;
497     uint64_t Addr = Sym.getValue();
498     Expected<StringRef> NameOrErr = Sym.getName();
499     if (!NameOrErr) {
500       // TODO: Actually report errors helpfully.
501       consumeError(NameOrErr.takeError());
502       continue;
503     }
504     StringRef Name = *NameOrErr;
505     if (Name.size() == 0 || Name[0] == '\0')
506       continue;
507     MainBinarySymbolAddresses[Name] = Addr;
508   }
509 }
510 
511 namespace llvm {
512 namespace dsymutil {
513 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
514 parseDebugMap(StringRef InputFile, ArrayRef<std::string> Archs,
515               StringRef PrependPath, bool Verbose, bool InputIsYAML) {
516   if (!InputIsYAML) {
517     MachODebugMapParser Parser(InputFile, Archs, PrependPath, Verbose);
518     return Parser.parse();
519   } else {
520     return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
521   }
522 }
523 
524 bool dumpStab(StringRef InputFile, ArrayRef<std::string> Archs,
525               StringRef PrependPath) {
526   MachODebugMapParser Parser(InputFile, Archs, PrependPath, false);
527   return Parser.dumpStab();
528 }
529 } // namespace dsymutil
530 } // namespace llvm
531