DebugSession.cpp 16 KB

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