DebugSession.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "DebugSession.h"
  7. #include <AK/JsonObject.h>
  8. #include <AK/JsonValue.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/Optional.h>
  11. #include <AK/Platform.h>
  12. #include <LibCore/File.h>
  13. #include <LibRegex/Regex.h>
  14. #include <stdlib.h>
  15. #include <sys/mman.h>
  16. namespace Debug {
  17. DebugSession::DebugSession(pid_t pid, String source_root)
  18. : m_debuggee_pid(pid)
  19. , m_source_root(source_root)
  20. {
  21. }
  22. DebugSession::~DebugSession()
  23. {
  24. if (m_is_debuggee_dead)
  25. return;
  26. for (const auto& bp : m_breakpoints) {
  27. disable_breakpoint(bp.key);
  28. }
  29. m_breakpoints.clear();
  30. for (const auto& wp : m_watchpoints) {
  31. disable_watchpoint(wp.key);
  32. }
  33. m_watchpoints.clear();
  34. if (ptrace(PT_DETACH, m_debuggee_pid, 0, 0) < 0) {
  35. perror("PT_DETACH");
  36. }
  37. }
  38. void DebugSession::for_each_loaded_library(Function<IterationDecision(LoadedLibrary const&)> func) const
  39. {
  40. for (const auto& lib_name : m_loaded_libraries.keys()) {
  41. const auto& lib = *m_loaded_libraries.get(lib_name).value();
  42. if (func(lib) == IterationDecision::Break)
  43. break;
  44. }
  45. }
  46. OwnPtr<DebugSession> DebugSession::exec_and_attach(String const& command, String source_root)
  47. {
  48. auto pid = fork();
  49. if (pid < 0) {
  50. perror("fork");
  51. exit(1);
  52. }
  53. if (!pid) {
  54. if (ptrace(PT_TRACE_ME, 0, 0, 0) < 0) {
  55. perror("PT_TRACE_ME");
  56. exit(1);
  57. }
  58. auto parts = command.split(' ');
  59. VERIFY(!parts.is_empty());
  60. const char** args = (const char**)calloc(parts.size() + 1, sizeof(const char*));
  61. for (size_t i = 0; i < parts.size(); i++) {
  62. args[i] = parts[i].characters();
  63. }
  64. const char** envp = (const char**)calloc(2, sizeof(const char*));
  65. // This causes loader to stop on a breakpoint before jumping to the entry point of the program.
  66. envp[0] = "_LOADER_BREAKPOINT=1";
  67. int rc = execvpe(args[0], const_cast<char**>(args), const_cast<char**>(envp));
  68. if (rc < 0) {
  69. perror("execvp");
  70. exit(1);
  71. }
  72. }
  73. if (waitpid(pid, nullptr, WSTOPPED) != pid) {
  74. perror("waitpid");
  75. return {};
  76. }
  77. if (ptrace(PT_ATTACH, pid, 0, 0) < 0) {
  78. perror("PT_ATTACH");
  79. return {};
  80. }
  81. // We want to continue until the exit from the 'execve' sycsall.
  82. // This ensures that when we start debugging the process
  83. // it executes the target image, and not the forked image of the tracing process.
  84. // 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!)
  85. if (waitpid(pid, nullptr, WSTOPPED) != pid) {
  86. perror("wait_pid");
  87. return {};
  88. }
  89. auto debug_session = adopt_own(*new DebugSession(pid, source_root));
  90. // Continue until breakpoint before entry point of main program
  91. int wstatus = debug_session->continue_debuggee_and_wait();
  92. if (WSTOPSIG(wstatus) != SIGTRAP) {
  93. dbgln("expected SIGTRAP");
  94. return {};
  95. }
  96. // At this point, libraries should have been loaded
  97. debug_session->update_loaded_libs();
  98. return debug_session;
  99. }
  100. bool DebugSession::poke(void* address, FlatPtr data)
  101. {
  102. if (ptrace(PT_POKE, m_debuggee_pid, (void*)address, (void*)data) < 0) {
  103. perror("PT_POKE");
  104. return false;
  105. }
  106. return true;
  107. }
  108. Optional<FlatPtr> DebugSession::peek(void* address) const
  109. {
  110. Optional<FlatPtr> result;
  111. auto rc = ptrace(PT_PEEK, m_debuggee_pid, address, nullptr);
  112. if (errno == 0)
  113. result = static_cast<FlatPtr>(rc);
  114. return result;
  115. }
  116. bool DebugSession::poke_debug(u32 register_index, FlatPtr data)
  117. {
  118. if (ptrace(PT_POKEDEBUG, m_debuggee_pid, reinterpret_cast<void*>(register_index), (void*)data) < 0) {
  119. perror("PT_POKEDEBUG");
  120. return false;
  121. }
  122. return true;
  123. }
  124. Optional<FlatPtr> DebugSession::peek_debug(u32 register_index) const
  125. {
  126. Optional<FlatPtr> result;
  127. int rc = ptrace(PT_PEEKDEBUG, m_debuggee_pid, reinterpret_cast<FlatPtr*>(register_index), nullptr);
  128. if (errno == 0)
  129. result = static_cast<FlatPtr>(rc);
  130. return result;
  131. }
  132. bool DebugSession::insert_breakpoint(void* address)
  133. {
  134. // We insert a software breakpoint by
  135. // patching the first byte of the instruction at 'address'
  136. // with the breakpoint instruction (int3)
  137. if (m_breakpoints.contains(address))
  138. return false;
  139. auto original_bytes = peek(reinterpret_cast<FlatPtr*>(address));
  140. if (!original_bytes.has_value())
  141. return false;
  142. VERIFY((original_bytes.value() & 0xff) != BREAKPOINT_INSTRUCTION);
  143. BreakPoint breakpoint { address, original_bytes.value(), BreakPointState::Disabled };
  144. m_breakpoints.set(address, breakpoint);
  145. enable_breakpoint(breakpoint.address);
  146. return true;
  147. }
  148. bool DebugSession::disable_breakpoint(void* address)
  149. {
  150. auto breakpoint = m_breakpoints.get(address);
  151. VERIFY(breakpoint.has_value());
  152. if (!poke(reinterpret_cast<FlatPtr*>(reinterpret_cast<char*>(breakpoint.value().address)), breakpoint.value().original_first_word))
  153. return false;
  154. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  155. bp.state = BreakPointState::Disabled;
  156. m_breakpoints.set(bp.address, bp);
  157. return true;
  158. }
  159. bool DebugSession::enable_breakpoint(void* address)
  160. {
  161. auto breakpoint = m_breakpoints.get(address);
  162. VERIFY(breakpoint.has_value());
  163. VERIFY(breakpoint.value().state == BreakPointState::Disabled);
  164. if (!poke(reinterpret_cast<FlatPtr*>(breakpoint.value().address), (breakpoint.value().original_first_word & ~(FlatPtr)0xff) | BREAKPOINT_INSTRUCTION))
  165. return false;
  166. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  167. bp.state = BreakPointState::Enabled;
  168. m_breakpoints.set(bp.address, bp);
  169. return true;
  170. }
  171. bool DebugSession::remove_breakpoint(void* address)
  172. {
  173. if (!disable_breakpoint(address))
  174. return false;
  175. m_breakpoints.remove(address);
  176. return true;
  177. }
  178. bool DebugSession::breakpoint_exists(void* address) const
  179. {
  180. return m_breakpoints.contains(address);
  181. }
  182. bool DebugSession::insert_watchpoint(void* address, u32 ebp)
  183. {
  184. auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER);
  185. if (!current_register_status.has_value())
  186. return false;
  187. // FIXME: 64 bit support
  188. u32 dr7_value = static_cast<u32>(current_register_status.value());
  189. u32 next_available_index;
  190. for (next_available_index = 0; next_available_index < 4; next_available_index++) {
  191. auto bitmask = 1 << (next_available_index * 2);
  192. if ((dr7_value & bitmask) == 0)
  193. break;
  194. }
  195. if (next_available_index > 3)
  196. return false;
  197. WatchPoint watchpoint { address, next_available_index, ebp };
  198. if (!poke_debug(next_available_index, reinterpret_cast<uintptr_t>(address)))
  199. return false;
  200. dr7_value |= (1u << (next_available_index * 2)); // Enable local breakpoint for our index
  201. auto condition_shift = 16 + (next_available_index * 4);
  202. dr7_value &= ~(0b11u << condition_shift);
  203. dr7_value |= 1u << condition_shift; // Trigger on writes
  204. auto length_shift = 18 + (next_available_index * 4);
  205. dr7_value &= ~(0b11u << length_shift);
  206. // FIXME: take variable size into account?
  207. dr7_value |= 0b11u << length_shift; // 4 bytes wide
  208. if (!poke_debug(DEBUG_CONTROL_REGISTER, dr7_value))
  209. return false;
  210. m_watchpoints.set(address, watchpoint);
  211. return true;
  212. }
  213. bool DebugSession::remove_watchpoint(void* address)
  214. {
  215. if (!disable_watchpoint(address))
  216. return false;
  217. return m_watchpoints.remove(address);
  218. }
  219. bool DebugSession::disable_watchpoint(void* address)
  220. {
  221. VERIFY(watchpoint_exists(address));
  222. auto watchpoint = m_watchpoints.get(address).value();
  223. if (!poke_debug(watchpoint.debug_register_index, 0))
  224. return false;
  225. auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER);
  226. if (!current_register_status.has_value())
  227. return false;
  228. u32 dr7_value = current_register_status.value();
  229. dr7_value &= ~(1u << watchpoint.debug_register_index * 2);
  230. if (!poke_debug(watchpoint.debug_register_index, dr7_value))
  231. return false;
  232. return true;
  233. }
  234. bool DebugSession::watchpoint_exists(void* address) const
  235. {
  236. return m_watchpoints.contains(address);
  237. }
  238. PtraceRegisters DebugSession::get_registers() const
  239. {
  240. PtraceRegisters regs;
  241. if (ptrace(PT_GETREGS, m_debuggee_pid, &regs, 0) < 0) {
  242. perror("PT_GETREGS");
  243. VERIFY_NOT_REACHED();
  244. }
  245. return regs;
  246. }
  247. void DebugSession::set_registers(PtraceRegisters const& regs)
  248. {
  249. if (ptrace(PT_SETREGS, m_debuggee_pid, reinterpret_cast<void*>(&const_cast<PtraceRegisters&>(regs)), 0) < 0) {
  250. perror("PT_SETREGS");
  251. VERIFY_NOT_REACHED();
  252. }
  253. }
  254. void DebugSession::continue_debuggee(ContinueType type)
  255. {
  256. int command = (type == ContinueType::FreeRun) ? PT_CONTINUE : PT_SYSCALL;
  257. if (ptrace(command, m_debuggee_pid, 0, 0) < 0) {
  258. perror("continue");
  259. VERIFY_NOT_REACHED();
  260. }
  261. }
  262. int DebugSession::continue_debuggee_and_wait(ContinueType type)
  263. {
  264. continue_debuggee(type);
  265. int wstatus = 0;
  266. if (waitpid(m_debuggee_pid, &wstatus, WSTOPPED | WEXITED) != m_debuggee_pid) {
  267. perror("waitpid");
  268. VERIFY_NOT_REACHED();
  269. }
  270. return wstatus;
  271. }
  272. void* DebugSession::single_step()
  273. {
  274. // Single stepping works by setting the x86 TRAP flag bit in the eflags register.
  275. // This flag causes the cpu to enter single-stepping mode, which causes
  276. // Interrupt 1 (debug interrupt) to be emitted after every instruction.
  277. // To single step the program, we set the TRAP flag and continue the debuggee.
  278. // After the debuggee has stopped, we clear the TRAP flag.
  279. auto regs = get_registers();
  280. constexpr u32 TRAP_FLAG = 0x100;
  281. #if ARCH(I386)
  282. regs.eflags |= TRAP_FLAG;
  283. #else
  284. regs.rflags |= TRAP_FLAG;
  285. #endif
  286. set_registers(regs);
  287. continue_debuggee();
  288. if (waitpid(m_debuggee_pid, 0, WSTOPPED) != m_debuggee_pid) {
  289. perror("waitpid");
  290. VERIFY_NOT_REACHED();
  291. }
  292. regs = get_registers();
  293. #if ARCH(I386)
  294. regs.eflags &= ~(TRAP_FLAG);
  295. #else
  296. regs.rflags &= ~(TRAP_FLAG);
  297. #endif
  298. set_registers(regs);
  299. return (void*)regs.ip();
  300. }
  301. void DebugSession::detach()
  302. {
  303. for (auto& breakpoint : m_breakpoints.keys()) {
  304. remove_breakpoint(breakpoint);
  305. }
  306. for (auto& watchpoint : m_watchpoints.keys())
  307. remove_watchpoint(watchpoint);
  308. continue_debuggee();
  309. }
  310. Optional<DebugSession::InsertBreakpointAtSymbolResult> DebugSession::insert_breakpoint(String const& symbol_name)
  311. {
  312. Optional<InsertBreakpointAtSymbolResult> result;
  313. for_each_loaded_library([this, symbol_name, &result](auto& lib) {
  314. // The loader contains its own definitions for LibC symbols, so we don't want to include it in the search.
  315. if (lib.name == "Loader.so")
  316. return IterationDecision::Continue;
  317. auto symbol = lib.debug_info->elf().find_demangled_function(symbol_name);
  318. if (!symbol.has_value())
  319. return IterationDecision::Continue;
  320. auto breakpoint_address = symbol.value().value() + lib.base_address;
  321. bool rc = this->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
  322. if (!rc)
  323. return IterationDecision::Break;
  324. result = InsertBreakpointAtSymbolResult { lib.name, breakpoint_address };
  325. return IterationDecision::Break;
  326. });
  327. return result;
  328. }
  329. Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::insert_breakpoint(String const& filename, size_t line_number)
  330. {
  331. auto address_and_source_position = get_address_from_source_position(filename, line_number);
  332. if (!address_and_source_position.has_value())
  333. return {};
  334. auto address = address_and_source_position.value().address;
  335. bool rc = this->insert_breakpoint(reinterpret_cast<void*>(address));
  336. if (!rc)
  337. return {};
  338. auto lib = library_at(address);
  339. VERIFY(lib);
  340. return InsertBreakpointAtSourcePositionResult { lib->name, address_and_source_position.value().file, address_and_source_position.value().line, address };
  341. }
  342. void DebugSession::update_loaded_libs()
  343. {
  344. auto file = Core::File::construct(String::formatted("/proc/{}/vm", m_debuggee_pid));
  345. bool rc = file->open(Core::OpenMode::ReadOnly);
  346. VERIFY(rc);
  347. auto file_contents = file->read_all();
  348. auto json = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors();
  349. auto const& vm_entries = json.as_array();
  350. Regex<PosixExtended> segment_name_re("(.+): ");
  351. auto get_path_to_object = [&segment_name_re](String const& vm_name) -> Optional<String> {
  352. if (vm_name == "/usr/lib/Loader.so")
  353. return vm_name;
  354. RegexResult result;
  355. auto rc = segment_name_re.search(vm_name, result);
  356. if (!rc)
  357. return {};
  358. auto lib_name = result.capture_group_matches.at(0).at(0).view.string_view().to_string();
  359. if (lib_name.starts_with("/"))
  360. return lib_name;
  361. return String::formatted("/usr/lib/{}", lib_name);
  362. };
  363. vm_entries.for_each([&](auto& entry) {
  364. // TODO: check that region is executable
  365. auto vm_name = entry.as_object().get("name").as_string();
  366. auto object_path = get_path_to_object(vm_name);
  367. if (!object_path.has_value())
  368. return IterationDecision::Continue;
  369. String lib_name = object_path.value();
  370. if (Core::File::looks_like_shared_library(lib_name))
  371. lib_name = LexicalPath::basename(object_path.value());
  372. FlatPtr base_address = entry.as_object().get("address").to_addr();
  373. if (auto it = m_loaded_libraries.find(lib_name); it != m_loaded_libraries.end()) {
  374. // We expect the VM regions to be sorted by address.
  375. VERIFY(base_address >= it->value->base_address);
  376. return IterationDecision::Continue;
  377. }
  378. auto file_or_error = MappedFile::map(object_path.value());
  379. if (file_or_error.is_error())
  380. return IterationDecision::Continue;
  381. auto image = make<ELF::Image>(file_or_error.value()->bytes());
  382. auto debug_info = make<DebugInfo>(*image, m_source_root, base_address);
  383. auto lib = make<LoadedLibrary>(lib_name, file_or_error.release_value(), move(image), move(debug_info), base_address);
  384. m_loaded_libraries.set(lib_name, move(lib));
  385. return IterationDecision::Continue;
  386. });
  387. }
  388. }