main.cpp 9.7 KB

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