main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/OwnPtr.h>
  10. #include <AK/Platform.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Try.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/System.h>
  15. #include <LibDebug/DebugInfo.h>
  16. #include <LibDebug/DebugSession.h>
  17. #include <LibLine/Editor.h>
  18. #include <LibMain/Main.h>
  19. #include <LibX86/Disassembler.h>
  20. #include <LibX86/Instruction.h>
  21. #include <signal.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <sys/arch/regs.h>
  25. #include <unistd.h>
  26. RefPtr<Line::Editor> editor;
  27. OwnPtr<Debug::DebugSession> g_debug_session;
  28. static void handle_sigint(int)
  29. {
  30. outln("Debugger: SIGINT");
  31. // The destructor of DebugSession takes care of detaching
  32. g_debug_session = nullptr;
  33. }
  34. static void handle_print_registers(PtraceRegisters const& regs)
  35. {
  36. #if ARCH(X86_64)
  37. outln("rax={:p} rbx={:p} rcx={:p} rdx={:p}", regs.rax, regs.rbx, regs.rcx, regs.rdx);
  38. outln("rsp={:p} rbp={:p} rsi={:p} rdi={:p}", regs.rsp, regs.rbp, regs.rsi, regs.rdi);
  39. outln("r8 ={:p} r9 ={:p} r10={:p} r11={:p}", regs.r8, regs.r9, regs.r10, regs.r11);
  40. outln("r12={:p} r13={:p} r14={:p} r15={:p}", regs.r12, regs.r13, regs.r14, regs.r15);
  41. outln("rip={:p} rflags={:p}", regs.rip, regs.rflags);
  42. #elif ARCH(AARCH64)
  43. (void)regs;
  44. TODO_AARCH64();
  45. #elif ARCH(RISCV64)
  46. (void)regs;
  47. TODO_RISCV64();
  48. #else
  49. # error Unknown architecture
  50. #endif
  51. }
  52. static bool handle_disassemble_command(ByteString const& command, FlatPtr first_instruction)
  53. {
  54. auto parts = command.split(' ');
  55. size_t number_of_instructions_to_disassemble = 5;
  56. if (parts.size() == 2) {
  57. auto number = parts[1].to_number<unsigned>();
  58. if (!number.has_value())
  59. return false;
  60. number_of_instructions_to_disassemble = number.value();
  61. }
  62. // FIXME: Instead of using a fixed "dump_size",
  63. // we can feed instructions to the disassembler one by one
  64. constexpr size_t dump_size = 0x100;
  65. ByteBuffer code;
  66. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  67. auto value = g_debug_session->peek(first_instruction + i * sizeof(u32));
  68. if (!value.has_value())
  69. break;
  70. if (code.try_append(&value, sizeof(u32)).is_error())
  71. break;
  72. }
  73. X86::SimpleInstructionStream stream(code.data(), code.size());
  74. X86::Disassembler disassembler(stream);
  75. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  76. auto offset = stream.offset();
  77. auto insn = disassembler.next();
  78. if (!insn.has_value())
  79. break;
  80. outln(" {:p} <+{}>:\t{}", offset + first_instruction, offset, insn.value().to_byte_string(offset));
  81. }
  82. return true;
  83. }
  84. static bool handle_backtrace_command(PtraceRegisters const& regs)
  85. {
  86. (void)regs;
  87. TODO();
  88. return true;
  89. }
  90. static bool insert_breakpoint_at_address(FlatPtr address)
  91. {
  92. return g_debug_session->insert_breakpoint(address);
  93. }
  94. static bool insert_breakpoint_at_source_position(ByteString const& file, size_t line)
  95. {
  96. auto result = g_debug_session->insert_breakpoint(file, line);
  97. if (!result.has_value()) {
  98. warnln("Could not insert breakpoint at {}:{}", file, line);
  99. return false;
  100. }
  101. outln("Breakpoint inserted [{}:{} ({}:{:p})]", result.value().filename, result.value().line_number, result.value().library_name, result.value().address);
  102. return true;
  103. }
  104. static bool insert_breakpoint_at_symbol(ByteString const& symbol)
  105. {
  106. auto result = g_debug_session->insert_breakpoint(symbol);
  107. if (!result.has_value()) {
  108. warnln("Could not insert breakpoint at symbol: {}", symbol);
  109. return false;
  110. }
  111. outln("Breakpoint inserted [{}:{:p}]", result.value().library_name, result.value().address);
  112. return true;
  113. }
  114. static bool handle_breakpoint_command(ByteString const& command)
  115. {
  116. auto parts = command.split(' ');
  117. if (parts.size() != 2)
  118. return false;
  119. auto argument = parts[1];
  120. if (argument.is_empty())
  121. return false;
  122. if (argument.contains(":"sv)) {
  123. auto source_arguments = argument.split(':');
  124. if (source_arguments.size() != 2)
  125. return false;
  126. auto line = source_arguments[1].to_number<unsigned>();
  127. if (!line.has_value())
  128. return false;
  129. auto file = source_arguments[0];
  130. return insert_breakpoint_at_source_position(file, line.value());
  131. }
  132. if ((argument.starts_with("0x"sv))) {
  133. return insert_breakpoint_at_address(strtoul(argument.characters() + 2, nullptr, 16));
  134. }
  135. return insert_breakpoint_at_symbol(argument);
  136. }
  137. static bool handle_examine_command(ByteString const& command)
  138. {
  139. auto parts = command.split(' ');
  140. if (parts.size() != 2)
  141. return false;
  142. auto argument = parts[1];
  143. if (argument.is_empty())
  144. return false;
  145. if (!(argument.starts_with("0x"sv))) {
  146. return false;
  147. }
  148. FlatPtr address = strtoul(argument.characters() + 2, nullptr, 16);
  149. auto res = g_debug_session->peek(address);
  150. if (!res.has_value()) {
  151. outln("Could not examine memory at address {:p}", address);
  152. return true;
  153. }
  154. outln("{:#x}", res.value());
  155. return true;
  156. }
  157. static void print_help()
  158. {
  159. out("Options:\n"
  160. "cont - Continue execution\n"
  161. "si - step to the next instruction\n"
  162. "sl - step to the next source line\n"
  163. "line - show the position of the current instruction in the source code\n"
  164. "regs - Print registers\n"
  165. "dis [number of instructions] - Print disassembly\n"
  166. "bp <address/symbol/file:line> - Insert a breakpoint\n"
  167. "bt - show backtrace for current thread\n"
  168. "x <address> - examine dword in memory\n");
  169. }
  170. static NonnullOwnPtr<Debug::DebugSession> create_debug_session(StringView command, pid_t pid_to_debug)
  171. {
  172. if (!command.is_null()) {
  173. auto result = Debug::DebugSession::exec_and_attach(command);
  174. if (!result) {
  175. warnln("Failed to start debugging session for: \"{}\"", command);
  176. exit(1);
  177. }
  178. return result.release_nonnull();
  179. }
  180. if (pid_to_debug == -1) {
  181. warnln("Either a command or a pid must be specified");
  182. exit(1);
  183. }
  184. auto result = Debug::DebugSession::attach(pid_to_debug);
  185. if (!result) {
  186. warnln("Failed to attach to pid: {}", pid_to_debug);
  187. exit(1);
  188. }
  189. return result.release_nonnull();
  190. }
  191. ErrorOr<int> serenity_main(Main::Arguments arguments)
  192. {
  193. editor = Line::Editor::construct();
  194. TRY(Core::System::pledge("stdio proc ptrace exec rpath tty sigaction cpath unix"));
  195. StringView command;
  196. pid_t pid_to_debug = -1;
  197. Core::ArgsParser args_parser;
  198. args_parser.add_positional_argument(command,
  199. "The program to be debugged, along with its arguments",
  200. "program", Core::ArgsParser::Required::No);
  201. args_parser.add_option(pid_to_debug, "Attach debugger to running process", "pid", 'p', "PID");
  202. args_parser.parse(arguments);
  203. g_debug_session = create_debug_session(command, pid_to_debug);
  204. struct sigaction sa {
  205. };
  206. sa.sa_handler = handle_sigint;
  207. TRY(Core::System::sigaction(SIGINT, &sa, nullptr));
  208. Debug::DebugInfo::SourcePosition previous_source_position;
  209. bool in_step_line = false;
  210. g_debug_session->run(Debug::DebugSession::DesiredInitialDebugeeState::Stopped, [&](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  211. if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
  212. outln("Program exited.");
  213. return Debug::DebugSession::DebugDecision::Detach;
  214. }
  215. VERIFY(optional_regs.has_value());
  216. PtraceRegisters const& regs = optional_regs.value();
  217. #if ARCH(X86_64)
  218. FlatPtr const ip = regs.rip;
  219. #elif ARCH(AARCH64)
  220. FlatPtr const ip = 0; // FIXME
  221. TODO_AARCH64();
  222. #elif ARCH(RISCV64)
  223. FlatPtr const ip = 0; // FIXME
  224. TODO_RISCV64();
  225. #else
  226. # error Unknown architecture
  227. #endif
  228. auto symbol_at_ip = g_debug_session->symbolicate(ip);
  229. auto source_position = g_debug_session->get_source_position(ip);
  230. if (in_step_line) {
  231. bool no_source_info = !source_position.has_value();
  232. if (no_source_info || source_position.value() != previous_source_position) {
  233. if (no_source_info)
  234. outln("No source information for current instruction! stopping.");
  235. in_step_line = false;
  236. } else {
  237. return Debug::DebugSession::DebugDecision::SingleStep;
  238. }
  239. }
  240. if (symbol_at_ip.has_value())
  241. outln("Program is stopped at: {:p} ({}:{})", ip, symbol_at_ip.value().library_name, symbol_at_ip.value().symbol);
  242. else
  243. outln("Program is stopped at: {:p}", ip);
  244. if (source_position.has_value()) {
  245. previous_source_position = source_position.value();
  246. outln("Source location: {}:{}", source_position.value().file_path, source_position.value().line_number);
  247. } else {
  248. outln("(No source location information for the current instruction)");
  249. }
  250. for (;;) {
  251. auto command_result = editor->get_line("(sdb) ");
  252. if (command_result.is_error())
  253. return Debug::DebugSession::DebugDecision::Detach;
  254. auto& command = command_result.value();
  255. bool success = false;
  256. Optional<Debug::DebugSession::DebugDecision> decision;
  257. if (command.is_empty() && !editor->history().is_empty()) {
  258. command = editor->history().last().entry;
  259. }
  260. if (command == "cont") {
  261. decision = Debug::DebugSession::DebugDecision::Continue;
  262. success = true;
  263. } else if (command == "si") {
  264. decision = Debug::DebugSession::DebugDecision::SingleStep;
  265. success = true;
  266. } else if (command == "sl") {
  267. if (source_position.has_value()) {
  268. decision = Debug::DebugSession::DebugDecision::SingleStep;
  269. in_step_line = true;
  270. success = true;
  271. } else {
  272. outln("No source location information for the current instruction");
  273. }
  274. } else if (command == "regs") {
  275. handle_print_registers(regs);
  276. success = true;
  277. } else if (command.starts_with("dis"sv)) {
  278. success = handle_disassemble_command(command, ip);
  279. } else if (command.starts_with("bp"sv)) {
  280. success = handle_breakpoint_command(command);
  281. } else if (command.starts_with("x"sv)) {
  282. success = handle_examine_command(command);
  283. } else if (command.starts_with("bt"sv)) {
  284. success = handle_backtrace_command(regs);
  285. }
  286. if (success && !command.is_empty()) {
  287. // Don't add repeated commands to history
  288. if (editor->history().is_empty() || editor->history().last().entry != command)
  289. editor->add_to_history(command);
  290. }
  291. if (!success) {
  292. print_help();
  293. }
  294. if (decision.has_value())
  295. return decision.value();
  296. }
  297. });
  298. return 0;
  299. }