DebugSession.cpp 14 KB

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