DebugSession.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 "DebugSession.h"
  27. #include <AK/Optional.h>
  28. #include <stdlib.h>
  29. namespace Debug {
  30. DebugSession::DebugSession(int pid)
  31. : m_debuggee_pid(pid)
  32. , m_executable(initialize_executable_mapped_file(pid))
  33. , m_elf(ELF::Loader::create(reinterpret_cast<const u8*>(m_executable->data()), m_executable->size()))
  34. , m_debug_info(m_elf)
  35. {
  36. }
  37. NonnullOwnPtr<const MappedFile> DebugSession::initialize_executable_mapped_file(int pid)
  38. {
  39. auto executable = adopt_own(*new MappedFile(String::format("/proc/%d/exe", pid)));
  40. ASSERT(executable->is_valid());
  41. return executable;
  42. }
  43. DebugSession::~DebugSession()
  44. {
  45. if (m_is_debuggee_dead)
  46. return;
  47. for (const auto& bp : m_breakpoints) {
  48. disable_breakpoint(bp.key);
  49. }
  50. m_breakpoints.clear();
  51. if (ptrace(PT_DETACH, m_debuggee_pid, 0, 0) < 0) {
  52. perror("PT_DETACH");
  53. }
  54. }
  55. OwnPtr<DebugSession> DebugSession::exec_and_attach(const String& command)
  56. {
  57. int pid = fork();
  58. if (!pid) {
  59. if (ptrace(PT_TRACE_ME, 0, 0, 0) < 0) {
  60. perror("PT_TRACE_ME");
  61. exit(1);
  62. }
  63. auto parts = command.split(' ');
  64. ASSERT(!parts.is_empty());
  65. const char** args = (const char**)calloc(parts.size() + 1, sizeof(const char*));
  66. for (size_t i = 0; i < parts.size(); i++) {
  67. args[i] = parts[i].characters();
  68. }
  69. int rc = execvp(args[0], const_cast<char**>(args));
  70. if (rc < 0) {
  71. perror("execvp");
  72. }
  73. ASSERT_NOT_REACHED();
  74. }
  75. if (waitpid(pid, nullptr, WSTOPPED) != pid) {
  76. perror("waitpid");
  77. return nullptr;
  78. }
  79. if (ptrace(PT_ATTACH, pid, 0, 0) < 0) {
  80. perror("PT_ATTACH");
  81. return nullptr;
  82. }
  83. if (waitpid(pid, nullptr, WSTOPPED) != pid) {
  84. perror("waitpid");
  85. return nullptr;
  86. }
  87. if (ptrace(PT_CONTINUE, pid, 0, 0) < 0) {
  88. perror("continue");
  89. return nullptr;
  90. }
  91. // We want to continue until the exit from the 'execve' sycsall.
  92. // This ensures that when we start debugging the process
  93. // it executes the target image, and not the forked image of the tracing process.
  94. // NOTE: we only need to do this when we are debugging a new process (i.e not attaching to a process that's already running!)
  95. if (waitpid(pid, nullptr, WSTOPPED) != pid) {
  96. perror("wait_pid");
  97. return nullptr;
  98. }
  99. return make<DebugSession>(pid);
  100. }
  101. bool DebugSession::poke(u32* address, u32 data)
  102. {
  103. if (ptrace(PT_POKE, m_debuggee_pid, (void*)address, data) < 0) {
  104. perror("PT_POKE");
  105. return false;
  106. }
  107. return true;
  108. }
  109. Optional<u32> DebugSession::peek(u32* address) const
  110. {
  111. Optional<u32> result;
  112. int rc = ptrace(PT_PEEK, m_debuggee_pid, (void*)address, 0);
  113. if (errno == 0)
  114. result = static_cast<u32>(rc);
  115. return result;
  116. }
  117. bool DebugSession::insert_breakpoint(void* address)
  118. {
  119. // We insert a software breakpoint by
  120. // patching the first byte of the instruction at 'address'
  121. // with the breakpoint instruction (int3)
  122. if (m_breakpoints.contains(address))
  123. return false;
  124. auto original_bytes = peek(reinterpret_cast<u32*>(address));
  125. if (!original_bytes.has_value())
  126. return false;
  127. ASSERT((original_bytes.value() & 0xff) != BREAKPOINT_INSTRUCTION);
  128. BreakPoint breakpoint { address, original_bytes.value(), BreakPointState::Disabled };
  129. m_breakpoints.set(address, breakpoint);
  130. enable_breakpoint(breakpoint.address);
  131. return true;
  132. }
  133. bool DebugSession::disable_breakpoint(void* address)
  134. {
  135. auto breakpoint = m_breakpoints.get(address);
  136. ASSERT(breakpoint.has_value());
  137. if (!poke(reinterpret_cast<u32*>(reinterpret_cast<char*>(breakpoint.value().address)), breakpoint.value().original_first_word))
  138. return false;
  139. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  140. bp.state = BreakPointState::Disabled;
  141. m_breakpoints.set(bp.address, bp);
  142. return true;
  143. }
  144. bool DebugSession::enable_breakpoint(void* address)
  145. {
  146. auto breakpoint = m_breakpoints.get(address);
  147. ASSERT(breakpoint.has_value());
  148. ASSERT(breakpoint.value().state == BreakPointState::Disabled);
  149. if (!poke(reinterpret_cast<u32*>(breakpoint.value().address), (breakpoint.value().original_first_word & ~(uint32_t)0xff) | BREAKPOINT_INSTRUCTION))
  150. return false;
  151. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  152. bp.state = BreakPointState::Enabled;
  153. m_breakpoints.set(bp.address, bp);
  154. return true;
  155. }
  156. bool DebugSession::remove_breakpoint(void* address)
  157. {
  158. if (!disable_breakpoint(address))
  159. return false;
  160. m_breakpoints.remove(address);
  161. return true;
  162. }
  163. bool DebugSession::breakpoint_exists(void* address) const
  164. {
  165. return m_breakpoints.contains(address);
  166. }
  167. PtraceRegisters DebugSession::get_registers() const
  168. {
  169. PtraceRegisters regs;
  170. if (ptrace(PT_GETREGS, m_debuggee_pid, &regs, 0) < 0) {
  171. perror("PT_GETREGS");
  172. ASSERT_NOT_REACHED();
  173. }
  174. return regs;
  175. }
  176. void DebugSession::set_registers(const PtraceRegisters& regs)
  177. {
  178. if (ptrace(PT_SETREGS, m_debuggee_pid, reinterpret_cast<void*>(&const_cast<PtraceRegisters&>(regs)), 0) < 0) {
  179. perror("PT_SETREGS");
  180. ASSERT_NOT_REACHED();
  181. }
  182. }
  183. void DebugSession::continue_debuggee(ContinueType type)
  184. {
  185. int command = (type == ContinueType::FreeRun) ? PT_CONTINUE : PT_SYSCALL;
  186. if (ptrace(command, m_debuggee_pid, 0, 0) < 0) {
  187. perror("continue");
  188. ASSERT_NOT_REACHED();
  189. }
  190. }
  191. int DebugSession::continue_debuggee_and_wait(ContinueType type)
  192. {
  193. continue_debuggee(type);
  194. int wstatus = 0;
  195. if (waitpid(m_debuggee_pid, &wstatus, WSTOPPED | WEXITED) != m_debuggee_pid) {
  196. perror("waitpid");
  197. ASSERT_NOT_REACHED();
  198. }
  199. return wstatus;
  200. }
  201. void* DebugSession::single_step()
  202. {
  203. // Single stepping works by setting the x86 TRAP flag bit in the eflags register.
  204. // This flag causes the cpu to enter single-stepping mode, which causes
  205. // Interrupt 1 (debug interrupt) to be emitted after every instruction.
  206. // To single step the program, we set the TRAP flag and continue the debuggee.
  207. // After the debuggee has stopped, we clear the TRAP flag.
  208. auto regs = get_registers();
  209. constexpr u32 TRAP_FLAG = 0x100;
  210. regs.eflags |= TRAP_FLAG;
  211. set_registers(regs);
  212. continue_debuggee();
  213. if (waitpid(m_debuggee_pid, 0, WSTOPPED) != m_debuggee_pid) {
  214. perror("waitpid");
  215. ASSERT_NOT_REACHED();
  216. }
  217. regs = get_registers();
  218. regs.eflags &= ~(TRAP_FLAG);
  219. set_registers(regs);
  220. return (void*)regs.eip;
  221. }
  222. void DebugSession::detach()
  223. {
  224. for (auto& breakpoint : m_breakpoints.keys()) {
  225. remove_breakpoint(breakpoint);
  226. }
  227. continue_debuggee();
  228. }
  229. }