DebugSession.cpp 16 KB

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