OSDN Git Service

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