DebugInfo.cpp 17 KB

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