DebugSession.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "DebugSession.h"
  27. #include <AK/JsonObject.h>
  28. #include <AK/JsonValue.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/Optional.h>
  31. #include <LibCore/File.h>
  32. #include <LibRegex/Regex.h>
  33. #include <stdlib.h>
  34. #include <sys/mman.h>
  35. namespace Debug {
  36. DebugSession::DebugSession(pid_t pid, String source_root)
  37. : m_debuggee_pid(pid)
  38. , m_source_root(source_root)
  39. {
  40. }
  41. DebugSession::~DebugSession()
  42. {
  43. if (m_is_debuggee_dead)
  44. return;
  45. for (const auto& bp : m_breakpoints) {
  46. disable_breakpoint(bp.key);
  47. }
  48. m_breakpoints.clear();
  49. for (const auto& wp : m_watchpoints) {
  50. disable_watchpoint(wp.key);
  51. }
  52. m_watchpoints.clear();
  53. if (ptrace(PT_DETACH, m_debuggee_pid, 0, 0) < 0) {
  54. perror("PT_DETACH");
  55. }
  56. }
  57. OwnPtr<DebugSession> DebugSession::exec_and_attach(const String& command, String source_root)
  58. {
  59. auto pid = fork();
  60. if (pid < 0) {
  61. perror("fork");
  62. exit(1);
  63. }
  64. if (!pid) {
  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. const char** args = (const char**)calloc(parts.size() + 1, sizeof(const char*));
  72. for (size_t i = 0; i < parts.size(); i++) {
  73. args[i] = parts[i].characters();
  74. }
  75. const char** envp = (const char**)calloc(2, sizeof(const char*));
  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' sycsall.
  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));
  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. bool DebugSession::poke(u32* address, u32 data)
  112. {
  113. if (ptrace(PT_POKE, m_debuggee_pid, (void*)address, data) < 0) {
  114. perror("PT_POKE");
  115. return false;
  116. }
  117. return true;
  118. }
  119. Optional<u32> DebugSession::peek(u32* address) const
  120. {
  121. Optional<u32> result;
  122. int rc = ptrace(PT_PEEK, m_debuggee_pid, (void*)address, 0);
  123. if (errno == 0)
  124. result = static_cast<u32>(rc);
  125. return result;
  126. }
  127. bool DebugSession::poke_debug(u32 register_index, u32 data)
  128. {
  129. if (ptrace(PT_POKEDEBUG, m_debuggee_pid, reinterpret_cast<u32*>(register_index), data) < 0) {
  130. perror("PT_POKEDEBUG");
  131. return false;
  132. }
  133. return true;
  134. }
  135. Optional<u32> DebugSession::peek_debug(u32 register_index) const
  136. {
  137. Optional<u32> result;
  138. int rc = ptrace(PT_PEEKDEBUG, m_debuggee_pid, reinterpret_cast<u32*>(register_index), 0);
  139. if (errno == 0)
  140. result = static_cast<u32>(rc);
  141. return result;
  142. }
  143. bool DebugSession::insert_breakpoint(void* address)
  144. {
  145. // We insert a software breakpoint by
  146. // patching the first byte of the instruction at 'address'
  147. // with the breakpoint instruction (int3)
  148. if (m_breakpoints.contains(address))
  149. return false;
  150. auto original_bytes = peek(reinterpret_cast<u32*>(address));
  151. if (!original_bytes.has_value())
  152. return false;
  153. VERIFY((original_bytes.value() & 0xff) != BREAKPOINT_INSTRUCTION);
  154. BreakPoint breakpoint { address, original_bytes.value(), BreakPointState::Disabled };
  155. m_breakpoints.set(address, breakpoint);
  156. enable_breakpoint(breakpoint.address);
  157. return true;
  158. }
  159. bool DebugSession::disable_breakpoint(void* address)
  160. {
  161. auto breakpoint = m_breakpoints.get(address);
  162. VERIFY(breakpoint.has_value());
  163. if (!poke(reinterpret_cast<u32*>(reinterpret_cast<char*>(breakpoint.value().address)), breakpoint.value().original_first_word))
  164. return false;
  165. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  166. bp.state = BreakPointState::Disabled;
  167. m_breakpoints.set(bp.address, bp);
  168. return true;
  169. }
  170. bool DebugSession::enable_breakpoint(void* address)
  171. {
  172. auto breakpoint = m_breakpoints.get(address);
  173. VERIFY(breakpoint.has_value());
  174. VERIFY(breakpoint.value().state == BreakPointState::Disabled);
  175. if (!poke(reinterpret_cast<u32*>(breakpoint.value().address), (breakpoint.value().original_first_word & ~(uint32_t)0xff) | BREAKPOINT_INSTRUCTION))
  176. return false;
  177. auto bp = m_breakpoints.get(breakpoint.value().address).value();
  178. bp.state = BreakPointState::Enabled;
  179. m_breakpoints.set(bp.address, bp);
  180. return true;
  181. }
  182. bool DebugSession::remove_breakpoint(void* address)
  183. {
  184. if (!disable_breakpoint(address))
  185. return false;
  186. m_breakpoints.remove(address);
  187. return true;
  188. }
  189. bool DebugSession::breakpoint_exists(void* address) const
  190. {
  191. return m_breakpoints.contains(address);
  192. }
  193. bool DebugSession::insert_watchpoint(void* address, u32 ebp)
  194. {
  195. auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER);
  196. if (!current_register_status.has_value())
  197. return false;
  198. u32 dr7_value = current_register_status.value();
  199. u32 next_available_index;
  200. for (next_available_index = 0; next_available_index < 4; next_available_index++) {
  201. auto bitmask = 1 << (next_available_index * 2);
  202. if ((dr7_value & bitmask) == 0)
  203. break;
  204. }
  205. if (next_available_index > 3)
  206. return false;
  207. WatchPoint watchpoint { address, next_available_index, ebp };
  208. if (!poke_debug(next_available_index, reinterpret_cast<uintptr_t>(address)))
  209. return false;
  210. dr7_value |= (1u << (next_available_index * 2)); // Enable local breakpoint for our index
  211. auto condition_shift = 16 + (next_available_index * 4);
  212. dr7_value &= ~(0b11u << condition_shift);
  213. dr7_value |= 1u << condition_shift; // Trigger on writes
  214. auto length_shift = 18 + (next_available_index * 4);
  215. dr7_value &= ~(0b11u << length_shift);
  216. // FIXME: take variable size into account?
  217. dr7_value |= 0b11u << length_shift; // 4 bytes wide
  218. if (!poke_debug(DEBUG_CONTROL_REGISTER, dr7_value))
  219. return false;
  220. m_watchpoints.set(address, watchpoint);
  221. return true;
  222. }
  223. bool DebugSession::remove_watchpoint(void* address)
  224. {
  225. if (!disable_watchpoint(address))
  226. return false;
  227. return m_watchpoints.remove(address);
  228. }
  229. bool DebugSession::disable_watchpoint(void* address)
  230. {
  231. VERIFY(watchpoint_exists(address));
  232. auto watchpoint = m_watchpoints.get(address).value();
  233. if (!poke_debug(watchpoint.debug_register_index, 0))
  234. return false;
  235. auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER);
  236. if (!current_register_status.has_value())
  237. return false;
  238. u32 dr7_value = current_register_status.value();
  239. dr7_value &= ~(1u << watchpoint.debug_register_index * 2);
  240. if (!poke_debug(watchpoint.debug_register_index, dr7_value))
  241. return false;
  242. return true;
  243. }
  244. bool DebugSession::watchpoint_exists(void* address) const
  245. {
  246. return m_watchpoints.contains(address);
  247. }
  248. PtraceRegisters DebugSession::get_registers() const
  249. {
  250. PtraceRegisters regs;
  251. if (ptrace(PT_GETREGS, m_debuggee_pid, &regs, 0) < 0) {
  252. perror("PT_GETREGS");
  253. VERIFY_NOT_REACHED();
  254. }
  255. return regs;
  256. }
  257. void DebugSession::set_registers(const PtraceRegisters& regs)
  258. {
  259. if (ptrace(PT_SETREGS, m_debuggee_pid, reinterpret_cast<void*>(&const_cast<PtraceRegisters&>(regs)), 0) < 0) {
  260. perror("PT_SETREGS");
  261. VERIFY_NOT_REACHED();
  262. }
  263. }
  264. void DebugSession::continue_debuggee(ContinueType type)
  265. {
  266. int command = (type == ContinueType::FreeRun) ? PT_CONTINUE : PT_SYSCALL;
  267. if (ptrace(command, m_debuggee_pid, 0, 0) < 0) {
  268. perror("continue");
  269. VERIFY_NOT_REACHED();
  270. }
  271. }
  272. int DebugSession::continue_debuggee_and_wait(ContinueType type)
  273. {
  274. continue_debuggee(type);
  275. int wstatus = 0;
  276. if (waitpid(m_debuggee_pid, &wstatus, WSTOPPED | WEXITED) != m_debuggee_pid) {
  277. perror("waitpid");
  278. VERIFY_NOT_REACHED();
  279. }
  280. return wstatus;
  281. }
  282. void* DebugSession::single_step()
  283. {
  284. // Single stepping works by setting the x86 TRAP flag bit in the eflags register.
  285. // This flag causes the cpu to enter single-stepping mode, which causes
  286. // Interrupt 1 (debug interrupt) to be emitted after every instruction.
  287. // To single step the program, we set the TRAP flag and continue the debuggee.
  288. // After the debuggee has stopped, we clear the TRAP flag.
  289. auto regs = get_registers();
  290. constexpr u32 TRAP_FLAG = 0x100;
  291. regs.eflags |= TRAP_FLAG;
  292. set_registers(regs);
  293. continue_debuggee();
  294. if (waitpid(m_debuggee_pid, 0, WSTOPPED) != m_debuggee_pid) {
  295. perror("waitpid");
  296. VERIFY_NOT_REACHED();
  297. }
  298. regs = get_registers();
  299. regs.eflags &= ~(TRAP_FLAG);
  300. set_registers(regs);
  301. return (void*)regs.eip;
  302. }
  303. void DebugSession::detach()
  304. {
  305. for (auto& breakpoint : m_breakpoints.keys()) {
  306. remove_breakpoint(breakpoint);
  307. }
  308. for (auto& watchpoint : m_watchpoints.keys())
  309. remove_watchpoint(watchpoint);
  310. continue_debuggee();
  311. }
  312. Optional<DebugSession::InsertBreakpointAtSymbolResult> DebugSession::insert_breakpoint(const String& symbol_name)
  313. {
  314. Optional<InsertBreakpointAtSymbolResult> result;
  315. for_each_loaded_library([this, symbol_name, &result](auto& lib) {
  316. // The loader contains its own definitions for LibC symbols, so we don't want to include it in the search.
  317. if (lib.name == "Loader.so")
  318. return IterationDecision::Continue;
  319. auto symbol = lib.debug_info->elf().find_demangled_function(symbol_name);
  320. if (!symbol.has_value())
  321. return IterationDecision::Continue;
  322. auto breakpoint_address = symbol.value().value() + lib.base_address;
  323. bool rc = this->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
  324. if (!rc)
  325. return IterationDecision::Break;
  326. result = InsertBreakpointAtSymbolResult { lib.name, breakpoint_address };
  327. return IterationDecision::Break;
  328. });
  329. return result;
  330. }
  331. Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::insert_breakpoint(const String& file_name, size_t line_number)
  332. {
  333. auto address_and_source_position = get_address_from_source_position(file_name, line_number);
  334. if (!address_and_source_position.has_value())
  335. return {};
  336. auto address = address_and_source_position.value().address;
  337. bool rc = this->insert_breakpoint(reinterpret_cast<void*>(address));
  338. if (!rc)
  339. return {};
  340. auto lib = library_at(address);
  341. VERIFY(lib);
  342. return InsertBreakpointAtSourcePositionResult { lib->name, address_and_source_position.value().file, address_and_source_position.value().line, address };
  343. }
  344. void DebugSession::update_loaded_libs()
  345. {
  346. auto file = Core::File::construct(String::formatted("/proc/{}/vm", m_debuggee_pid));
  347. bool rc = file->open(Core::IODevice::ReadOnly);
  348. VERIFY(rc);
  349. auto file_contents = file->read_all();
  350. auto json = JsonValue::from_string(file_contents);
  351. VERIFY(json.has_value());
  352. auto vm_entries = json.value().as_array();
  353. Regex<PosixExtended> re("(.+): \\.text");
  354. auto get_path_to_object = [&re](const String& vm_name) -> Optional<String> {
  355. if (vm_name == "/usr/lib/Loader.so")
  356. return vm_name;
  357. RegexResult result;
  358. auto rc = re.search(vm_name, result);
  359. if (!rc)
  360. return {};
  361. auto lib_name = result.capture_group_matches.at(0).at(0).view.u8view().to_string();
  362. if (lib_name.starts_with("/"))
  363. return lib_name;
  364. return String::formatted("/usr/lib/{}", lib_name);
  365. };
  366. vm_entries.for_each([&](auto& entry) {
  367. // TODO: check that region is executable
  368. auto vm_name = entry.as_object().get("name").as_string();
  369. auto object_path = get_path_to_object(vm_name);
  370. if (!object_path.has_value())
  371. return IterationDecision::Continue;
  372. String lib_name = object_path.value();
  373. if (lib_name.ends_with(".so"))
  374. lib_name = LexicalPath(object_path.value()).basename();
  375. // FIXME: DebugInfo currently cannot parse the debug information of libgcc_s.so
  376. if (lib_name == "libgcc_s.so")
  377. return IterationDecision::Continue;
  378. if (m_loaded_libraries.contains(lib_name))
  379. return IterationDecision::Continue;
  380. auto file_or_error = MappedFile ::map(object_path.value());
  381. if (file_or_error.is_error())
  382. return IterationDecision::Continue;
  383. FlatPtr base_address = entry.as_object().get("address").as_u32();
  384. auto debug_info = make<DebugInfo>(make<ELF::Image>(file_or_error.value()->bytes()), m_source_root, base_address);
  385. auto lib = make<LoadedLibrary>(lib_name, file_or_error.release_value(), move(debug_info), base_address);
  386. m_loaded_libraries.set(lib_name, move(lib));
  387. return IterationDecision::Continue;
  388. });
  389. }
  390. const DebugSession::LoadedLibrary* DebugSession::library_at(FlatPtr address) const
  391. {
  392. const LoadedLibrary* result = nullptr;
  393. for_each_loaded_library([&result, address](const auto& lib) {
  394. if (address >= lib.base_address && address < lib.base_address + lib.debug_info->elf().size()) {
  395. result = &lib;
  396. return IterationDecision::Break;
  397. }
  398. return IterationDecision::Continue;
  399. });
  400. return result;
  401. }
  402. Optional<DebugSession::SymbolicationResult> DebugSession::symbolicate(FlatPtr address) const
  403. {
  404. auto* lib = library_at(address);
  405. if (!lib)
  406. return {};
  407. //FIXME: ELF::Image symlicate() API should return String::empty() if symbol is not found (It currently returns ??)
  408. auto symbol = lib->debug_info->elf().symbolicate(address - lib->base_address);
  409. return { { lib->name, symbol } };
  410. }
  411. Optional<DebugInfo::SourcePositionAndAddress> DebugSession::get_address_from_source_position(const String& file, size_t line) const
  412. {
  413. Optional<DebugInfo::SourcePositionAndAddress> result;
  414. for_each_loaded_library([this, file, line, &result](auto& lib) {
  415. // The loader contains its own definitions for LibC symbols, so we don't want to include it in the search.
  416. if (lib.name == "Loader.so")
  417. return IterationDecision::Continue;
  418. auto source_position_and_address = lib.debug_info->get_address_from_source_position(file, line);
  419. if (!source_position_and_address.has_value())
  420. return IterationDecision::Continue;
  421. result = source_position_and_address;
  422. result.value().address += lib.base_address;
  423. return IterationDecision::Break;
  424. });
  425. return result;
  426. }
  427. Optional<DebugInfo::SourcePosition> DebugSession::get_source_position(FlatPtr address) const
  428. {
  429. auto* lib = library_at(address);
  430. if (!lib)
  431. return {};
  432. return lib->debug_info->get_source_position(address - lib->base_address);
  433. }
  434. }