DebugSession.cpp 16 KB

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