Debugger.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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_continue_mutex, nullptr);
  55. pthread_cond_init(&m_continue_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 statemanet).
  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([&](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_continue_mutex);
  135. pthread_cond_wait(&m_continue_cond, &m_continue_mutex);
  136. pthread_mutex_unlock(&m_continue_mutex);
  137. m_on_continue_callback();
  138. } else {
  139. m_continue_type = ContinueType::Continue;
  140. }
  141. switch (m_continue_type) {
  142. case ContinueType::Continue:
  143. m_state.set_normal();
  144. return Debug::DebugSession::DebugDecision::Continue;
  145. case ContinueType::SourceSingleStep:
  146. m_state.set_single_stepping(source_position.value());
  147. return Debug::DebugSession::DebugDecision::SingleStep;
  148. case ContinueType::SourceStepOut:
  149. m_state.set_stepping_out();
  150. do_step_out(regs);
  151. return Debug::DebugSession::DebugDecision::Continue;
  152. case ContinueType::SourceStepOver:
  153. m_state.set_stepping_over();
  154. do_step_over(regs);
  155. return Debug::DebugSession::DebugDecision::Continue;
  156. }
  157. ASSERT_NOT_REACHED();
  158. });
  159. m_debug_session.clear();
  160. return 0;
  161. }
  162. void Debugger::DebuggingState::set_normal()
  163. {
  164. m_state = State::Normal;
  165. m_original_source_position.clear();
  166. }
  167. void Debugger::DebuggingState::set_single_stepping(Debug::DebugInfo::SourcePosition original_source_position)
  168. {
  169. m_state = State::SingleStepping;
  170. m_original_source_position = original_source_position;
  171. }
  172. bool Debugger::DebuggingState::should_stop_single_stepping(const Debug::DebugInfo::SourcePosition& current_source_position) const
  173. {
  174. ASSERT(m_state == State::SingleStepping);
  175. return m_original_source_position.value() != current_source_position;
  176. }
  177. void Debugger::remove_temporary_breakpoints()
  178. {
  179. for (auto breakpoint_address : m_state.temporary_breakpoints()) {
  180. ASSERT(m_debug_session->breakpoint_exists((void*)breakpoint_address));
  181. bool rc = m_debug_session->remove_breakpoint((void*)breakpoint_address);
  182. ASSERT(rc);
  183. }
  184. m_state.clear_temporary_breakpoints();
  185. }
  186. void Debugger::DebuggingState::clear_temporary_breakpoints()
  187. {
  188. m_addresses_of_temporary_breakpoints.clear();
  189. }
  190. void Debugger::DebuggingState::add_temporary_breakpoint(u32 address)
  191. {
  192. m_addresses_of_temporary_breakpoints.append(address);
  193. }
  194. void Debugger::do_step_out(const PtraceRegisters& regs)
  195. {
  196. // To step out, we simply insert a temporary breakpoint at the
  197. // instruction the current function returns to, and continue
  198. // execution until we hit that instruction (or some other breakpoint).
  199. insert_temporary_breakpoint_at_return_address(regs);
  200. }
  201. void Debugger::do_step_over(const PtraceRegisters& regs)
  202. {
  203. // To step over, we insert a temporary breakpoint at each line in the current function,
  204. // as well as at the current function's return point, and continue execution.
  205. auto current_function = m_debug_session->debug_info().get_containing_function(regs.eip);
  206. ASSERT(current_function.has_value());
  207. auto lines_in_current_function = m_debug_session->debug_info().source_lines_in_scope(current_function.value());
  208. for (const auto& line : lines_in_current_function) {
  209. insert_temporary_breakpoint(line.address_of_first_statement);
  210. }
  211. insert_temporary_breakpoint_at_return_address(regs);
  212. }
  213. void Debugger::insert_temporary_breakpoint_at_return_address(const PtraceRegisters& regs)
  214. {
  215. auto frame_info = Debug::StackFrameUtils::get_info(*m_debug_session, regs.ebp);
  216. ASSERT(frame_info.has_value());
  217. u32 return_address = frame_info.value().return_address;
  218. insert_temporary_breakpoint(return_address);
  219. }
  220. void Debugger::insert_temporary_breakpoint(FlatPtr address)
  221. {
  222. if (m_debug_session->breakpoint_exists((void*)address))
  223. return;
  224. bool success = m_debug_session->insert_breakpoint(reinterpret_cast<void*>(address));
  225. ASSERT(success);
  226. m_state.add_temporary_breakpoint(address);
  227. }
  228. }