DebugSession.cpp 15 KB

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