Debugger.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 "Debugger.h"
  27. #include <LibDebug/StackFrameUtils.h>
  28. namespace HackStudio {
  29. static Debugger* s_the;
  30. Debugger& Debugger::the()
  31. {
  32. ASSERT(s_the);
  33. return *s_the;
  34. }
  35. void Debugger::initialize(
  36. Function<HasControlPassedToUser(const PtraceRegisters&)> on_stop_callback,
  37. Function<void()> on_continue_callback,
  38. Function<void()> on_exit_callback)
  39. {
  40. s_the = new Debugger(move(on_stop_callback), move(on_continue_callback), move(on_exit_callback));
  41. }
  42. bool Debugger::is_initialized()
  43. {
  44. return s_the;
  45. }
  46. Debugger::Debugger(
  47. Function<HasControlPassedToUser(const PtraceRegisters&)> on_stop_callback,
  48. Function<void()> on_continue_callback,
  49. Function<void()> on_exit_callback)
  50. : m_on_stopped_callback(move(on_stop_callback))
  51. , m_on_continue_callback(move(on_continue_callback))
  52. , m_on_exit_callback(move(on_exit_callback))
  53. {
  54. pthread_mutex_init(&m_ui_action_mutex, nullptr);
  55. pthread_cond_init(&m_ui_action_cond, nullptr);
  56. }
  57. void Debugger::on_breakpoint_change(const String& file, size_t line, BreakpointChange change_type)
  58. {
  59. auto position = create_source_position(file, line);
  60. if (change_type == BreakpointChange::Added) {
  61. Debugger::the().m_breakpoints.append(position);
  62. } else {
  63. Debugger::the().m_breakpoints.remove_all_matching([&](Debug::DebugInfo::SourcePosition val) { return val == position; });
  64. }
  65. auto session = Debugger::the().session();
  66. if (!session)
  67. return;
  68. auto address = session->debug_info().get_instruction_from_source(position.file_path, position.line_number);
  69. if (!address.has_value()) {
  70. dbg() << "Warning: couldn't get instruction address from source";
  71. // TODO: Currently, the GUI will indicate that a breakpoint was inserted/removed at this line,
  72. // regardless of whether we actually succeeded to insert it. (For example a breakpoint on a comment, or an include statement).
  73. // We should indicate failure via a return value from this function, and not update the breakpoint GUI if we fail.
  74. return;
  75. }
  76. if (change_type == BreakpointChange::Added) {
  77. bool success = session->insert_breakpoint(reinterpret_cast<void*>(address.value()));
  78. ASSERT(success);
  79. } else {
  80. bool success = session->remove_breakpoint(reinterpret_cast<void*>(address.value()));
  81. ASSERT(success);
  82. }
  83. }
  84. Debug::DebugInfo::SourcePosition Debugger::create_source_position(const String& file, size_t line)
  85. {
  86. if (!file.starts_with('/') && !file.starts_with("./"))
  87. return { String::format("./%s", file.characters()), line + 1 };
  88. return { file, line + 1 };
  89. }
  90. int Debugger::start_static()
  91. {
  92. Debugger::the().start();
  93. return 0;
  94. }
  95. void Debugger::start()
  96. {
  97. m_debug_session = Debug::DebugSession::exec_and_attach(m_executable_path);
  98. ASSERT(!!m_debug_session);
  99. for (const auto& breakpoint : m_breakpoints) {
  100. dbg() << "insertig breakpoint at: " << breakpoint.file_path << ":" << breakpoint.line_number;
  101. auto address = m_debug_session->debug_info().get_instruction_from_source(breakpoint.file_path, breakpoint.line_number);
  102. if (address.has_value()) {
  103. bool success = m_debug_session->insert_breakpoint(reinterpret_cast<void*>(address.value()));
  104. ASSERT(success);
  105. } else {
  106. dbg() << "couldn't insert breakpoint";
  107. }
  108. }
  109. debugger_loop();
  110. }
  111. int Debugger::debugger_loop()
  112. {
  113. ASSERT(m_debug_session);
  114. m_debug_session->run([this](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  115. if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
  116. dbg() << "Program exited";
  117. m_on_exit_callback();
  118. return Debug::DebugSession::DebugDecision::Detach;
  119. }
  120. remove_temporary_breakpoints();
  121. ASSERT(optional_regs.has_value());
  122. const PtraceRegisters& regs = optional_regs.value();
  123. auto source_position = m_debug_session->debug_info().get_source_position(regs.eip);
  124. if (m_state.get() == Debugger::DebuggingState::SingleStepping) {
  125. ASSERT(source_position.has_value());
  126. if (m_state.should_stop_single_stepping(source_position.value())) {
  127. m_state.set_normal();
  128. } else {
  129. return Debug::DebugSession::DebugDecision::SingleStep;
  130. }
  131. }
  132. auto control_passed_to_user = m_on_stopped_callback(regs);
  133. if (control_passed_to_user == HasControlPassedToUser::Yes) {
  134. pthread_mutex_lock(&m_ui_action_mutex);
  135. pthread_cond_wait(&m_ui_action_cond, &m_ui_action_mutex);
  136. pthread_mutex_unlock(&m_ui_action_mutex);
  137. if (m_requested_debugger_action != DebuggerAction::Exit)
  138. m_on_continue_callback();
  139. } else {
  140. m_requested_debugger_action = DebuggerAction::Continue;
  141. }
  142. switch (m_requested_debugger_action) {
  143. case DebuggerAction::Continue:
  144. m_state.set_normal();
  145. return Debug::DebugSession::DebugDecision::Continue;
  146. case DebuggerAction::SourceSingleStep:
  147. m_state.set_single_stepping(source_position.value());
  148. return Debug::DebugSession::DebugDecision::SingleStep;
  149. case DebuggerAction::SourceStepOut:
  150. m_state.set_stepping_out();
  151. do_step_out(regs);
  152. return Debug::DebugSession::DebugDecision::Continue;
  153. case DebuggerAction::SourceStepOver:
  154. m_state.set_stepping_over();
  155. do_step_over(regs);
  156. return Debug::DebugSession::DebugDecision::Continue;
  157. case DebuggerAction::Exit:
  158. // NOTE: Is detaching from the debuggee the best thing to do here?
  159. // We could display a dialog in the UI, remind the user that there is
  160. // a live debugged process, and ask whether they want to terminate/detach.
  161. dbg() << "Debugger exiting";
  162. return Debug::DebugSession::DebugDecision::Detach;
  163. }
  164. ASSERT_NOT_REACHED();
  165. });
  166. m_debug_session.clear();
  167. return 0;
  168. }
  169. void Debugger::DebuggingState::set_normal()
  170. {
  171. m_state = State::Normal;
  172. m_original_source_position.clear();
  173. }
  174. void Debugger::DebuggingState::set_single_stepping(Debug::DebugInfo::SourcePosition original_source_position)
  175. {
  176. m_state = State::SingleStepping;
  177. m_original_source_position = original_source_position;
  178. }
  179. bool Debugger::DebuggingState::should_stop_single_stepping(const Debug::DebugInfo::SourcePosition& current_source_position) const
  180. {
  181. ASSERT(m_state == State::SingleStepping);
  182. return m_original_source_position.value() != current_source_position;
  183. }
  184. void Debugger::remove_temporary_breakpoints()
  185. {
  186. for (auto breakpoint_address : m_state.temporary_breakpoints()) {
  187. ASSERT(m_debug_session->breakpoint_exists((void*)breakpoint_address));
  188. bool rc = m_debug_session->remove_breakpoint((void*)breakpoint_address);
  189. ASSERT(rc);
  190. }
  191. m_state.clear_temporary_breakpoints();
  192. }
  193. void Debugger::DebuggingState::clear_temporary_breakpoints()
  194. {
  195. m_addresses_of_temporary_breakpoints.clear();
  196. }
  197. void Debugger::DebuggingState::add_temporary_breakpoint(u32 address)
  198. {
  199. m_addresses_of_temporary_breakpoints.append(address);
  200. }
  201. void Debugger::do_step_out(const PtraceRegisters& regs)
  202. {
  203. // To step out, we simply insert a temporary breakpoint at the
  204. // instruction the current function returns to, and continue
  205. // execution until we hit that instruction (or some other breakpoint).
  206. insert_temporary_breakpoint_at_return_address(regs);
  207. }
  208. void Debugger::do_step_over(const PtraceRegisters& regs)
  209. {
  210. // To step over, we insert a temporary breakpoint at each line in the current function,
  211. // as well as at the current function's return point, and continue execution.
  212. auto current_function = m_debug_session->debug_info().get_containing_function(regs.eip);
  213. ASSERT(current_function.has_value());
  214. auto lines_in_current_function = m_debug_session->debug_info().source_lines_in_scope(current_function.value());
  215. for (const auto& line : lines_in_current_function) {
  216. insert_temporary_breakpoint(line.address_of_first_statement);
  217. }
  218. insert_temporary_breakpoint_at_return_address(regs);
  219. }
  220. void Debugger::insert_temporary_breakpoint_at_return_address(const PtraceRegisters& regs)
  221. {
  222. auto frame_info = Debug::StackFrameUtils::get_info(*m_debug_session, regs.ebp);
  223. ASSERT(frame_info.has_value());
  224. u32 return_address = frame_info.value().return_address;
  225. insert_temporary_breakpoint(return_address);
  226. }
  227. void Debugger::insert_temporary_breakpoint(FlatPtr address)
  228. {
  229. if (m_debug_session->breakpoint_exists((void*)address))
  230. return;
  231. bool success = m_debug_session->insert_breakpoint(reinterpret_cast<void*>(address));
  232. ASSERT(success);
  233. m_state.add_temporary_breakpoint(address);
  234. }
  235. void Debugger::set_requested_debugger_action(DebuggerAction action)
  236. {
  237. pthread_mutex_lock(continue_mutex());
  238. m_requested_debugger_action = action;
  239. pthread_cond_signal(continue_cond());
  240. pthread_mutex_unlock(continue_mutex());
  241. }
  242. }