DebugSession.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Demangle.h>
  8. #include <AK/Function.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/Optional.h>
  12. #include <AK/OwnPtr.h>
  13. #include <AK/String.h>
  14. #include <LibC/sys/arch/i386/regs.h>
  15. #include <LibCore/MappedFile.h>
  16. #include <LibDebug/DebugInfo.h>
  17. #include <LibDebug/ProcessInspector.h>
  18. #include <signal.h>
  19. #include <stdio.h>
  20. #include <sys/ptrace.h>
  21. #include <sys/wait.h>
  22. #include <unistd.h>
  23. namespace Debug {
  24. class DebugSession : public ProcessInspector {
  25. public:
  26. static OwnPtr<DebugSession> exec_and_attach(String const& command, String source_root = {}, Function<ErrorOr<void>()> setup_child = {});
  27. virtual ~DebugSession() override;
  28. // ^Debug::ProcessInspector
  29. virtual bool poke(FlatPtr address, FlatPtr data) override;
  30. virtual Optional<FlatPtr> peek(FlatPtr address) const override;
  31. virtual PtraceRegisters get_registers() const override;
  32. virtual void set_registers(PtraceRegisters const&) override;
  33. virtual void for_each_loaded_library(Function<IterationDecision(LoadedLibrary const&)>) const override;
  34. int pid() const { return m_debuggee_pid; }
  35. bool poke_debug(u32 register_index, FlatPtr data) const;
  36. Optional<FlatPtr> peek_debug(u32 register_index) const;
  37. enum class BreakPointState {
  38. Enabled,
  39. Disabled,
  40. };
  41. struct BreakPoint {
  42. FlatPtr address { 0 };
  43. FlatPtr original_first_word { 0 };
  44. BreakPointState state { BreakPointState::Disabled };
  45. };
  46. struct InsertBreakpointAtSymbolResult {
  47. String library_name;
  48. FlatPtr address { 0 };
  49. };
  50. Optional<InsertBreakpointAtSymbolResult> insert_breakpoint(String const& symbol_name);
  51. struct InsertBreakpointAtSourcePositionResult {
  52. String library_name;
  53. String filename;
  54. size_t line_number { 0 };
  55. FlatPtr address { 0 };
  56. };
  57. Optional<InsertBreakpointAtSourcePositionResult> insert_breakpoint(String const& filename, size_t line_number);
  58. bool insert_breakpoint(FlatPtr address);
  59. bool disable_breakpoint(FlatPtr address);
  60. bool enable_breakpoint(FlatPtr address);
  61. bool remove_breakpoint(FlatPtr address);
  62. bool breakpoint_exists(FlatPtr address) const;
  63. struct WatchPoint {
  64. FlatPtr address { 0 };
  65. u32 debug_register_index { 0 };
  66. u32 ebp { 0 };
  67. };
  68. bool insert_watchpoint(FlatPtr address, u32 ebp);
  69. bool remove_watchpoint(FlatPtr address);
  70. bool disable_watchpoint(FlatPtr address);
  71. bool watchpoint_exists(FlatPtr address) const;
  72. void dump_breakpoints()
  73. {
  74. for (auto addr : m_breakpoints.keys()) {
  75. dbgln("{}", addr);
  76. }
  77. }
  78. enum class ContinueType {
  79. FreeRun,
  80. Syscall,
  81. };
  82. void continue_debuggee(ContinueType type = ContinueType::FreeRun);
  83. // Returns the wstatus result of waitpid()
  84. int continue_debuggee_and_wait(ContinueType type = ContinueType::FreeRun);
  85. // Returns the new eip
  86. FlatPtr single_step();
  87. void detach();
  88. enum DesiredInitialDebugeeState {
  89. Running,
  90. Stopped
  91. };
  92. template<typename Callback>
  93. void run(DesiredInitialDebugeeState, Callback);
  94. enum DebugDecision {
  95. Continue,
  96. SingleStep,
  97. ContinueBreakAtSyscall,
  98. Detach,
  99. Kill,
  100. };
  101. enum DebugBreakReason {
  102. Breakpoint,
  103. Syscall,
  104. Exited,
  105. };
  106. private:
  107. explicit DebugSession(pid_t, String source_root);
  108. // x86 breakpoint instruction "int3"
  109. static constexpr u8 BREAKPOINT_INSTRUCTION = 0xcc;
  110. void update_loaded_libs();
  111. int m_debuggee_pid { -1 };
  112. String m_source_root;
  113. bool m_is_debuggee_dead { false };
  114. HashMap<FlatPtr, BreakPoint> m_breakpoints;
  115. HashMap<FlatPtr, WatchPoint> m_watchpoints;
  116. // Maps from library name to LoadedLibrary object
  117. HashMap<String, NonnullOwnPtr<LoadedLibrary>> m_loaded_libraries;
  118. };
  119. template<typename Callback>
  120. void DebugSession::run(DesiredInitialDebugeeState initial_debugee_state, Callback callback)
  121. {
  122. enum class State {
  123. FirstIteration,
  124. FreeRun,
  125. Syscall,
  126. ConsecutiveBreakpoint,
  127. SingleStep,
  128. };
  129. State state { State::FirstIteration };
  130. auto do_continue_and_wait = [&]() {
  131. int wstatus = continue_debuggee_and_wait((state == State::Syscall) ? ContinueType::Syscall : ContinueType::FreeRun);
  132. // FIXME: This check actually only checks whether the debuggee
  133. // stopped because it hit a breakpoint/syscall/is in single stepping mode or not
  134. if (WSTOPSIG(wstatus) != SIGTRAP) {
  135. callback(DebugBreakReason::Exited, Optional<PtraceRegisters>());
  136. m_is_debuggee_dead = true;
  137. return true;
  138. }
  139. return false;
  140. };
  141. for (;;) {
  142. if ((state == State::FirstIteration && initial_debugee_state == DesiredInitialDebugeeState::Running) || state == State::FreeRun || state == State::Syscall) {
  143. if (do_continue_and_wait())
  144. break;
  145. }
  146. if (state == State::FirstIteration)
  147. state = State::FreeRun;
  148. auto regs = get_registers();
  149. #if ARCH(I386)
  150. FlatPtr current_instruction = regs.eip;
  151. #else
  152. FlatPtr current_instruction = regs.rip;
  153. #endif
  154. auto debug_status = peek_debug(DEBUG_STATUS_REGISTER);
  155. if (debug_status.has_value() && (debug_status.value() & 0b1111) > 0) {
  156. // Tripped a watchpoint
  157. auto watchpoint_index = debug_status.value() & 0b1111;
  158. Optional<WatchPoint> watchpoint {};
  159. for (auto wp : m_watchpoints) {
  160. if ((watchpoint_index & (1 << wp.value.debug_register_index)) == 0)
  161. continue;
  162. watchpoint = wp.value;
  163. break;
  164. }
  165. if (watchpoint.has_value()) {
  166. auto required_ebp = watchpoint.value().ebp;
  167. auto found_ebp = false;
  168. #if ARCH(I386)
  169. FlatPtr current_ebp = regs.ebp;
  170. #else
  171. FlatPtr current_ebp = regs.rbp;
  172. #endif
  173. do {
  174. if (current_ebp == required_ebp) {
  175. found_ebp = true;
  176. break;
  177. }
  178. auto return_address = peek(current_ebp + sizeof(FlatPtr));
  179. auto next_ebp = peek(current_ebp);
  180. VERIFY(return_address.has_value());
  181. VERIFY(next_ebp.has_value());
  182. current_instruction = return_address.value();
  183. current_ebp = next_ebp.value();
  184. } while (current_ebp && current_instruction);
  185. if (!found_ebp) {
  186. dbgln("Removing watchpoint at {:p} because it went out of scope!", watchpoint.value().address);
  187. remove_watchpoint(watchpoint.value().address);
  188. continue;
  189. }
  190. }
  191. }
  192. Optional<BreakPoint> current_breakpoint;
  193. if (state == State::FreeRun || state == State::Syscall) {
  194. current_breakpoint = m_breakpoints.get(current_instruction - 1);
  195. if (current_breakpoint.has_value())
  196. state = State::FreeRun;
  197. } else {
  198. current_breakpoint = m_breakpoints.get(current_instruction);
  199. }
  200. if (current_breakpoint.has_value()) {
  201. // We want to make the breakpoint transparent to the user of the debugger.
  202. // To achieve this, we perform two rollbacks:
  203. // 1. Set regs.eip to point at the actual address of the instruction we broke on.
  204. // regs.eip currently points to one byte after the address of the original instruction,
  205. // because the cpu has just executed the INT3 we patched into the instruction.
  206. // 2. We restore the original first byte of the instruction,
  207. // because it was patched with INT3.
  208. auto breakpoint_addr = bit_cast<FlatPtr>(current_breakpoint.value().address);
  209. #if ARCH(I386)
  210. regs.eip = breakpoint_addr;
  211. #else
  212. regs.rip = breakpoint_addr;
  213. #endif
  214. set_registers(regs);
  215. disable_breakpoint(current_breakpoint.value().address);
  216. }
  217. DebugBreakReason reason = (state == State::Syscall && !current_breakpoint.has_value()) ? DebugBreakReason::Syscall : DebugBreakReason::Breakpoint;
  218. DebugDecision decision = callback(reason, regs);
  219. if (reason == DebugBreakReason::Syscall) {
  220. // skip the exit from the syscall
  221. if (do_continue_and_wait())
  222. break;
  223. }
  224. if (decision == DebugDecision::Continue) {
  225. state = State::FreeRun;
  226. } else if (decision == DebugDecision::ContinueBreakAtSyscall) {
  227. state = State::Syscall;
  228. }
  229. bool did_single_step = false;
  230. auto current_breakpoint_address = bit_cast<FlatPtr>(current_breakpoint.value().address);
  231. // Re-enable the breakpoint if it wasn't removed by the user
  232. if (current_breakpoint.has_value() && m_breakpoints.contains(current_breakpoint_address)) {
  233. // The current breakpoint was removed to make it transparent to the user.
  234. // We now want to re-enable it - the code execution flow could hit it again.
  235. // To re-enable the breakpoint, we first perform a single step and execute the
  236. // instruction of the breakpoint, and then redo the INT3 patch in its first byte.
  237. // If the user manually inserted a breakpoint at the current instruction,
  238. // we need to disable that breakpoint because we want to singlestep over that
  239. // instruction (we re-enable it again later anyways).
  240. if (m_breakpoints.contains(current_breakpoint_address) && m_breakpoints.get(current_breakpoint_address).value().state == BreakPointState::Enabled) {
  241. disable_breakpoint(current_breakpoint.value().address);
  242. }
  243. auto stopped_address = single_step();
  244. enable_breakpoint(current_breakpoint.value().address);
  245. did_single_step = true;
  246. // If there is another breakpoint after the current one,
  247. // Then we are already on it (because of single_step)
  248. auto breakpoint_at_next_instruction = m_breakpoints.get(stopped_address);
  249. if (breakpoint_at_next_instruction.has_value()
  250. && breakpoint_at_next_instruction.value().state == BreakPointState::Enabled) {
  251. state = State::ConsecutiveBreakpoint;
  252. }
  253. }
  254. if (decision == DebugDecision::SingleStep) {
  255. state = State::SingleStep;
  256. }
  257. if (decision == DebugDecision::Detach) {
  258. detach();
  259. break;
  260. }
  261. if (decision == DebugDecision::Kill) {
  262. kill(m_debuggee_pid, SIGTERM);
  263. break;
  264. }
  265. if (state == State::SingleStep && !did_single_step) {
  266. single_step();
  267. }
  268. }
  269. }
  270. }