MachODebugMapParser.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. #include "BinaryHolder.h"
  10. #include "DebugMap.h"
  11. #include "dsymutil.h"
  12. #include "llvm/Object/MachO.h"
  13. #include "llvm/Support/Path.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. namespace {
  16. using namespace llvm;
  17. using namespace llvm::dsymutil;
  18. using namespace llvm::object;
  19. class MachODebugMapParser {
  20. public:
  21. MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "",
  22. bool Verbose = false)
  23. : BinaryPath(BinaryPath), PathPrefix(PathPrefix),
  24. MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose),
  25. CurrentDebugMapObject(nullptr) {}
  26. /// \brief Parses and returns the DebugMap of the input binary.
  27. /// \returns an error in case the provided BinaryPath doesn't exist
  28. /// or isn't of a supported type.
  29. ErrorOr<std::unique_ptr<DebugMap>> parse();
  30. private:
  31. std::string BinaryPath;
  32. std::string PathPrefix;
  33. /// Owns the MemoryBuffer for the main binary.
  34. BinaryHolder MainBinaryHolder;
  35. /// Map of the binary symbol addresses.
  36. StringMap<uint64_t> MainBinarySymbolAddresses;
  37. StringRef MainBinaryStrings;
  38. /// The constructed DebugMap.
  39. std::unique_ptr<DebugMap> Result;
  40. /// Owns the MemoryBuffer for the currently handled object file.
  41. BinaryHolder CurrentObjectHolder;
  42. /// Map of the currently processed object file symbol addresses.
  43. StringMap<uint64_t> CurrentObjectAddresses;
  44. /// Element of the debug map corresponfing to the current object file.
  45. DebugMapObject *CurrentDebugMapObject;
  46. /// Holds function info while function scope processing.
  47. const char *CurrentFunctionName;
  48. uint64_t CurrentFunctionAddress;
  49. void switchToNewDebugMapObject(StringRef Filename);
  50. void resetParserState();
  51. uint64_t getMainBinarySymbolAddress(StringRef Name);
  52. void loadMainBinarySymbols();
  53. void loadCurrentObjectFileSymbols();
  54. void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
  55. uint8_t SectionIndex, uint16_t Flags,
  56. uint64_t Value);
  57. template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
  58. handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
  59. STE.n_value);
  60. }
  61. };
  62. static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
  63. }
  64. /// Reset the parser state coresponding to the current object
  65. /// file. This is to be called after an object file is finished
  66. /// processing.
  67. void MachODebugMapParser::resetParserState() {
  68. CurrentObjectAddresses.clear();
  69. CurrentDebugMapObject = nullptr;
  70. }
  71. /// Create a new DebugMapObject. This function resets the state of the
  72. /// parser that was referring to the last object file and sets
  73. /// everything up to add symbols to the new one.
  74. void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
  75. resetParserState();
  76. SmallString<80> Path(PathPrefix);
  77. sys::path::append(Path, Filename);
  78. auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
  79. if (auto Error = MachOOrError.getError()) {
  80. Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
  81. Error.message() + "\n");
  82. return;
  83. }
  84. loadCurrentObjectFileSymbols();
  85. CurrentDebugMapObject = &Result->addDebugMapObject(Path);
  86. }
  87. static Triple getTriple(const object::MachOObjectFile &Obj) {
  88. Triple TheTriple("unknown-unknown-unknown");
  89. TheTriple.setArch(Triple::ArchType(Obj.getArch()));
  90. TheTriple.setObjectFormat(Triple::MachO);
  91. return TheTriple;
  92. }
  93. /// This main parsing routine tries to open the main binary and if
  94. /// successful iterates over the STAB entries. The real parsing is
  95. /// done in handleStabSymbolTableEntry.
  96. ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
  97. auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
  98. if (auto Error = MainBinOrError.getError())
  99. return Error;
  100. const MachOObjectFile &MainBinary = *MainBinOrError;
  101. loadMainBinarySymbols();
  102. Result = make_unique<DebugMap>(getTriple(MainBinary));
  103. MainBinaryStrings = MainBinary.getStringTableData();
  104. for (const SymbolRef &Symbol : MainBinary.symbols()) {
  105. const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
  106. if (MainBinary.is64Bit())
  107. handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
  108. else
  109. handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
  110. }
  111. resetParserState();
  112. return std::move(Result);
  113. }
  114. /// Interpret the STAB entries to fill the DebugMap.
  115. void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
  116. uint8_t Type,
  117. uint8_t SectionIndex,
  118. uint16_t Flags,
  119. uint64_t Value) {
  120. if (!(Type & MachO::N_STAB))
  121. return;
  122. const char *Name = &MainBinaryStrings.data()[StringIndex];
  123. // An N_OSO entry represents the start of a new object file description.
  124. if (Type == MachO::N_OSO)
  125. return switchToNewDebugMapObject(Name);
  126. // If the last N_OSO object file wasn't found,
  127. // CurrentDebugMapObject will be null. Do not update anything
  128. // until we find the next valid N_OSO entry.
  129. if (!CurrentDebugMapObject)
  130. return;
  131. uint32_t Size = 0;
  132. switch (Type) {
  133. case MachO::N_GSYM:
  134. // This is a global variable. We need to query the main binary
  135. // symbol table to find its address as it might not be in the
  136. // debug map (for common symbols).
  137. Value = getMainBinarySymbolAddress(Name);
  138. break;
  139. case MachO::N_FUN:
  140. // Functions are scopes in STABS. They have an end marker that
  141. // contains the function size.
  142. if (Name[0] == '\0') {
  143. Size = Value;
  144. Value = CurrentFunctionAddress;
  145. Name = CurrentFunctionName;
  146. break;
  147. } else {
  148. CurrentFunctionName = Name;
  149. CurrentFunctionAddress = Value;
  150. return;
  151. }
  152. case MachO::N_STSYM:
  153. break;
  154. default:
  155. return;
  156. }
  157. auto ObjectSymIt = CurrentObjectAddresses.find(Name);
  158. if (ObjectSymIt == CurrentObjectAddresses.end())
  159. return Warning("could not find object file symbol for symbol " +
  160. Twine(Name));
  161. if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
  162. Size))
  163. return Warning(Twine("failed to insert symbol '") + Name +
  164. "' in the debug map.");
  165. }
  166. /// Load the current object file symbols into CurrentObjectAddresses.
  167. void MachODebugMapParser::loadCurrentObjectFileSymbols() {
  168. CurrentObjectAddresses.clear();
  169. for (auto Sym : CurrentObjectHolder.Get().symbols()) {
  170. uint64_t Addr = Sym.getValue();
  171. ErrorOr<StringRef> Name = Sym.getName();
  172. if (!Name)
  173. continue;
  174. CurrentObjectAddresses[*Name] = Addr;
  175. }
  176. }
  177. /// Lookup a symbol address in the main binary symbol table. The
  178. /// parser only needs to query common symbols, thus not every symbol's
  179. /// address is available through this function.
  180. uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
  181. auto Sym = MainBinarySymbolAddresses.find(Name);
  182. if (Sym == MainBinarySymbolAddresses.end())
  183. return 0;
  184. return Sym->second;
  185. }
  186. /// Load the interesting main binary symbols' addresses into
  187. /// MainBinarySymbolAddresses.
  188. void MachODebugMapParser::loadMainBinarySymbols() {
  189. const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
  190. section_iterator Section = MainBinary.section_end();
  191. for (const auto &Sym : MainBinary.symbols()) {
  192. SymbolRef::Type Type = Sym.getType();
  193. // Skip undefined and STAB entries.
  194. if ((Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown))
  195. continue;
  196. // The only symbols of interest are the global variables. These
  197. // are the only ones that need to be queried because the address
  198. // of common data won't be described in the debug map. All other
  199. // addresses should be fetched for the debug map.
  200. if (!(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
  201. Section == MainBinary.section_end() || Section->isText())
  202. continue;
  203. uint64_t Addr = Sym.getValue();
  204. ErrorOr<StringRef> NameOrErr = Sym.getName();
  205. if (!NameOrErr)
  206. continue;
  207. StringRef Name = *NameOrErr;
  208. if (Name.size() == 0 || Name[0] == '\0')
  209. continue;
  210. MainBinarySymbolAddresses[Name] = Addr;
  211. }
  212. }
  213. namespace llvm {
  214. namespace dsymutil {
  215. llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
  216. StringRef PrependPath,
  217. bool Verbose,
  218. bool InputIsYAML) {
  219. if (!InputIsYAML) {
  220. MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
  221. return Parser.parse();
  222. } else {
  223. return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
  224. }
  225. }
  226. }
  227. }