main.cpp 11 KB

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