main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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/StringBuilder.h>
  11. #include <LibC/sys/arch/i386/regs.h>
  12. #include <LibCore/ArgsParser.h>
  13. #include <LibCore/File.h>
  14. #include <LibDebug/DebugInfo.h>
  15. #include <LibDebug/DebugSession.h>
  16. #include <LibLine/Editor.h>
  17. #include <LibX86/Disassembler.h>
  18. #include <LibX86/Instruction.h>
  19. #include <signal.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. RefPtr<Line::Editor> editor;
  25. OwnPtr<Debug::DebugSession> g_debug_session;
  26. static void handle_sigint(int)
  27. {
  28. outln("Debugger: SIGINT");
  29. // The destructor of DebugSession takes care of detaching
  30. g_debug_session = nullptr;
  31. }
  32. static void handle_print_registers(const PtraceRegisters& regs)
  33. {
  34. outln("eax={:08x} ebx={:08x} ecx={:08x} edx={:08x}", regs.eax, regs.ebx, regs.ecx, regs.edx);
  35. outln("esp={:08x} ebp={:08x} esi={:08x} edi={:08x}", regs.esp, regs.ebp, regs.esi, regs.edi);
  36. outln("eip={:08x} eflags={:08x}", regs.eip, regs.eflags);
  37. }
  38. static bool handle_disassemble_command(const String& command, void* first_instruction)
  39. {
  40. auto parts = command.split(' ');
  41. size_t number_of_instructions_to_disassemble = 5;
  42. if (parts.size() == 2) {
  43. auto number = parts[1].to_uint();
  44. if (!number.has_value())
  45. return false;
  46. number_of_instructions_to_disassemble = number.value();
  47. }
  48. // FIXME: Instead of using a fixed "dump_size",
  49. // we can feed instructions to the disassembler one by one
  50. constexpr size_t dump_size = 0x100;
  51. ByteBuffer code;
  52. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  53. auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
  54. if (!value.has_value())
  55. break;
  56. code.append(&value, sizeof(u32));
  57. }
  58. X86::SimpleInstructionStream stream(code.data(), code.size());
  59. X86::Disassembler disassembler(stream);
  60. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  61. auto offset = stream.offset();
  62. auto insn = disassembler.next();
  63. if (!insn.has_value())
  64. break;
  65. outln(" {:p} <+{}>:\t{}", offset + reinterpret_cast<size_t>(first_instruction), offset, insn.value().to_string(offset));
  66. }
  67. return true;
  68. }
  69. static bool handle_backtrace_command(const PtraceRegisters& regs)
  70. {
  71. auto ebp_val = regs.ebp;
  72. auto eip_val = regs.eip;
  73. outln("Backtrace:");
  74. while (g_debug_session->peek((u32*)eip_val).has_value() && g_debug_session->peek((u32*)ebp_val).has_value()) {
  75. auto eip_symbol = g_debug_session->symbolicate(eip_val);
  76. auto source_position = g_debug_session->get_source_position(eip_val);
  77. String symbol_location = (eip_symbol.has_value() && eip_symbol->symbol != "") ? eip_symbol->symbol : "???";
  78. if (source_position.has_value()) {
  79. outln("{:p} in {} ({}:{})", eip_val, symbol_location, source_position->file_path, source_position->line_number);
  80. } else {
  81. outln("{:p} in {}", eip_val, symbol_location);
  82. }
  83. auto next_eip = g_debug_session->peek((u32*)(ebp_val + 4));
  84. auto next_ebp = g_debug_session->peek((u32*)ebp_val);
  85. eip_val = (u32)next_eip.value();
  86. ebp_val = (u32)next_ebp.value();
  87. }
  88. return true;
  89. }
  90. static bool insert_breakpoint_at_address(FlatPtr address)
  91. {
  92. return g_debug_session->insert_breakpoint((void*)address);
  93. }
  94. static bool insert_breakpoint_at_source_position(const String& 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(const String& 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(const String& 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(":")) {
  123. auto source_arguments = argument.split(':');
  124. if (source_arguments.size() != 2)
  125. return false;
  126. auto line = source_arguments[1].to_uint();
  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"))) {
  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(const String& 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"))) {
  146. return false;
  147. }
  148. u32 address = strtoul(argument.characters() + 2, nullptr, 16);
  149. auto res = g_debug_session->peek((u32*)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. int main(int argc, char** argv)
  171. {
  172. editor = Line::Editor::construct();
  173. if (pledge("stdio proc ptrace exec rpath tty sigaction cpath unix", nullptr) < 0) {
  174. perror("pledge");
  175. return 1;
  176. }
  177. const char* command = nullptr;
  178. Core::ArgsParser args_parser;
  179. args_parser.add_positional_argument(command,
  180. "The program to be debugged, along with its arguments",
  181. "program", Core::ArgsParser::Required::Yes);
  182. args_parser.parse(argc, argv);
  183. auto result = Debug::DebugSession::exec_and_attach(command);
  184. if (!result) {
  185. warnln("Failed to start debugging session for: \"{}\"", command);
  186. exit(1);
  187. }
  188. g_debug_session = result.release_nonnull();
  189. struct sigaction sa {
  190. };
  191. sa.sa_handler = handle_sigint;
  192. sigaction(SIGINT, &sa, nullptr);
  193. Debug::DebugInfo::SourcePosition previous_source_position;
  194. bool in_step_line = false;
  195. g_debug_session->run(Debug::DebugSession::DesiredInitialDebugeeState::Stopped, [&](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  196. if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
  197. outln("Program exited.");
  198. return Debug::DebugSession::DebugDecision::Detach;
  199. }
  200. VERIFY(optional_regs.has_value());
  201. const PtraceRegisters& regs = optional_regs.value();
  202. auto symbol_at_ip = g_debug_session->symbolicate(regs.eip);
  203. auto source_position = g_debug_session->get_source_position(regs.eip);
  204. if (in_step_line) {
  205. bool no_source_info = !source_position.has_value();
  206. if (no_source_info || source_position.value() != previous_source_position) {
  207. if (no_source_info)
  208. outln("No source information for current instruction! stoppoing.");
  209. in_step_line = false;
  210. } else {
  211. return Debug::DebugSession::DebugDecision::SingleStep;
  212. }
  213. }
  214. if (symbol_at_ip.has_value())
  215. outln("Program is stopped at: {:p} ({}:{})", regs.eip, symbol_at_ip.value().library_name, symbol_at_ip.value().symbol);
  216. else
  217. outln("Program is stopped at: {:p}", regs.eip);
  218. if (source_position.has_value()) {
  219. previous_source_position = source_position.value();
  220. outln("Source location: {}:{}", source_position.value().file_path, source_position.value().line_number);
  221. } else {
  222. outln("(No source location information for the current instruction)");
  223. }
  224. for (;;) {
  225. auto command_result = editor->get_line("(sdb) ");
  226. if (command_result.is_error())
  227. return Debug::DebugSession::DebugDecision::Detach;
  228. auto& command = command_result.value();
  229. bool success = false;
  230. Optional<Debug::DebugSession::DebugDecision> decision;
  231. if (command.is_empty() && !editor->history().is_empty()) {
  232. command = editor->history().last().entry;
  233. }
  234. if (command == "cont") {
  235. decision = Debug::DebugSession::DebugDecision::Continue;
  236. success = true;
  237. } else if (command == "si") {
  238. decision = Debug::DebugSession::DebugDecision::SingleStep;
  239. success = true;
  240. } else if (command == "sl") {
  241. if (source_position.has_value()) {
  242. decision = Debug::DebugSession::DebugDecision::SingleStep;
  243. in_step_line = true;
  244. success = true;
  245. } else {
  246. outln("No source location information for the current instruction");
  247. }
  248. } else if (command == "regs") {
  249. handle_print_registers(regs);
  250. success = true;
  251. } else if (command.starts_with("dis")) {
  252. success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));
  253. } else if (command.starts_with("bp")) {
  254. success = handle_breakpoint_command(command);
  255. } else if (command.starts_with("x")) {
  256. success = handle_examine_command(command);
  257. } else if (command.starts_with("bt")) {
  258. success = handle_backtrace_command(regs);
  259. }
  260. if (success && !command.is_empty()) {
  261. // Don't add repeated commands to history
  262. if (editor->history().is_empty() || editor->history().last().entry != command)
  263. editor->add_to_history(command);
  264. }
  265. if (!success) {
  266. print_help();
  267. }
  268. if (decision.has_value())
  269. return decision.value();
  270. }
  271. });
  272. }