DebugSession.cpp 7.9 KB

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