DebugSession.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. #pragma once
  27. #include <AK/Demangle.h>
  28. #include <AK/HashMap.h>
  29. #include <AK/MappedFile.h>
  30. #include <AK/NonnullRefPtr.h>
  31. #include <AK/Optional.h>
  32. #include <AK/OwnPtr.h>
  33. #include <AK/String.h>
  34. #include <LibC/sys/arch/i386/regs.h>
  35. #include <LibDebug/DebugInfo.h>
  36. #include <LibELF/Loader.h>
  37. #include <signal.h>
  38. #include <stdio.h>
  39. #include <sys/ptrace.h>
  40. #include <sys/wait.h>
  41. #include <unistd.h>
  42. namespace Debug {
  43. class DebugSession {
  44. public:
  45. static OwnPtr<DebugSession> exec_and_attach(const String& command);
  46. // Has to be public for OwnPtr::make
  47. DebugSession(int pid);
  48. ~DebugSession();
  49. int pid() const { return m_debuggee_pid; }
  50. bool poke(u32* address, u32 data);
  51. Optional<u32> peek(u32* address) const;
  52. enum class BreakPointState {
  53. Enabled,
  54. Disabled,
  55. };
  56. struct BreakPoint {
  57. void* address;
  58. u32 original_first_word;
  59. BreakPointState state;
  60. };
  61. bool insert_breakpoint(void* address);
  62. bool disable_breakpoint(void* address);
  63. bool enable_breakpoint(void* address);
  64. bool remove_breakpoint(void* address);
  65. bool breakpoint_exists(void* address) const;
  66. void dump_breakpoints()
  67. {
  68. for (auto addr : m_breakpoints.keys()) {
  69. dbg() << addr;
  70. }
  71. }
  72. PtraceRegisters get_registers() const;
  73. void set_registers(const PtraceRegisters&);
  74. enum class ContinueType {
  75. FreeRun,
  76. Syscall,
  77. };
  78. void continue_debuggee(ContinueType type = ContinueType::FreeRun);
  79. // Returns the wstatus result of waitpid()
  80. int continue_debuggee_and_wait(ContinueType type = ContinueType::FreeRun);
  81. // Returns the new eip
  82. void* single_step();
  83. void detach();
  84. template<typename Callback>
  85. void run(Callback callback);
  86. const ELF::Loader& elf() const { return *m_elf; }
  87. NonnullRefPtr<const ELF::Loader> elf_ref() const { return m_elf; }
  88. const MappedFile& executable() const { return *m_executable; }
  89. const DebugInfo& debug_info() const { return m_debug_info; }
  90. enum DebugDecision {
  91. Continue,
  92. SingleStep,
  93. ContinueBreakAtSyscall,
  94. Detach,
  95. Kill,
  96. };
  97. enum DebugBreakReason {
  98. Breakpoint,
  99. Syscall,
  100. Exited,
  101. };
  102. private:
  103. // x86 breakpoint instruction "int3"
  104. static constexpr u8 BREAKPOINT_INSTRUCTION = 0xcc;
  105. static NonnullOwnPtr<const MappedFile> initialize_executable_mapped_file(int pid);
  106. int m_debuggee_pid { -1 };
  107. bool m_is_debuggee_dead { false };
  108. NonnullOwnPtr<const MappedFile> m_executable;
  109. NonnullRefPtr<const ELF::Loader> m_elf;
  110. DebugInfo m_debug_info;
  111. HashMap<void*, BreakPoint> m_breakpoints;
  112. };
  113. template<typename Callback>
  114. void DebugSession::run(Callback callback)
  115. {
  116. enum class State {
  117. FreeRun,
  118. Syscall,
  119. ConsecutiveBreakpoint,
  120. SingleStep,
  121. };
  122. State state { State::FreeRun };
  123. auto do_continue_and_wait = [&]() {
  124. int wstatus = continue_debuggee_and_wait((state == State::FreeRun) ? ContinueType::FreeRun : ContinueType::Syscall);
  125. // FIXME: This check actually only checks whether the debuggee
  126. // stopped because it hit a breakpoint/syscall/is in single stepping mode or not
  127. if (WSTOPSIG(wstatus) != SIGTRAP) {
  128. callback(DebugBreakReason::Exited, Optional<PtraceRegisters>());
  129. m_is_debuggee_dead = true;
  130. return true;
  131. }
  132. return false;
  133. };
  134. for (;;) {
  135. if (state == State::FreeRun || state == State::Syscall) {
  136. if (do_continue_and_wait())
  137. break;
  138. }
  139. auto regs = get_registers();
  140. Optional<BreakPoint> current_breakpoint;
  141. if (state == State::FreeRun || state == State::Syscall) {
  142. current_breakpoint = m_breakpoints.get((void*)((u32)regs.eip - 1));
  143. if (current_breakpoint.has_value())
  144. state = State::FreeRun;
  145. } else {
  146. current_breakpoint = m_breakpoints.get((void*)regs.eip);
  147. }
  148. if (current_breakpoint.has_value()) {
  149. // We want to make the breakpoint transparent to the user of the debugger.
  150. // To achieive this, we perform two rollbacks:
  151. // 1. Set regs.eip to point at the actual address of the instruction we breaked on.
  152. // regs.eip currently points to one byte after the address of the original instruction,
  153. // because the cpu has just executed the INT3 we patched into the instruction.
  154. // 2. We restore the original first byte of the instruction,
  155. // because it was patched with INT3.
  156. regs.eip = reinterpret_cast<u32>(current_breakpoint.value().address);
  157. set_registers(regs);
  158. disable_breakpoint(current_breakpoint.value().address);
  159. }
  160. DebugBreakReason reason = (state == State::Syscall && !current_breakpoint.has_value()) ? DebugBreakReason::Syscall : DebugBreakReason::Breakpoint;
  161. DebugDecision decision = callback(reason, regs);
  162. if (reason == DebugBreakReason::Syscall) {
  163. // skip the exit from the syscall
  164. if (do_continue_and_wait())
  165. break;
  166. }
  167. if (decision == DebugDecision::Continue) {
  168. state = State::FreeRun;
  169. } else if (decision == DebugDecision::ContinueBreakAtSyscall) {
  170. state = State::Syscall;
  171. }
  172. bool did_single_step = false;
  173. // Re-enable the breakpoint if it wasn't removed by the user
  174. if (current_breakpoint.has_value() && m_breakpoints.contains(current_breakpoint.value().address)) {
  175. // The current breakpoint was removed to make it transparent to the user.
  176. // We now want to re-enable it - the code execution flow could hit it again.
  177. // To re-enable the breakpoint, we first perform a single step and execute the
  178. // instruction of the breakpoint, and then redo the INT3 patch in its first byte.
  179. // If the user manually inserted a breakpoint at were we breaked at originally,
  180. // we need to disable that breakpoint because we want to singlestep over it to execute the
  181. // instruction we breaked on (we re-enable it again later anyways).
  182. if (m_breakpoints.contains(current_breakpoint.value().address) && m_breakpoints.get(current_breakpoint.value().address).value().state == BreakPointState::Enabled) {
  183. disable_breakpoint(current_breakpoint.value().address);
  184. }
  185. auto stopped_address = single_step();
  186. enable_breakpoint(current_breakpoint.value().address);
  187. did_single_step = true;
  188. // If there is another breakpoint after the current one,
  189. // Then we are already on it (because of single_step)
  190. auto breakpoint_at_next_instruction = m_breakpoints.get(stopped_address);
  191. if (breakpoint_at_next_instruction.has_value()
  192. && breakpoint_at_next_instruction.value().state == BreakPointState::Enabled) {
  193. state = State::ConsecutiveBreakpoint;
  194. }
  195. }
  196. if (decision == DebugDecision::SingleStep) {
  197. state = State::SingleStep;
  198. }
  199. if (decision == DebugDecision::Detach) {
  200. detach();
  201. break;
  202. }
  203. if (decision == DebugDecision::Kill) {
  204. ASSERT_NOT_REACHED(); // TODO: implement
  205. }
  206. if (state == State::SingleStep && !did_single_step) {
  207. single_step();
  208. }
  209. }
  210. }
  211. }