Debugger.cpp 11 KB

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