DebugInfo.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "DebugInfo.h"
  27. #include <AK/Debug.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/MemoryStream.h>
  30. #include <AK/QuickSort.h>
  31. #include <LibDebug/Dwarf/CompilationUnit.h>
  32. #include <LibDebug/Dwarf/DwarfInfo.h>
  33. #include <LibDebug/Dwarf/Expression.h>
  34. namespace Debug {
  35. DebugInfo::DebugInfo(NonnullOwnPtr<const ELF::Image> elf, String source_root, FlatPtr base_address)
  36. : m_elf(move(elf))
  37. , m_source_root(source_root)
  38. , m_base_address(base_address)
  39. , m_dwarf_info(*m_elf)
  40. {
  41. prepare_variable_scopes();
  42. prepare_lines();
  43. }
  44. void DebugInfo::prepare_variable_scopes()
  45. {
  46. m_dwarf_info.for_each_compilation_unit([&](const Dwarf::CompilationUnit& unit) {
  47. auto root = unit.root_die();
  48. parse_scopes_impl(root);
  49. });
  50. }
  51. void DebugInfo::parse_scopes_impl(const Dwarf::DIE& die)
  52. {
  53. die.for_each_child([&](const Dwarf::DIE& child) {
  54. if (child.is_null())
  55. return;
  56. if (!(child.tag() == Dwarf::EntryTag::SubProgram || child.tag() == Dwarf::EntryTag::LexicalBlock))
  57. return;
  58. if (child.get_attribute(Dwarf::Attribute::Inline).has_value()) {
  59. #if SPAM_DEBUG
  60. dbgln("DWARF inlined functions are not supported");
  61. #endif
  62. return;
  63. }
  64. if (child.get_attribute(Dwarf::Attribute::Ranges).has_value()) {
  65. #if SPAM_DEBUG
  66. dbgln("DWARF ranges are not supported");
  67. #endif
  68. return;
  69. }
  70. auto name = child.get_attribute(Dwarf::Attribute::Name);
  71. VariablesScope scope {};
  72. scope.is_function = (child.tag() == Dwarf::EntryTag::SubProgram);
  73. if (name.has_value())
  74. scope.name = name.value().data.as_string;
  75. if (!child.get_attribute(Dwarf::Attribute::LowPc).has_value()) {
  76. #if SPAM_DEBUG
  77. dbgln("DWARF: Couldn't find attribute LowPc for scope");
  78. #endif
  79. return;
  80. }
  81. scope.address_low = child.get_attribute(Dwarf::Attribute::LowPc).value().data.as_u32;
  82. // The attribute name HighPc is confusing. In this context, it seems to actually be a positive offset from LowPc
  83. scope.address_high = scope.address_low + child.get_attribute(Dwarf::Attribute::HighPc).value().data.as_u32;
  84. child.for_each_child([&](const Dwarf::DIE& variable_entry) {
  85. if (!(variable_entry.tag() == Dwarf::EntryTag::Variable
  86. || variable_entry.tag() == Dwarf::EntryTag::FormalParameter))
  87. return;
  88. scope.dies_of_variables.append(variable_entry);
  89. });
  90. m_scopes.append(scope);
  91. parse_scopes_impl(child);
  92. });
  93. }
  94. void DebugInfo::prepare_lines()
  95. {
  96. auto section = elf().lookup_section(".debug_line");
  97. if (section.is_undefined())
  98. return;
  99. InputMemoryStream stream { section.bytes() };
  100. Vector<Dwarf::LineProgram::LineInfo> all_lines;
  101. while (!stream.eof()) {
  102. Dwarf::LineProgram program(stream);
  103. all_lines.append(program.lines());
  104. }
  105. String serenity_slash("serenity/");
  106. for (auto& line_info : all_lines) {
  107. String file_path = line_info.file;
  108. if (file_path.contains("Toolchain/") || file_path.contains("libgcc"))
  109. continue;
  110. if (file_path.contains(serenity_slash)) {
  111. auto start_index = file_path.index_of(serenity_slash).value() + serenity_slash.length();
  112. file_path = file_path.substring(start_index, file_path.length() - start_index);
  113. }
  114. if (file_path.starts_with("./") && !m_source_root.is_null()) {
  115. file_path = LexicalPath::canonicalized_path(String::formatted("{}/{}", m_source_root, file_path));
  116. }
  117. m_sorted_lines.append({ line_info.address, file_path, line_info.line });
  118. }
  119. quick_sort(m_sorted_lines, [](auto& a, auto& b) {
  120. return a.address < b.address;
  121. });
  122. }
  123. Optional<DebugInfo::SourcePosition> DebugInfo::get_source_position(u32 target_address) const
  124. {
  125. if (m_sorted_lines.is_empty())
  126. return {};
  127. if (target_address < m_sorted_lines[0].address)
  128. return {};
  129. // TODO: We can do a binray search here
  130. for (size_t i = 0; i < m_sorted_lines.size() - 1; ++i) {
  131. if (m_sorted_lines[i + 1].address > target_address) {
  132. return SourcePosition::from_line_info(m_sorted_lines[i]);
  133. }
  134. }
  135. return {};
  136. }
  137. Optional<DebugInfo::SourcePositionAndAddress> DebugInfo::get_address_from_source_position(const String& file, size_t line) const
  138. {
  139. String file_path = file;
  140. if (!file_path.starts_with("/"))
  141. file_path = String::format("/%s", file_path.characters());
  142. constexpr char SERENITY_LIBS_PREFIX[] = "/usr/src/serenity";
  143. if (file.starts_with(SERENITY_LIBS_PREFIX)) {
  144. file_path = file.substring(sizeof(SERENITY_LIBS_PREFIX), file.length() - sizeof(SERENITY_LIBS_PREFIX));
  145. file_path = String::format("../%s", file_path.characters());
  146. }
  147. Optional<SourcePositionAndAddress> result;
  148. for (const auto& line_entry : m_sorted_lines) {
  149. if (!line_entry.file.ends_with(file_path))
  150. continue;
  151. if (line_entry.line > line)
  152. continue;
  153. // We look for the source position that is closest to the desired position, and is not after it.
  154. // For example, get_address_of_source_position("main.cpp", 73) could return the address for an instruction whose location is ("main.cpp", 72)
  155. // as there might not be an instruction mapped for "main.cpp", 73.
  156. if (!result.has_value() || (line_entry.line > result.value().line)) {
  157. result = SourcePositionAndAddress { line_entry.file, line_entry.line, line_entry.address };
  158. }
  159. }
  160. return result;
  161. }
  162. NonnullOwnPtrVector<DebugInfo::VariableInfo> DebugInfo::get_variables_in_current_scope(const PtraceRegisters& regs) const
  163. {
  164. NonnullOwnPtrVector<DebugInfo::VariableInfo> variables;
  165. // TODO: We can store the scopes in a better data structure
  166. for (const auto& scope : m_scopes) {
  167. if (regs.eip - m_base_address < scope.address_low || regs.eip - m_base_address >= scope.address_high)
  168. continue;
  169. for (const auto& die_entry : scope.dies_of_variables) {
  170. auto variable_info = create_variable_info(die_entry, regs);
  171. if (!variable_info)
  172. continue;
  173. variables.append(variable_info.release_nonnull());
  174. }
  175. }
  176. return variables;
  177. }
  178. static Optional<Dwarf::DIE> parse_variable_type_die(const Dwarf::DIE& variable_die, DebugInfo::VariableInfo& variable_info)
  179. {
  180. auto type_die_offset = variable_die.get_attribute(Dwarf::Attribute::Type);
  181. if (!type_die_offset.has_value())
  182. return {};
  183. VERIFY(type_die_offset.value().type == Dwarf::DIE::AttributeValue::Type::DieReference);
  184. auto type_die = variable_die.get_die_at_offset(type_die_offset.value().data.as_u32);
  185. auto type_name = type_die.get_attribute(Dwarf::Attribute::Name);
  186. if (type_name.has_value()) {
  187. variable_info.type_name = type_name.value().data.as_string;
  188. } else {
  189. dbgln("Unnamed DWARF type at offset: {}", type_die.offset());
  190. variable_info.type_name = "[Unnamed Type]";
  191. }
  192. return type_die;
  193. }
  194. static void parse_variable_location(const Dwarf::DIE& variable_die, DebugInfo::VariableInfo& variable_info, const PtraceRegisters& regs)
  195. {
  196. auto location_info = variable_die.get_attribute(Dwarf::Attribute::Location);
  197. if (!location_info.has_value()) {
  198. location_info = variable_die.get_attribute(Dwarf::Attribute::MemberLocation);
  199. }
  200. if (!location_info.has_value())
  201. return;
  202. switch (location_info.value().type) {
  203. case Dwarf::DIE::AttributeValue::Type::UnsignedNumber:
  204. variable_info.location_type = DebugInfo::VariableInfo::LocationType::Address;
  205. variable_info.location_data.address = location_info.value().data.as_u32;
  206. break;
  207. case Dwarf::DIE::AttributeValue::Type::DwarfExpression: {
  208. auto expression_bytes = ReadonlyBytes { location_info.value().data.as_raw_bytes.bytes, location_info.value().data.as_raw_bytes.length };
  209. auto value = Dwarf::Expression::evaluate(expression_bytes, regs);
  210. if (value.type != Dwarf::Expression::Type::None) {
  211. VERIFY(value.type == Dwarf::Expression::Type::UnsignedIntetger);
  212. variable_info.location_type = DebugInfo::VariableInfo::LocationType::Address;
  213. variable_info.location_data.address = value.data.as_u32;
  214. }
  215. break;
  216. }
  217. default:
  218. dbgln("Warning: unhandled Dwarf location type: {}", (int)location_info.value().type);
  219. }
  220. }
  221. OwnPtr<DebugInfo::VariableInfo> DebugInfo::create_variable_info(const Dwarf::DIE& variable_die, const PtraceRegisters& regs, u32 address_offset) const
  222. {
  223. VERIFY(is_variable_tag_supported(variable_die.tag()));
  224. if (variable_die.tag() == Dwarf::EntryTag::FormalParameter
  225. && !variable_die.get_attribute(Dwarf::Attribute::Name).has_value()) {
  226. // We don't want to display info for unused parameters
  227. return {};
  228. }
  229. NonnullOwnPtr<VariableInfo> variable_info = make<VariableInfo>();
  230. auto name_attribute = variable_die.get_attribute(Dwarf::Attribute::Name);
  231. if (name_attribute.has_value())
  232. variable_info->name = name_attribute.value().data.as_string;
  233. auto type_die = parse_variable_type_die(variable_die, *variable_info);
  234. if (variable_die.tag() == Dwarf::EntryTag::Enumerator) {
  235. auto constant = variable_die.get_attribute(Dwarf::Attribute::ConstValue);
  236. VERIFY(constant.has_value());
  237. switch (constant.value().type) {
  238. case Dwarf::DIE::AttributeValue::Type::UnsignedNumber:
  239. variable_info->constant_data.as_u32 = constant.value().data.as_u32;
  240. break;
  241. case Dwarf::DIE::AttributeValue::Type::SignedNumber:
  242. variable_info->constant_data.as_i32 = constant.value().data.as_i32;
  243. break;
  244. case Dwarf::DIE::AttributeValue::Type::String:
  245. variable_info->constant_data.as_string = constant.value().data.as_string;
  246. break;
  247. default:
  248. VERIFY_NOT_REACHED();
  249. }
  250. } else {
  251. parse_variable_location(variable_die, *variable_info, regs);
  252. variable_info->location_data.address += address_offset;
  253. }
  254. if (type_die.has_value()) {
  255. OwnPtr<VariableInfo> type_info;
  256. if (type_die.value().tag() == Dwarf::EntryTag::EnumerationType || type_die.value().tag() == Dwarf::EntryTag::StructureType) {
  257. type_info = create_variable_info(type_die.value(), regs);
  258. }
  259. type_die.value().for_each_child([&](const Dwarf::DIE& member) {
  260. if (member.is_null())
  261. return;
  262. if (!is_variable_tag_supported(member.tag()))
  263. return;
  264. auto member_variable = create_variable_info(member, regs, variable_info->location_data.address);
  265. VERIFY(member_variable);
  266. if (type_die.value().tag() == Dwarf::EntryTag::EnumerationType) {
  267. member_variable->parent = type_info.ptr();
  268. type_info->members.append(member_variable.release_nonnull());
  269. } else {
  270. if (variable_info->location_type == DebugInfo::VariableInfo::LocationType::None)
  271. return;
  272. VERIFY(variable_info->location_type == DebugInfo::VariableInfo::LocationType::Address);
  273. member_variable->parent = variable_info.ptr();
  274. variable_info->members.append(member_variable.release_nonnull());
  275. }
  276. });
  277. if (type_info) {
  278. variable_info->type = move(type_info);
  279. variable_info->type->type_tag = type_die.value().tag();
  280. }
  281. }
  282. return variable_info;
  283. }
  284. bool DebugInfo::is_variable_tag_supported(const Dwarf::EntryTag& tag)
  285. {
  286. return tag == Dwarf::EntryTag::Variable
  287. || tag == Dwarf::EntryTag::Member
  288. || tag == Dwarf::EntryTag::FormalParameter
  289. || tag == Dwarf::EntryTag::EnumerationType
  290. || tag == Dwarf::EntryTag::Enumerator
  291. || tag == Dwarf::EntryTag::StructureType;
  292. }
  293. String DebugInfo::name_of_containing_function(u32 address) const
  294. {
  295. auto function = get_containing_function(address);
  296. if (!function.has_value())
  297. return {};
  298. return function.value().name;
  299. }
  300. Optional<DebugInfo::VariablesScope> DebugInfo::get_containing_function(u32 address) const
  301. {
  302. for (const auto& scope : m_scopes) {
  303. if (!scope.is_function || address < scope.address_low || address >= scope.address_high)
  304. continue;
  305. return scope;
  306. }
  307. return {};
  308. }
  309. Vector<DebugInfo::SourcePosition> DebugInfo::source_lines_in_scope(const VariablesScope& scope) const
  310. {
  311. Vector<DebugInfo::SourcePosition> source_lines;
  312. for (const auto& line : m_sorted_lines) {
  313. if (line.address < scope.address_low)
  314. continue;
  315. if (line.address >= scope.address_high)
  316. break;
  317. source_lines.append(SourcePosition::from_line_info(line));
  318. }
  319. return source_lines;
  320. }
  321. DebugInfo::SourcePosition DebugInfo::SourcePosition::from_line_info(const Dwarf::LineProgram::LineInfo& line)
  322. {
  323. return { line.file, line.line, { line.address } };
  324. }
  325. }