main.cpp 11 KB

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