DebugSession.h 11 KB

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