Debugger.cpp 11 KB

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