DebugInfo.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * Copyright (c) 2020-2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "DebugInfo.h"
  7. #include <AK/Debug.h>
  8. #include <AK/LexicalPath.h>
  9. #include <AK/QuickSort.h>
  10. #include <LibDebug/Dwarf/CompilationUnit.h>
  11. #include <LibDebug/Dwarf/DwarfInfo.h>
  12. namespace Debug {
  13. DebugInfo::DebugInfo(ELF::Image const& elf, ByteString source_root, FlatPtr base_address)
  14. : m_elf(elf)
  15. , m_source_root(move(source_root))
  16. , m_base_address(base_address)
  17. , m_dwarf_info(m_elf)
  18. {
  19. prepare_variable_scopes().release_value_but_fixme_should_propagate_errors();
  20. prepare_lines().release_value_but_fixme_should_propagate_errors();
  21. }
  22. ErrorOr<void> DebugInfo::prepare_variable_scopes()
  23. {
  24. TRY(m_dwarf_info.for_each_compilation_unit([&](Dwarf::CompilationUnit const& unit) -> ErrorOr<void> {
  25. auto root = unit.root_die();
  26. TRY(parse_scopes_impl(root));
  27. return {};
  28. }));
  29. return {};
  30. }
  31. ErrorOr<void> DebugInfo::parse_scopes_impl(Dwarf::DIE const& die)
  32. {
  33. TRY(die.for_each_child([&](Dwarf::DIE const& child) -> ErrorOr<void> {
  34. if (child.is_null())
  35. return {};
  36. if (!(child.tag() == Dwarf::EntryTag::SubProgram || child.tag() == Dwarf::EntryTag::LexicalBlock))
  37. return {};
  38. if (TRY(child.get_attribute(Dwarf::Attribute::Inline)).has_value()) {
  39. dbgln_if(SPAM_DEBUG, "DWARF inlined functions are not supported");
  40. return {};
  41. }
  42. if (TRY(child.get_attribute(Dwarf::Attribute::Ranges)).has_value()) {
  43. dbgln_if(SPAM_DEBUG, "DWARF ranges are not supported");
  44. return {};
  45. }
  46. auto name = TRY(child.get_attribute(Dwarf::Attribute::Name));
  47. VariablesScope scope {};
  48. scope.is_function = (child.tag() == Dwarf::EntryTag::SubProgram);
  49. if (name.has_value())
  50. scope.name = TRY(name.value().as_string());
  51. if (!TRY(child.get_attribute(Dwarf::Attribute::LowPc)).has_value()) {
  52. dbgln_if(SPAM_DEBUG, "DWARF: Couldn't find attribute LowPc for scope");
  53. return {};
  54. }
  55. scope.address_low = TRY(TRY(child.get_attribute(Dwarf::Attribute::LowPc)).value().as_addr());
  56. auto high_pc = TRY(child.get_attribute(Dwarf::Attribute::HighPc));
  57. if (high_pc->type() == Dwarf::AttributeValue::Type::Address)
  58. scope.address_high = TRY(high_pc->as_addr());
  59. else
  60. scope.address_high = scope.address_low + high_pc->as_unsigned();
  61. TRY(child.for_each_child([&](Dwarf::DIE const& variable_entry) -> ErrorOr<void> {
  62. if (!(variable_entry.tag() == Dwarf::EntryTag::Variable
  63. || variable_entry.tag() == Dwarf::EntryTag::FormalParameter))
  64. return {};
  65. scope.dies_of_variables.append(variable_entry);
  66. return {};
  67. }));
  68. m_scopes.append(scope);
  69. TRY(parse_scopes_impl(child));
  70. return {};
  71. }));
  72. return {};
  73. }
  74. ErrorOr<void> DebugInfo::prepare_lines()
  75. {
  76. Vector<Dwarf::LineProgram::LineInfo> all_lines;
  77. TRY(m_dwarf_info.for_each_compilation_unit([&all_lines](Dwarf::CompilationUnit const& unit) -> ErrorOr<void> {
  78. all_lines.extend(unit.line_program().lines());
  79. return {};
  80. }));
  81. HashMap<DeprecatedFlyString, Optional<ByteString>> memoized_full_paths;
  82. auto compute_full_path = [&](DeprecatedFlyString const& file_path) -> Optional<ByteString> {
  83. if (file_path.view().contains("Toolchain/"sv) || file_path.view().contains("libgcc"sv))
  84. return {};
  85. if (file_path.view().starts_with("./"sv) && !m_source_root.is_empty())
  86. return LexicalPath::join(m_source_root, file_path).string();
  87. if (auto index_of_serenity_slash = file_path.view().find("serenity/"sv); index_of_serenity_slash.has_value()) {
  88. auto start_index = index_of_serenity_slash.value() + "serenity/"sv.length();
  89. return file_path.view().substring_view(start_index, file_path.length() - start_index);
  90. }
  91. return file_path;
  92. };
  93. m_sorted_lines.ensure_capacity(all_lines.size());
  94. for (auto const& line_info : all_lines) {
  95. auto maybe_full_path = memoized_full_paths.ensure(line_info.file, [&] { return compute_full_path(line_info.file); });
  96. if (!maybe_full_path.has_value())
  97. continue;
  98. m_sorted_lines.unchecked_append({ line_info.address, maybe_full_path.release_value(), line_info.line });
  99. }
  100. quick_sort(m_sorted_lines, [](auto& a, auto& b) {
  101. return a.address < b.address;
  102. });
  103. return {};
  104. }
  105. Optional<DebugInfo::SourcePosition> DebugInfo::get_source_position(FlatPtr target_address) const
  106. {
  107. if (m_sorted_lines.is_empty())
  108. return {};
  109. if (target_address < m_sorted_lines[0].address)
  110. return {};
  111. // TODO: We can do a binary search here
  112. for (size_t i = 0; i < m_sorted_lines.size() - 1; ++i) {
  113. if (m_sorted_lines[i + 1].address > target_address) {
  114. return SourcePosition::from_line_info(m_sorted_lines[i]);
  115. }
  116. }
  117. return {};
  118. }
  119. Optional<DebugInfo::SourcePositionAndAddress> DebugInfo::get_address_from_source_position(ByteString const& file, size_t line) const
  120. {
  121. ByteString file_path = file;
  122. if (!file_path.starts_with('/'))
  123. file_path = ByteString::formatted("/{}", file_path);
  124. Optional<SourcePositionAndAddress> result;
  125. for (auto const& line_entry : m_sorted_lines) {
  126. if (!line_entry.file.ends_with(file_path))
  127. continue;
  128. if (line_entry.line > line)
  129. continue;
  130. // We look for the source position that is closest to the desired position, and is not after it.
  131. // For example, get_address_of_source_position("main.cpp", 73) could return the address for an instruction whose location is ("main.cpp", 72)
  132. // as there might not be an instruction mapped for "main.cpp", 73.
  133. if (!result.has_value() || (line_entry.line > result.value().line)) {
  134. result = SourcePositionAndAddress { line_entry.file, line_entry.line, line_entry.address };
  135. }
  136. }
  137. return result;
  138. }
  139. ErrorOr<Vector<NonnullOwnPtr<DebugInfo::VariableInfo>>> DebugInfo::get_variables_in_current_scope(PtraceRegisters const& regs) const
  140. {
  141. Vector<NonnullOwnPtr<DebugInfo::VariableInfo>> variables;
  142. // TODO: We can store the scopes in a better data structure
  143. for (auto const& scope : m_scopes) {
  144. FlatPtr ip;
  145. #if ARCH(X86_64)
  146. ip = regs.rip;
  147. #elif ARCH(AARCH64)
  148. TODO_AARCH64();
  149. #elif ARCH(RISCV64)
  150. TODO_RISCV64();
  151. #else
  152. # error Unknown architecture
  153. #endif
  154. if (ip - m_base_address < scope.address_low || ip - m_base_address >= scope.address_high)
  155. continue;
  156. for (auto const& die_entry : scope.dies_of_variables) {
  157. auto variable_info = TRY(create_variable_info(die_entry, regs));
  158. if (!variable_info)
  159. continue;
  160. variables.append(variable_info.release_nonnull());
  161. }
  162. }
  163. return variables;
  164. }
  165. static ErrorOr<Optional<Dwarf::DIE>> parse_variable_type_die(Dwarf::DIE const& variable_die, DebugInfo::VariableInfo& variable_info)
  166. {
  167. auto type_die_offset = TRY(variable_die.get_attribute(Dwarf::Attribute::Type));
  168. if (!type_die_offset.has_value())
  169. return Optional<Dwarf::DIE> {};
  170. VERIFY(type_die_offset.value().type() == Dwarf::AttributeValue::Type::DieReference);
  171. auto type_die = variable_die.compilation_unit().get_die_at_offset(type_die_offset.value().as_unsigned());
  172. auto type_name = TRY(type_die.get_attribute(Dwarf::Attribute::Name));
  173. if (type_name.has_value()) {
  174. variable_info.type_name = TRY(type_name.value().as_string());
  175. } else {
  176. dbgln("Unnamed DWARF type at offset: {}", type_die.offset());
  177. variable_info.type_name = "[Unnamed Type]";
  178. }
  179. return type_die;
  180. }
  181. static ErrorOr<void> parse_variable_location(Dwarf::DIE const& variable_die, DebugInfo::VariableInfo& variable_info, PtraceRegisters const&)
  182. {
  183. auto location_info = TRY(variable_die.get_attribute(Dwarf::Attribute::Location));
  184. if (!location_info.has_value()) {
  185. location_info = TRY(variable_die.get_attribute(Dwarf::Attribute::MemberLocation));
  186. }
  187. if (!location_info.has_value())
  188. return {};
  189. switch (location_info.value().type()) {
  190. case Dwarf::AttributeValue::Type::UnsignedNumber:
  191. if (location_info->form() != Dwarf::AttributeDataForm::LocListX) {
  192. variable_info.location_type = DebugInfo::VariableInfo::LocationType::Address;
  193. variable_info.location_data.address = location_info.value().as_unsigned();
  194. } else {
  195. dbgln("Warning: unsupported Dwarf 5 loclist");
  196. }
  197. break;
  198. default:
  199. dbgln("Warning: unhandled Dwarf location type: {}", to_underlying(location_info.value().type()));
  200. }
  201. return {};
  202. }
  203. ErrorOr<OwnPtr<DebugInfo::VariableInfo>> DebugInfo::create_variable_info(Dwarf::DIE const& variable_die, PtraceRegisters const& regs, u32 address_offset) const
  204. {
  205. VERIFY(is_variable_tag_supported(variable_die.tag()));
  206. if (variable_die.tag() == Dwarf::EntryTag::FormalParameter
  207. && !TRY(variable_die.get_attribute(Dwarf::Attribute::Name)).has_value()) {
  208. // We don't want to display info for unused parameters
  209. return OwnPtr<DebugInfo::VariableInfo> {};
  210. }
  211. NonnullOwnPtr<VariableInfo> variable_info = make<VariableInfo>();
  212. auto name_attribute = TRY(variable_die.get_attribute(Dwarf::Attribute::Name));
  213. if (name_attribute.has_value())
  214. variable_info->name = TRY(name_attribute.value().as_string());
  215. auto type_die = TRY(parse_variable_type_die(variable_die, *variable_info));
  216. if (variable_die.tag() == Dwarf::EntryTag::Enumerator) {
  217. auto constant = TRY(variable_die.get_attribute(Dwarf::Attribute::ConstValue));
  218. VERIFY(constant.has_value());
  219. switch (constant.value().type()) {
  220. case Dwarf::AttributeValue::Type::UnsignedNumber:
  221. variable_info->constant_data.as_u32 = constant.value().as_unsigned();
  222. break;
  223. case Dwarf::AttributeValue::Type::SignedNumber:
  224. variable_info->constant_data.as_i32 = constant.value().as_signed();
  225. break;
  226. case Dwarf::AttributeValue::Type::String:
  227. variable_info->constant_data.as_string = TRY(constant.value().as_string());
  228. break;
  229. default:
  230. VERIFY_NOT_REACHED();
  231. }
  232. } else {
  233. TRY(parse_variable_location(variable_die, *variable_info, regs));
  234. variable_info->location_data.address += address_offset;
  235. }
  236. if (type_die.has_value())
  237. TRY(add_type_info_to_variable(type_die.value(), regs, variable_info));
  238. return variable_info;
  239. }
  240. ErrorOr<void> DebugInfo::add_type_info_to_variable(Dwarf::DIE const& type_die, PtraceRegisters const& regs, DebugInfo::VariableInfo* parent_variable) const
  241. {
  242. OwnPtr<VariableInfo> type_info;
  243. auto is_array_type = type_die.tag() == Dwarf::EntryTag::ArrayType;
  244. if (type_die.tag() == Dwarf::EntryTag::EnumerationType
  245. || type_die.tag() == Dwarf::EntryTag::StructureType
  246. || is_array_type) {
  247. type_info = TRY(create_variable_info(type_die, regs));
  248. }
  249. TRY(type_die.for_each_child([&](Dwarf::DIE const& member) -> ErrorOr<void> {
  250. if (member.is_null())
  251. return {};
  252. if (is_array_type && member.tag() == Dwarf::EntryTag::SubRangeType) {
  253. auto upper_bound = TRY(member.get_attribute(Dwarf::Attribute::UpperBound));
  254. VERIFY(upper_bound.has_value());
  255. auto size = upper_bound.value().as_unsigned() + 1;
  256. type_info->dimension_sizes.append(size);
  257. return {};
  258. }
  259. if (!is_variable_tag_supported(member.tag()))
  260. return {};
  261. auto member_variable = TRY(create_variable_info(member, regs, parent_variable->location_data.address));
  262. VERIFY(member_variable);
  263. if (type_die.tag() == Dwarf::EntryTag::EnumerationType) {
  264. member_variable->parent = type_info.ptr();
  265. type_info->members.append(member_variable.release_nonnull());
  266. } else {
  267. if (parent_variable->location_type != DebugInfo::VariableInfo::LocationType::Address)
  268. return {};
  269. member_variable->parent = parent_variable;
  270. parent_variable->members.append(member_variable.release_nonnull());
  271. }
  272. return {};
  273. }));
  274. if (type_info) {
  275. if (is_array_type) {
  276. StringBuilder array_type_name;
  277. array_type_name.append(type_info->type_name);
  278. for (auto array_size : type_info->dimension_sizes) {
  279. array_type_name.append('[');
  280. array_type_name.append(ByteString::formatted("{:d}", array_size));
  281. array_type_name.append(']');
  282. }
  283. parent_variable->type_name = array_type_name.to_byte_string();
  284. }
  285. parent_variable->type = move(type_info);
  286. parent_variable->type->type_tag = type_die.tag();
  287. }
  288. return {};
  289. }
  290. bool DebugInfo::is_variable_tag_supported(Dwarf::EntryTag const& tag)
  291. {
  292. return tag == Dwarf::EntryTag::Variable
  293. || tag == Dwarf::EntryTag::Member
  294. || tag == Dwarf::EntryTag::FormalParameter
  295. || tag == Dwarf::EntryTag::EnumerationType
  296. || tag == Dwarf::EntryTag::Enumerator
  297. || tag == Dwarf::EntryTag::StructureType
  298. || tag == Dwarf::EntryTag::ArrayType;
  299. }
  300. ByteString DebugInfo::name_of_containing_function(FlatPtr address) const
  301. {
  302. auto function = get_containing_function(address);
  303. if (!function.has_value())
  304. return {};
  305. return function.value().name;
  306. }
  307. Optional<DebugInfo::VariablesScope> DebugInfo::get_containing_function(FlatPtr address) const
  308. {
  309. for (auto const& scope : m_scopes) {
  310. if (!scope.is_function || address < scope.address_low || address >= scope.address_high)
  311. continue;
  312. return scope;
  313. }
  314. return {};
  315. }
  316. Vector<DebugInfo::SourcePosition> DebugInfo::source_lines_in_scope(VariablesScope const& scope) const
  317. {
  318. Vector<DebugInfo::SourcePosition> source_lines;
  319. for (auto const& line : m_sorted_lines) {
  320. if (line.address < scope.address_low)
  321. continue;
  322. if (line.address >= scope.address_high)
  323. break;
  324. source_lines.append(SourcePosition::from_line_info(line));
  325. }
  326. return source_lines;
  327. }
  328. DebugInfo::SourcePosition DebugInfo::SourcePosition::from_line_info(Dwarf::LineProgram::LineInfo const& line)
  329. {
  330. return { line.file, line.line, line.address };
  331. }
  332. ErrorOr<DebugInfo::SourcePositionWithInlines> DebugInfo::get_source_position_with_inlines(FlatPtr address) const
  333. {
  334. // If the address is in an "inline chain", this is the inner-most inlined position.
  335. auto inner_source_position = get_source_position(address);
  336. auto die = TRY(m_dwarf_info.get_die_at_address(address));
  337. if (!die.has_value() || die->tag() == Dwarf::EntryTag::SubroutineType) {
  338. // Inline chain is empty
  339. return SourcePositionWithInlines { inner_source_position, {} };
  340. }
  341. Vector<SourcePosition> inline_chain;
  342. auto insert_to_chain = [&](Dwarf::DIE const& die) -> ErrorOr<void> {
  343. auto caller_source_path = TRY(get_source_path_of_inline(die));
  344. auto caller_line = TRY(get_line_of_inline(die));
  345. if (!caller_source_path.has_value() || !caller_line.has_value()) {
  346. return {};
  347. }
  348. inline_chain.append({ ByteString::formatted("{}/{}", caller_source_path->directory, caller_source_path->filename), caller_line.value() });
  349. return {};
  350. };
  351. while (die->tag() == Dwarf::EntryTag::InlinedSubroutine) {
  352. TRY(insert_to_chain(*die));
  353. if (!die->parent_offset().has_value()) {
  354. break;
  355. }
  356. auto parent = TRY(die->compilation_unit().dwarf_info().get_cached_die_at_offset(die->parent_offset().value()));
  357. if (!parent.has_value()) {
  358. break;
  359. }
  360. die = *parent;
  361. }
  362. return SourcePositionWithInlines { inner_source_position, inline_chain };
  363. }
  364. ErrorOr<Optional<Dwarf::LineProgram::DirectoryAndFile>> DebugInfo::get_source_path_of_inline(Dwarf::DIE const& die) const
  365. {
  366. auto caller_file = TRY(die.get_attribute(Dwarf::Attribute::CallFile));
  367. if (caller_file.has_value()) {
  368. size_t file_index = 0;
  369. if (caller_file->type() == Dwarf::AttributeValue::Type::UnsignedNumber) {
  370. file_index = caller_file->as_unsigned();
  371. } else if (caller_file->type() == Dwarf::AttributeValue::Type::SignedNumber) {
  372. // For some reason, the file_index is sometimes stored as a signed number.
  373. auto signed_file_index = caller_file->as_signed();
  374. VERIFY(signed_file_index >= 0);
  375. VERIFY(static_cast<u64>(signed_file_index) <= NumericLimits<size_t>::max());
  376. file_index = static_cast<size_t>(caller_file->as_signed());
  377. } else {
  378. return Optional<Dwarf::LineProgram::DirectoryAndFile> {};
  379. }
  380. return die.compilation_unit().line_program().get_directory_and_file(file_index);
  381. }
  382. return Optional<Dwarf::LineProgram::DirectoryAndFile> {};
  383. }
  384. ErrorOr<Optional<uint32_t>> DebugInfo::get_line_of_inline(Dwarf::DIE const& die) const
  385. {
  386. auto caller_line = TRY(die.get_attribute(Dwarf::Attribute::CallLine));
  387. if (!caller_line.has_value())
  388. return Optional<uint32_t> {};
  389. if (caller_line->type() != Dwarf::AttributeValue::Type::UnsignedNumber)
  390. return Optional<uint32_t> {};
  391. return Optional<uint32_t> { caller_line.value().as_unsigned() };
  392. }
  393. }