DebugMap.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //===- tools/dsymutil/DebugMap.cpp - Generic debug map representation -----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "DebugMap.h"
  9. #include "BinaryHolder.h"
  10. #include "llvm/ADT/Optional.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/StringMap.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/Triple.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "llvm/BinaryFormat/MachO.h"
  17. #include "llvm/Object/ObjectFile.h"
  18. #include "llvm/Support/Chrono.h"
  19. #include "llvm/Support/Error.h"
  20. #include "llvm/Support/Format.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include "llvm/Support/Path.h"
  23. #include "llvm/Support/WithColor.h"
  24. #include "llvm/Support/YAMLTraits.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <algorithm>
  27. #include <cinttypes>
  28. #include <cstdint>
  29. #include <memory>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. namespace llvm {
  34. namespace dsymutil {
  35. using namespace llvm::object;
  36. DebugMapObject::DebugMapObject(StringRef ObjectFilename,
  37. sys::TimePoint<std::chrono::seconds> Timestamp,
  38. uint8_t Type)
  39. : Filename(std::string(ObjectFilename)), Timestamp(Timestamp), Type(Type) {}
  40. bool DebugMapObject::addSymbol(StringRef Name, Optional<uint64_t> ObjectAddress,
  41. uint64_t LinkedAddress, uint32_t Size) {
  42. auto InsertResult = Symbols.insert(
  43. std::make_pair(Name, SymbolMapping(ObjectAddress, LinkedAddress, Size)));
  44. if (ObjectAddress && InsertResult.second)
  45. AddressToMapping[*ObjectAddress] = &*InsertResult.first;
  46. return InsertResult.second;
  47. }
  48. void DebugMapObject::print(raw_ostream &OS) const {
  49. OS << getObjectFilename() << ":\n";
  50. // Sort the symbols in alphabetical order, like llvm-nm (and to get
  51. // deterministic output for testing).
  52. using Entry = std::pair<StringRef, SymbolMapping>;
  53. std::vector<Entry> Entries;
  54. Entries.reserve(Symbols.getNumItems());
  55. for (const auto &Sym : Symbols)
  56. Entries.push_back(std::make_pair(Sym.getKey(), Sym.getValue()));
  57. llvm::sort(Entries, [](const Entry &LHS, const Entry &RHS) {
  58. return LHS.first < RHS.first;
  59. });
  60. for (const auto &Sym : Entries) {
  61. if (Sym.second.ObjectAddress)
  62. OS << format("\t%016" PRIx64, uint64_t(*Sym.second.ObjectAddress));
  63. else
  64. OS << "\t????????????????";
  65. OS << format(" => %016" PRIx64 "+0x%x\t%s\n",
  66. uint64_t(Sym.second.BinaryAddress), uint32_t(Sym.second.Size),
  67. Sym.first.data());
  68. }
  69. OS << '\n';
  70. }
  71. #ifndef NDEBUG
  72. void DebugMapObject::dump() const { print(errs()); }
  73. #endif
  74. DebugMapObject &
  75. DebugMap::addDebugMapObject(StringRef ObjectFilePath,
  76. sys::TimePoint<std::chrono::seconds> Timestamp,
  77. uint8_t Type) {
  78. Objects.emplace_back(new DebugMapObject(ObjectFilePath, Timestamp, Type));
  79. return *Objects.back();
  80. }
  81. const DebugMapObject::DebugMapEntry *
  82. DebugMapObject::lookupSymbol(StringRef SymbolName) const {
  83. StringMap<SymbolMapping>::const_iterator Sym = Symbols.find(SymbolName);
  84. if (Sym == Symbols.end())
  85. return nullptr;
  86. return &*Sym;
  87. }
  88. const DebugMapObject::DebugMapEntry *
  89. DebugMapObject::lookupObjectAddress(uint64_t Address) const {
  90. auto Mapping = AddressToMapping.find(Address);
  91. if (Mapping == AddressToMapping.end())
  92. return nullptr;
  93. return Mapping->getSecond();
  94. }
  95. void DebugMap::print(raw_ostream &OS) const {
  96. yaml::Output yout(OS, /* Ctxt = */ nullptr, /* WrapColumn = */ 0);
  97. yout << const_cast<DebugMap &>(*this);
  98. }
  99. #ifndef NDEBUG
  100. void DebugMap::dump() const { print(errs()); }
  101. #endif
  102. namespace {
  103. struct YAMLContext {
  104. StringRef PrependPath;
  105. Triple BinaryTriple;
  106. };
  107. } // end anonymous namespace
  108. ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
  109. DebugMap::parseYAMLDebugMap(StringRef InputFile, StringRef PrependPath,
  110. bool Verbose) {
  111. auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(InputFile);
  112. if (auto Err = ErrOrFile.getError())
  113. return Err;
  114. YAMLContext Ctxt;
  115. Ctxt.PrependPath = PrependPath;
  116. std::unique_ptr<DebugMap> Res;
  117. yaml::Input yin((*ErrOrFile)->getBuffer(), &Ctxt);
  118. yin >> Res;
  119. if (auto EC = yin.error())
  120. return EC;
  121. std::vector<std::unique_ptr<DebugMap>> Result;
  122. Result.push_back(std::move(Res));
  123. return std::move(Result);
  124. }
  125. } // end namespace dsymutil
  126. namespace yaml {
  127. // Normalize/Denormalize between YAML and a DebugMapObject.
  128. struct MappingTraits<dsymutil::DebugMapObject>::YamlDMO {
  129. YamlDMO(IO &io) { Timestamp = 0; }
  130. YamlDMO(IO &io, dsymutil::DebugMapObject &Obj);
  131. dsymutil::DebugMapObject denormalize(IO &IO);
  132. std::string Filename;
  133. int64_t Timestamp;
  134. std::vector<dsymutil::DebugMapObject::YAMLSymbolMapping> Entries;
  135. };
  136. void MappingTraits<std::pair<std::string, DebugMapObject::SymbolMapping>>::
  137. mapping(IO &io, std::pair<std::string, DebugMapObject::SymbolMapping> &s) {
  138. io.mapRequired("sym", s.first);
  139. io.mapOptional("objAddr", s.second.ObjectAddress);
  140. io.mapRequired("binAddr", s.second.BinaryAddress);
  141. io.mapOptional("size", s.second.Size);
  142. }
  143. void MappingTraits<dsymutil::DebugMapObject>::mapping(
  144. IO &io, dsymutil::DebugMapObject &DMO) {
  145. MappingNormalization<YamlDMO, dsymutil::DebugMapObject> Norm(io, DMO);
  146. io.mapRequired("filename", Norm->Filename);
  147. io.mapOptional("timestamp", Norm->Timestamp);
  148. io.mapRequired("symbols", Norm->Entries);
  149. }
  150. void ScalarTraits<Triple>::output(const Triple &val, void *, raw_ostream &out) {
  151. out << val.str();
  152. }
  153. StringRef ScalarTraits<Triple>::input(StringRef scalar, void *, Triple &value) {
  154. value = Triple(scalar);
  155. return StringRef();
  156. }
  157. size_t
  158. SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::size(
  159. IO &io, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq) {
  160. return seq.size();
  161. }
  162. dsymutil::DebugMapObject &
  163. SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::element(
  164. IO &, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq,
  165. size_t index) {
  166. if (index >= seq.size()) {
  167. seq.resize(index + 1);
  168. seq[index].reset(new dsymutil::DebugMapObject);
  169. }
  170. return *seq[index];
  171. }
  172. void MappingTraits<dsymutil::DebugMap>::mapping(IO &io,
  173. dsymutil::DebugMap &DM) {
  174. io.mapRequired("triple", DM.BinaryTriple);
  175. io.mapOptional("binary-path", DM.BinaryPath);
  176. if (void *Ctxt = io.getContext())
  177. reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM.BinaryTriple;
  178. io.mapOptional("objects", DM.Objects);
  179. }
  180. void MappingTraits<std::unique_ptr<dsymutil::DebugMap>>::mapping(
  181. IO &io, std::unique_ptr<dsymutil::DebugMap> &DM) {
  182. if (!DM)
  183. DM.reset(new DebugMap());
  184. io.mapRequired("triple", DM->BinaryTriple);
  185. io.mapOptional("binary-path", DM->BinaryPath);
  186. if (void *Ctxt = io.getContext())
  187. reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM->BinaryTriple;
  188. io.mapOptional("objects", DM->Objects);
  189. }
  190. MappingTraits<dsymutil::DebugMapObject>::YamlDMO::YamlDMO(
  191. IO &io, dsymutil::DebugMapObject &Obj) {
  192. Filename = Obj.Filename;
  193. Timestamp = sys::toTimeT(Obj.getTimestamp());
  194. Entries.reserve(Obj.Symbols.size());
  195. for (auto &Entry : Obj.Symbols)
  196. Entries.push_back(
  197. std::make_pair(std::string(Entry.getKey()), Entry.getValue()));
  198. }
  199. dsymutil::DebugMapObject
  200. MappingTraits<dsymutil::DebugMapObject>::YamlDMO::denormalize(IO &IO) {
  201. BinaryHolder BinHolder(vfs::getRealFileSystem(), /* Verbose =*/false);
  202. const auto &Ctxt = *reinterpret_cast<YAMLContext *>(IO.getContext());
  203. SmallString<80> Path(Ctxt.PrependPath);
  204. StringMap<uint64_t> SymbolAddresses;
  205. sys::path::append(Path, Filename);
  206. auto ObjectEntry = BinHolder.getObjectEntry(Path);
  207. if (!ObjectEntry) {
  208. auto Err = ObjectEntry.takeError();
  209. WithColor::warning() << "Unable to open " << Path << " "
  210. << toString(std::move(Err)) << '\n';
  211. } else {
  212. auto Object = ObjectEntry->getObject(Ctxt.BinaryTriple);
  213. if (!Object) {
  214. auto Err = Object.takeError();
  215. WithColor::warning() << "Unable to open " << Path << " "
  216. << toString(std::move(Err)) << '\n';
  217. } else {
  218. for (const auto &Sym : Object->symbols()) {
  219. Expected<uint64_t> AddressOrErr = Sym.getValue();
  220. if (!AddressOrErr) {
  221. // TODO: Actually report errors helpfully.
  222. consumeError(AddressOrErr.takeError());
  223. continue;
  224. }
  225. Expected<StringRef> Name = Sym.getName();
  226. Expected<uint32_t> FlagsOrErr = Sym.getFlags();
  227. if (!Name || !FlagsOrErr ||
  228. (*FlagsOrErr & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))) {
  229. // TODO: Actually report errors helpfully.
  230. if (!FlagsOrErr)
  231. consumeError(FlagsOrErr.takeError());
  232. if (!Name)
  233. consumeError(Name.takeError());
  234. continue;
  235. }
  236. SymbolAddresses[*Name] = *AddressOrErr;
  237. }
  238. }
  239. }
  240. dsymutil::DebugMapObject Res(Path, sys::toTimePoint(Timestamp), MachO::N_OSO);
  241. for (auto &Entry : Entries) {
  242. auto &Mapping = Entry.second;
  243. Optional<uint64_t> ObjAddress;
  244. if (Mapping.ObjectAddress)
  245. ObjAddress = *Mapping.ObjectAddress;
  246. auto AddressIt = SymbolAddresses.find(Entry.first);
  247. if (AddressIt != SymbolAddresses.end())
  248. ObjAddress = AddressIt->getValue();
  249. Res.addSymbol(Entry.first, ObjAddress, Mapping.BinaryAddress, Mapping.Size);
  250. }
  251. return Res;
  252. }
  253. } // end namespace yaml
  254. } // end namespace llvm