DebugSession.cpp 15 KB

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