Debugger.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Debugger.h"
  7. #include <LibDebug/StackFrameUtils.h>
  8. namespace HackStudio {
  9. static Debugger* s_the;
  10. Debugger& Debugger::the()
  11. {
  12. VERIFY(s_the);
  13. return *s_the;
  14. }
  15. void Debugger::initialize(
  16. DeprecatedString source_root,
  17. Function<HasControlPassedToUser(PtraceRegisters const&)> on_stop_callback,
  18. Function<void()> on_continue_callback,
  19. Function<void()> on_exit_callback)
  20. {
  21. s_the = new Debugger(source_root, move(on_stop_callback), move(on_continue_callback), move(on_exit_callback));
  22. }
  23. bool Debugger::is_initialized()
  24. {
  25. return s_the;
  26. }
  27. Debugger::Debugger(
  28. DeprecatedString source_root,
  29. Function<HasControlPassedToUser(PtraceRegisters const&)> on_stop_callback,
  30. Function<void()> on_continue_callback,
  31. Function<void()> on_exit_callback)
  32. : m_source_root(source_root)
  33. , m_on_stopped_callback(move(on_stop_callback))
  34. , m_on_continue_callback(move(on_continue_callback))
  35. , m_on_exit_callback(move(on_exit_callback))
  36. {
  37. pthread_mutex_init(&m_ui_action_mutex, nullptr);
  38. pthread_cond_init(&m_ui_action_cond, nullptr);
  39. }
  40. void Debugger::on_breakpoint_change(DeprecatedString const& file, size_t line, BreakpointChange change_type)
  41. {
  42. auto position = create_source_position(file, line);
  43. if (change_type == BreakpointChange::Added) {
  44. m_breakpoints.append(position);
  45. } else {
  46. m_breakpoints.remove_all_matching([&](Debug::DebugInfo::SourcePosition const& val) { return val == position; });
  47. }
  48. auto session = Debugger::the().session();
  49. if (!session)
  50. return;
  51. auto address = session->get_address_from_source_position(position.file_path, position.line_number);
  52. if (!address.has_value()) {
  53. dbgln("Warning: couldn't get instruction address from source");
  54. // TODO: Currently, the GUI will indicate that a breakpoint was inserted/removed at this line,
  55. // regardless of whether we actually succeeded to insert it. (For example a breakpoint on a comment, or an include statement).
  56. // We should indicate failure via a return value from this function, and not update the breakpoint GUI if we fail.
  57. return;
  58. }
  59. if (change_type == BreakpointChange::Added) {
  60. bool success = session->insert_breakpoint(address.value().address);
  61. VERIFY(success);
  62. } else {
  63. bool success = session->remove_breakpoint(address.value().address);
  64. VERIFY(success);
  65. }
  66. }
  67. bool Debugger::set_execution_position(DeprecatedString const& file, size_t line)
  68. {
  69. auto position = create_source_position(file, line);
  70. auto session = Debugger::the().session();
  71. if (!session)
  72. return false;
  73. auto address = session->get_address_from_source_position(position.file_path, position.line_number);
  74. if (!address.has_value())
  75. return false;
  76. auto registers = session->get_registers();
  77. registers.set_ip(address.value().address);
  78. session->set_registers(registers);
  79. return true;
  80. }
  81. Debug::DebugInfo::SourcePosition Debugger::create_source_position(DeprecatedString const& file, size_t line)
  82. {
  83. if (file.starts_with('/'))
  84. return { file, line + 1 };
  85. return { LexicalPath::canonicalized_path(DeprecatedString::formatted("{}/{}", m_source_root, file)), line + 1 };
  86. }
  87. intptr_t Debugger::start_static()
  88. {
  89. Debugger::the().start();
  90. return 0;
  91. }
  92. void Debugger::stop()
  93. {
  94. set_requested_debugger_action(DebuggerAction::Exit);
  95. }
  96. void Debugger::start()
  97. {
  98. auto [debug_session, initial_state] = create_debug_session();
  99. m_debug_session = move(debug_session);
  100. for (auto const& breakpoint : m_breakpoints) {
  101. dbgln("inserting breakpoint at: {}:{}", breakpoint.file_path, breakpoint.line_number);
  102. auto address = m_debug_session->get_address_from_source_position(breakpoint.file_path, breakpoint.line_number);
  103. if (address.has_value()) {
  104. bool success = m_debug_session->insert_breakpoint(address.value().address);
  105. VERIFY(success);
  106. } else {
  107. dbgln("couldn't insert breakpoint");
  108. }
  109. }
  110. debugger_loop(initial_state);
  111. }
  112. Debugger::CreateDebugSessionResult Debugger::create_debug_session()
  113. {
  114. if (!m_executable_path.is_null()) {
  115. auto child_setup_callback = [this]() {
  116. if (m_child_setup_callback)
  117. return m_child_setup_callback();
  118. return ErrorOr<void> {};
  119. };
  120. auto debug_session = Debug::DebugSession::exec_and_attach(m_executable_path, m_source_root, move(child_setup_callback));
  121. VERIFY(!!debug_session);
  122. return { debug_session.release_nonnull(), Debug::DebugSession::Running };
  123. }
  124. if (m_pid_to_attach.has_value()) {
  125. auto debug_session = Debug::DebugSession::attach(m_pid_to_attach.value(), m_source_root);
  126. VERIFY(!!debug_session);
  127. return { debug_session.release_nonnull(), Debug::DebugSession::Stopped };
  128. }
  129. VERIFY_NOT_REACHED();
  130. }
  131. int Debugger::debugger_loop(Debug::DebugSession::DesiredInitialDebugeeState initial_state)
  132. {
  133. VERIFY(m_debug_session);
  134. m_debug_session->run(initial_state, [this](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  135. if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
  136. dbgln("Program exited");
  137. m_on_exit_callback();
  138. return Debug::DebugSession::DebugDecision::Detach;
  139. }
  140. remove_temporary_breakpoints();
  141. VERIFY(optional_regs.has_value());
  142. const PtraceRegisters& regs = optional_regs.value();
  143. auto source_position = m_debug_session->get_source_position(regs.ip());
  144. if (!source_position.has_value())
  145. return Debug::DebugSession::DebugDecision::SingleStep;
  146. // We currently do no support stepping through assembly source
  147. if (source_position.value().file_path.ends_with(".S"sv))
  148. return Debug::DebugSession::DebugDecision::SingleStep;
  149. VERIFY(source_position.has_value());
  150. if (m_state.get() == Debugger::DebuggingState::SingleStepping) {
  151. if (m_state.should_stop_single_stepping(source_position.value())) {
  152. m_state.set_normal();
  153. } else {
  154. return Debug::DebugSession::DebugDecision::SingleStep;
  155. }
  156. }
  157. auto control_passed_to_user = m_on_stopped_callback(regs);
  158. if (control_passed_to_user == HasControlPassedToUser::Yes) {
  159. pthread_mutex_lock(&m_ui_action_mutex);
  160. pthread_cond_wait(&m_ui_action_cond, &m_ui_action_mutex);
  161. pthread_mutex_unlock(&m_ui_action_mutex);
  162. if (m_requested_debugger_action != DebuggerAction::Exit)
  163. m_on_continue_callback();
  164. } else {
  165. m_requested_debugger_action = DebuggerAction::Continue;
  166. }
  167. switch (m_requested_debugger_action) {
  168. case DebuggerAction::Continue:
  169. m_state.set_normal();
  170. return Debug::DebugSession::DebugDecision::Continue;
  171. case DebuggerAction::SourceSingleStep:
  172. m_state.set_single_stepping(source_position.value());
  173. return Debug::DebugSession::DebugDecision::SingleStep;
  174. case DebuggerAction::SourceStepOut:
  175. m_state.set_stepping_out();
  176. do_step_out(regs);
  177. return Debug::DebugSession::DebugDecision::Continue;
  178. case DebuggerAction::SourceStepOver:
  179. m_state.set_stepping_over();
  180. do_step_over(regs);
  181. return Debug::DebugSession::DebugDecision::Continue;
  182. case DebuggerAction::Exit:
  183. dbgln("Debugger exiting");
  184. m_on_exit_callback();
  185. return Debug::DebugSession::DebugDecision::Kill;
  186. }
  187. VERIFY_NOT_REACHED();
  188. });
  189. m_debug_session.clear();
  190. return 0;
  191. }
  192. void Debugger::DebuggingState::set_normal()
  193. {
  194. m_state = State::Normal;
  195. m_original_source_position.clear();
  196. }
  197. void Debugger::DebuggingState::set_single_stepping(Debug::DebugInfo::SourcePosition original_source_position)
  198. {
  199. m_state = State::SingleStepping;
  200. m_original_source_position = original_source_position;
  201. }
  202. bool Debugger::DebuggingState::should_stop_single_stepping(Debug::DebugInfo::SourcePosition const& current_source_position) const
  203. {
  204. VERIFY(m_state == State::SingleStepping);
  205. return m_original_source_position.value() != current_source_position;
  206. }
  207. void Debugger::remove_temporary_breakpoints()
  208. {
  209. for (auto breakpoint_address : m_state.temporary_breakpoints()) {
  210. VERIFY(m_debug_session->breakpoint_exists(breakpoint_address));
  211. bool rc = m_debug_session->remove_breakpoint(breakpoint_address);
  212. VERIFY(rc);
  213. }
  214. m_state.clear_temporary_breakpoints();
  215. }
  216. void Debugger::DebuggingState::clear_temporary_breakpoints()
  217. {
  218. m_addresses_of_temporary_breakpoints.clear();
  219. }
  220. void Debugger::DebuggingState::add_temporary_breakpoint(FlatPtr address)
  221. {
  222. m_addresses_of_temporary_breakpoints.append(address);
  223. }
  224. void Debugger::do_step_out(PtraceRegisters const& regs)
  225. {
  226. // To step out, we simply insert a temporary breakpoint at the
  227. // instruction the current function returns to, and continue
  228. // execution until we hit that instruction (or some other breakpoint).
  229. insert_temporary_breakpoint_at_return_address(regs);
  230. }
  231. void Debugger::do_step_over(PtraceRegisters const& regs)
  232. {
  233. // To step over, we insert a temporary breakpoint at each line in the current function,
  234. // as well as at the current function's return point, and continue execution.
  235. auto lib = m_debug_session->library_at(regs.ip());
  236. if (!lib)
  237. return;
  238. auto current_function = lib->debug_info->get_containing_function(regs.ip() - lib->base_address);
  239. if (!current_function.has_value()) {
  240. dbgln("cannot perform step_over, failed to find containing function of: {:p}", regs.ip());
  241. return;
  242. }
  243. VERIFY(current_function.has_value());
  244. auto lines_in_current_function = lib->debug_info->source_lines_in_scope(current_function.value());
  245. for (auto const& line : lines_in_current_function) {
  246. insert_temporary_breakpoint(line.address_of_first_statement.value() + lib->base_address);
  247. }
  248. insert_temporary_breakpoint_at_return_address(regs);
  249. }
  250. void Debugger::insert_temporary_breakpoint_at_return_address(PtraceRegisters const& regs)
  251. {
  252. auto frame_info = Debug::StackFrameUtils::get_info(*m_debug_session, regs.bp());
  253. VERIFY(frame_info.has_value());
  254. FlatPtr return_address = frame_info.value().return_address;
  255. insert_temporary_breakpoint(return_address);
  256. }
  257. void Debugger::insert_temporary_breakpoint(FlatPtr address)
  258. {
  259. if (m_debug_session->breakpoint_exists(address))
  260. return;
  261. bool success = m_debug_session->insert_breakpoint(address);
  262. VERIFY(success);
  263. m_state.add_temporary_breakpoint(address);
  264. }
  265. void Debugger::set_requested_debugger_action(DebuggerAction action)
  266. {
  267. pthread_mutex_lock(continue_mutex());
  268. m_requested_debugger_action = action;
  269. pthread_cond_signal(continue_cond());
  270. pthread_mutex_unlock(continue_mutex());
  271. }
  272. }