DebugSession.cpp 14 KB

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