DebugSession.cpp 7.8 KB

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