DebugInfo.cpp 18 KB

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