main.cpp 11 KB

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