DebugSession.cpp 15 KB

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