GsymCreator.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. //===- GsymCreator.cpp ----------------------------------------------------===//
  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. #include "llvm/DebugInfo/GSYM/GsymCreator.h"
  8. #include "llvm/DebugInfo/GSYM/FileWriter.h"
  9. #include "llvm/DebugInfo/GSYM/Header.h"
  10. #include "llvm/DebugInfo/GSYM/LineTable.h"
  11. #include "llvm/MC/StringTableBuilder.h"
  12. #include "llvm/Support/raw_ostream.h"
  13. #include <algorithm>
  14. #include <cassert>
  15. #include <functional>
  16. #include <vector>
  17. using namespace llvm;
  18. using namespace gsym;
  19. GsymCreator::GsymCreator() : StrTab(StringTableBuilder::ELF) {
  20. insertFile(StringRef());
  21. }
  22. uint32_t GsymCreator::insertFile(StringRef Path,
  23. llvm::sys::path::Style Style) {
  24. llvm::StringRef directory = llvm::sys::path::parent_path(Path, Style);
  25. llvm::StringRef filename = llvm::sys::path::filename(Path, Style);
  26. // We must insert the strings first, then call the FileEntry constructor.
  27. // If we inline the insertString() function call into the constructor, the
  28. // call order is undefined due to parameter lists not having any ordering
  29. // requirements.
  30. const uint32_t Dir = insertString(directory);
  31. const uint32_t Base = insertString(filename);
  32. FileEntry FE(Dir, Base);
  33. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  34. const auto NextIndex = Files.size();
  35. // Find FE in hash map and insert if not present.
  36. auto R = FileEntryToIndex.insert(std::make_pair(FE, NextIndex));
  37. if (R.second)
  38. Files.emplace_back(FE);
  39. return R.first->second;
  40. }
  41. llvm::Error GsymCreator::save(StringRef Path,
  42. llvm::support::endianness ByteOrder) const {
  43. std::error_code EC;
  44. raw_fd_ostream OutStrm(Path, EC);
  45. if (EC)
  46. return llvm::errorCodeToError(EC);
  47. FileWriter O(OutStrm, ByteOrder);
  48. return encode(O);
  49. }
  50. llvm::Error GsymCreator::encode(FileWriter &O) const {
  51. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  52. if (Funcs.empty())
  53. return createStringError(std::errc::invalid_argument,
  54. "no functions to encode");
  55. if (!Finalized)
  56. return createStringError(std::errc::invalid_argument,
  57. "GsymCreator wasn't finalized prior to encoding");
  58. if (Funcs.size() > UINT32_MAX)
  59. return createStringError(std::errc::invalid_argument,
  60. "too many FunctionInfos");
  61. const uint64_t MinAddr = BaseAddress ? *BaseAddress : Funcs.front().startAddress();
  62. const uint64_t MaxAddr = Funcs.back().startAddress();
  63. const uint64_t AddrDelta = MaxAddr - MinAddr;
  64. Header Hdr;
  65. Hdr.Magic = GSYM_MAGIC;
  66. Hdr.Version = GSYM_VERSION;
  67. Hdr.AddrOffSize = 0;
  68. Hdr.UUIDSize = static_cast<uint8_t>(UUID.size());
  69. Hdr.BaseAddress = MinAddr;
  70. Hdr.NumAddresses = static_cast<uint32_t>(Funcs.size());
  71. Hdr.StrtabOffset = 0; // We will fix this up later.
  72. Hdr.StrtabSize = 0; // We will fix this up later.
  73. memset(Hdr.UUID, 0, sizeof(Hdr.UUID));
  74. if (UUID.size() > sizeof(Hdr.UUID))
  75. return createStringError(std::errc::invalid_argument,
  76. "invalid UUID size %u", (uint32_t)UUID.size());
  77. // Set the address offset size correctly in the GSYM header.
  78. if (AddrDelta <= UINT8_MAX)
  79. Hdr.AddrOffSize = 1;
  80. else if (AddrDelta <= UINT16_MAX)
  81. Hdr.AddrOffSize = 2;
  82. else if (AddrDelta <= UINT32_MAX)
  83. Hdr.AddrOffSize = 4;
  84. else
  85. Hdr.AddrOffSize = 8;
  86. // Copy the UUID value if we have one.
  87. if (UUID.size() > 0)
  88. memcpy(Hdr.UUID, UUID.data(), UUID.size());
  89. // Write out the header.
  90. llvm::Error Err = Hdr.encode(O);
  91. if (Err)
  92. return Err;
  93. // Write out the address offsets.
  94. O.alignTo(Hdr.AddrOffSize);
  95. for (const auto &FuncInfo : Funcs) {
  96. uint64_t AddrOffset = FuncInfo.startAddress() - Hdr.BaseAddress;
  97. switch(Hdr.AddrOffSize) {
  98. case 1: O.writeU8(static_cast<uint8_t>(AddrOffset)); break;
  99. case 2: O.writeU16(static_cast<uint16_t>(AddrOffset)); break;
  100. case 4: O.writeU32(static_cast<uint32_t>(AddrOffset)); break;
  101. case 8: O.writeU64(AddrOffset); break;
  102. }
  103. }
  104. // Write out all zeros for the AddrInfoOffsets.
  105. O.alignTo(4);
  106. const off_t AddrInfoOffsetsOffset = O.tell();
  107. for (size_t i = 0, n = Funcs.size(); i < n; ++i)
  108. O.writeU32(0);
  109. // Write out the file table
  110. O.alignTo(4);
  111. assert(!Files.empty());
  112. assert(Files[0].Dir == 0);
  113. assert(Files[0].Base == 0);
  114. size_t NumFiles = Files.size();
  115. if (NumFiles > UINT32_MAX)
  116. return createStringError(std::errc::invalid_argument,
  117. "too many files");
  118. O.writeU32(static_cast<uint32_t>(NumFiles));
  119. for (auto File: Files) {
  120. O.writeU32(File.Dir);
  121. O.writeU32(File.Base);
  122. }
  123. // Write out the sting table.
  124. const off_t StrtabOffset = O.tell();
  125. StrTab.write(O.get_stream());
  126. const off_t StrtabSize = O.tell() - StrtabOffset;
  127. std::vector<uint32_t> AddrInfoOffsets;
  128. // Write out the address infos for each function info.
  129. for (const auto &FuncInfo : Funcs) {
  130. if (Expected<uint64_t> OffsetOrErr = FuncInfo.encode(O))
  131. AddrInfoOffsets.push_back(OffsetOrErr.get());
  132. else
  133. return OffsetOrErr.takeError();
  134. }
  135. // Fixup the string table offset and size in the header
  136. O.fixup32((uint32_t)StrtabOffset, offsetof(Header, StrtabOffset));
  137. O.fixup32((uint32_t)StrtabSize, offsetof(Header, StrtabSize));
  138. // Fixup all address info offsets
  139. uint64_t Offset = 0;
  140. for (auto AddrInfoOffset: AddrInfoOffsets) {
  141. O.fixup32(AddrInfoOffset, AddrInfoOffsetsOffset + Offset);
  142. Offset += 4;
  143. }
  144. return ErrorSuccess();
  145. }
  146. llvm::Error GsymCreator::finalize(llvm::raw_ostream &OS) {
  147. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  148. if (Finalized)
  149. return createStringError(std::errc::invalid_argument,
  150. "already finalized");
  151. Finalized = true;
  152. // Sort function infos so we can emit sorted functions.
  153. llvm::sort(Funcs);
  154. // Don't let the string table indexes change by finalizing in order.
  155. StrTab.finalizeInOrder();
  156. // Remove duplicates function infos that have both entries from debug info
  157. // (DWARF or Breakpad) and entries from the SymbolTable.
  158. //
  159. // Also handle overlapping function. Usually there shouldn't be any, but they
  160. // can and do happen in some rare cases.
  161. //
  162. // (a) (b) (c)
  163. // ^ ^ ^ ^
  164. // |X |Y |X ^ |X
  165. // | | | |Y | ^
  166. // | | | v v |Y
  167. // v v v v
  168. //
  169. // In (a) and (b), Y is ignored and X will be reported for the full range.
  170. // In (c), both functions will be included in the result and lookups for an
  171. // address in the intersection will return Y because of binary search.
  172. //
  173. // Note that in case of (b), we cannot include Y in the result because then
  174. // we wouldn't find any function for range (end of Y, end of X)
  175. // with binary search
  176. auto NumBefore = Funcs.size();
  177. auto Curr = Funcs.begin();
  178. auto Prev = Funcs.end();
  179. while (Curr != Funcs.end()) {
  180. // Can't check for overlaps or same address ranges if we don't have a
  181. // previous entry
  182. if (Prev != Funcs.end()) {
  183. if (Prev->Range.intersects(Curr->Range)) {
  184. // Overlapping address ranges.
  185. if (Prev->Range == Curr->Range) {
  186. // Same address range. Check if one is from debug info and the other
  187. // is from a symbol table. If so, then keep the one with debug info.
  188. // Our sorting guarantees that entries with matching address ranges
  189. // that have debug info are last in the sort.
  190. if (*Prev == *Curr) {
  191. // FunctionInfo entries match exactly (range, lines, inlines)
  192. OS << "warning: duplicate function info entries for range: "
  193. << Curr->Range << '\n';
  194. Curr = Funcs.erase(Prev);
  195. } else {
  196. if (!Prev->hasRichInfo() && Curr->hasRichInfo()) {
  197. // Same address range, one with no debug info (symbol) and the
  198. // next with debug info. Keep the latter.
  199. Curr = Funcs.erase(Prev);
  200. } else {
  201. OS << "warning: same address range contains different debug "
  202. << "info. Removing:\n"
  203. << *Prev << "\nIn favor of this one:\n"
  204. << *Curr << "\n";
  205. Curr = Funcs.erase(Prev);
  206. }
  207. }
  208. } else {
  209. // print warnings about overlaps
  210. OS << "warning: function ranges overlap:\n"
  211. << *Prev << "\n"
  212. << *Curr << "\n";
  213. }
  214. } else if (Prev->Range.size() == 0 &&
  215. Curr->Range.contains(Prev->Range.Start)) {
  216. OS << "warning: removing symbol:\n"
  217. << *Prev << "\nKeeping:\n"
  218. << *Curr << "\n";
  219. Curr = Funcs.erase(Prev);
  220. }
  221. }
  222. if (Curr == Funcs.end())
  223. break;
  224. Prev = Curr++;
  225. }
  226. // If our last function info entry doesn't have a size and if we have valid
  227. // text ranges, we should set the size of the last entry since any search for
  228. // a high address might match our last entry. By fixing up this size, we can
  229. // help ensure we don't cause lookups to always return the last symbol that
  230. // has no size when doing lookups.
  231. if (!Funcs.empty() && Funcs.back().Range.size() == 0 && ValidTextRanges) {
  232. if (auto Range = ValidTextRanges->getRangeThatContains(
  233. Funcs.back().Range.Start)) {
  234. Funcs.back().Range.End = Range->End;
  235. }
  236. }
  237. OS << "Pruned " << NumBefore - Funcs.size() << " functions, ended with "
  238. << Funcs.size() << " total\n";
  239. return Error::success();
  240. }
  241. uint32_t GsymCreator::insertString(StringRef S, bool Copy) {
  242. if (S.empty())
  243. return 0;
  244. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  245. if (Copy) {
  246. // We need to provide backing storage for the string if requested
  247. // since StringTableBuilder stores references to strings. Any string
  248. // that comes from a section in an object file doesn't need to be
  249. // copied, but any string created by code will need to be copied.
  250. // This allows GsymCreator to be really fast when parsing DWARF and
  251. // other object files as most strings don't need to be copied.
  252. CachedHashStringRef CHStr(S);
  253. if (!StrTab.contains(CHStr))
  254. S = StringStorage.insert(S).first->getKey();
  255. }
  256. return StrTab.add(S);
  257. }
  258. void GsymCreator::addFunctionInfo(FunctionInfo &&FI) {
  259. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  260. Ranges.insert(FI.Range);
  261. Funcs.emplace_back(FI);
  262. }
  263. void GsymCreator::forEachFunctionInfo(
  264. std::function<bool(FunctionInfo &)> const &Callback) {
  265. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  266. for (auto &FI : Funcs) {
  267. if (!Callback(FI))
  268. break;
  269. }
  270. }
  271. void GsymCreator::forEachFunctionInfo(
  272. std::function<bool(const FunctionInfo &)> const &Callback) const {
  273. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  274. for (const auto &FI : Funcs) {
  275. if (!Callback(FI))
  276. break;
  277. }
  278. }
  279. size_t GsymCreator::getNumFunctionInfos() const{
  280. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  281. return Funcs.size();
  282. }
  283. bool GsymCreator::IsValidTextAddress(uint64_t Addr) const {
  284. if (ValidTextRanges)
  285. return ValidTextRanges->contains(Addr);
  286. return true; // No valid text ranges has been set, so accept all ranges.
  287. }
  288. bool GsymCreator::hasFunctionInfoForAddress(uint64_t Addr) const {
  289. std::lock_guard<std::recursive_mutex> Guard(Mutex);
  290. return Ranges.contains(Addr);
  291. }