main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/Demangle.h>
  29. #include <AK/LogStream.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/kmalloc.h>
  32. #include <LibC/sys/arch/i386/regs.h>
  33. #include <LibCore/ArgsParser.h>
  34. #include <LibCore/File.h>
  35. #include <LibDebug/DebugInfo.h>
  36. #include <LibDebug/DebugSession.h>
  37. #include <LibLine/Editor.h>
  38. #include <LibX86/Disassembler.h>
  39. #include <LibX86/Instruction.h>
  40. #include <signal.h>
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <unistd.h>
  45. static Line::Editor editor {};
  46. OwnPtr<DebugSession> g_debug_session;
  47. static void handle_sigint(int)
  48. {
  49. printf("Debugger: SIGINT\n");
  50. // The destructor of DebugSession takes care of detaching
  51. g_debug_session = nullptr;
  52. }
  53. void handle_print_registers(const PtraceRegisters& regs)
  54. {
  55. printf("eax: 0x%x\n", regs.eax);
  56. printf("ecx: 0x%x\n", regs.ecx);
  57. printf("edx: 0x%x\n", regs.edx);
  58. printf("ebx: 0x%x\n", regs.ebx);
  59. printf("esp: 0x%x\n", regs.esp);
  60. printf("ebp: 0x%x\n", regs.ebp);
  61. printf("esi: 0x%x\n", regs.esi);
  62. printf("edi: 0x%x\n", regs.edi);
  63. printf("eip: 0x%x\n", regs.eip);
  64. printf("eflags: 0x%x\n", regs.eflags);
  65. }
  66. bool handle_disassemble_command(const String& command, void* first_instruction)
  67. {
  68. (void)demangle("foo");
  69. auto parts = command.split(' ');
  70. size_t number_of_instructions_to_disassemble = 5;
  71. if (parts.size() == 2) {
  72. bool ok;
  73. number_of_instructions_to_disassemble = parts[1].to_uint(ok);
  74. if (!ok)
  75. return false;
  76. }
  77. // FIXME: Instead of using a fixed "dump_size",
  78. // we can feed instructions to the disassembler one by one
  79. constexpr size_t dump_size = 0x100;
  80. ByteBuffer code;
  81. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  82. auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
  83. if (!value.has_value())
  84. break;
  85. code.append(&value, sizeof(u32));
  86. }
  87. X86::SimpleInstructionStream stream(code.data(), code.size());
  88. X86::Disassembler disassembler(stream);
  89. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  90. auto offset = stream.offset();
  91. auto insn = disassembler.next();
  92. if (!insn.has_value())
  93. break;
  94. printf(String::format(" %08x ", offset + reinterpret_cast<size_t>(first_instruction)).characters());
  95. printf("<+%lu>:\t", reinterpret_cast<size_t>(offset));
  96. printf("%s\n", insn.value().to_string(offset).characters());
  97. }
  98. return true;
  99. }
  100. bool handle_breakpoint_command(const String& command)
  101. {
  102. auto parts = command.split(' ');
  103. if (parts.size() != 2)
  104. return false;
  105. auto argument = parts[1];
  106. if (argument.is_empty())
  107. return false;
  108. u32 breakpoint_address = 0;
  109. if (argument.contains(":")) {
  110. auto source_arguments = argument.split(':');
  111. if (source_arguments.size() != 2)
  112. return false;
  113. bool ok = false;
  114. size_t line = source_arguments[1].to_uint(ok);
  115. if (!ok)
  116. return false;
  117. auto file = source_arguments[0];
  118. if (!file.contains("/"))
  119. file = String::format("./%s", file.characters());
  120. auto result = g_debug_session->debug_info().get_instruction_from_source(file, line);
  121. if (!result.has_value()) {
  122. printf("No matching instruction found\n");
  123. return false;
  124. }
  125. breakpoint_address = result.value();
  126. } else if ((argument[0] >= '0' && argument[0] <= '9')) {
  127. breakpoint_address = strtoul(argument.characters(), nullptr, 16);
  128. } else {
  129. auto symbol = g_debug_session->elf().find_demangled_function(argument);
  130. if (!symbol.has_value()) {
  131. printf("symbol %s not found\n", parts[1].characters());
  132. return false;
  133. }
  134. breakpoint_address = reinterpret_cast<u32>(symbol.value().value());
  135. }
  136. bool success = g_debug_session->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
  137. if (!success) {
  138. fprintf(stderr, "coult not insert breakpoint at: %08x\n", breakpoint_address);
  139. return false;
  140. }
  141. printf("breakpoint insterted at: %08x\n", breakpoint_address);
  142. return true;
  143. }
  144. void print_help()
  145. {
  146. printf("Options:\n"
  147. "cont - Continue execution\n"
  148. "si - step to the next instruction\n"
  149. "sl - step to the next source line\n"
  150. "line - show the position of the current instruction in the source code\n"
  151. "regs - Print registers\n"
  152. "dis [number of instructions] - Print disassembly\n"
  153. "bp <address/symbol/file:line> - Insert a breakpoint\n");
  154. }
  155. int main(int argc, char** argv)
  156. {
  157. if (pledge("stdio proc exec rpath tty", nullptr) < 0) {
  158. perror("pledge");
  159. return 1;
  160. }
  161. const char* command = nullptr;
  162. Core::ArgsParser args_parser;
  163. args_parser.add_positional_argument(command,
  164. "The program to be debugged, along with its arguments",
  165. "program", Core::ArgsParser::Required::Yes);
  166. args_parser.parse(argc, argv);
  167. auto result = DebugSession::exec_and_attach(command);
  168. if (!result) {
  169. fprintf(stderr, "Failed to start debugging session for: \"%s\"\n", command);
  170. exit(1);
  171. }
  172. g_debug_session = result.release_nonnull();
  173. struct sigaction sa;
  174. memset(&sa, 0, sizeof(struct sigaction));
  175. sa.sa_handler = handle_sigint;
  176. sigaction(SIGINT, &sa, nullptr);
  177. bool rc = g_debug_session->insert_breakpoint(g_debug_session->elf().entry().as_ptr());
  178. ASSERT(rc);
  179. DebugInfo::SourcePosition previous_source_position;
  180. bool in_step_line = false;
  181. g_debug_session->run([&](DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  182. if (reason == DebugSession::DebugBreakReason::Exited) {
  183. printf("Program exited.\n");
  184. return DebugSession::DebugDecision::Detach;
  185. }
  186. ASSERT(optional_regs.has_value());
  187. const PtraceRegisters& regs = optional_regs.value();
  188. auto symbol_at_ip = g_debug_session->elf().symbolicate(regs.eip);
  189. auto source_position = g_debug_session->debug_info().get_source_position(regs.eip);
  190. if (in_step_line) {
  191. bool no_source_info = !source_position.has_value();
  192. if (no_source_info || source_position.value() != previous_source_position) {
  193. if (no_source_info)
  194. printf("No source information for current instruction! stoppoing.\n");
  195. in_step_line = false;
  196. } else {
  197. return DebugSession::DebugDecision::SingleStep;
  198. }
  199. }
  200. printf("Program is stopped at: 0x%x (%s)\n", regs.eip, symbol_at_ip.characters());
  201. if (source_position.has_value()) {
  202. previous_source_position = source_position.value();
  203. printf("Source location: %s:%lu\n", source_position.value().file_path.characters(), source_position.value().line_number);
  204. } else {
  205. printf("(No source location information for the current instruction)\n");
  206. }
  207. for (;;) {
  208. auto command_result = editor.get_line("(sdb) ");
  209. if (command_result.is_error())
  210. return DebugSession::DebugDecision::Detach;
  211. auto& command = command_result.value();
  212. bool success = false;
  213. Optional<DebugSession::DebugDecision> decision;
  214. if (command.is_empty() && !editor.history().is_empty()) {
  215. command = editor.history().last();
  216. }
  217. if (command == "cont") {
  218. decision = DebugSession::DebugDecision::Continue;
  219. success = true;
  220. } else if (command == "si") {
  221. decision = DebugSession::DebugDecision::SingleStep;
  222. success = true;
  223. } else if (command == "sl") {
  224. if (source_position.has_value()) {
  225. decision = DebugSession::DebugDecision::SingleStep;
  226. in_step_line = true;
  227. success = true;
  228. } else {
  229. printf("No source location information for the current instruction\n");
  230. }
  231. } else if (command == "regs") {
  232. handle_print_registers(regs);
  233. success = true;
  234. } else if (command.starts_with("dis")) {
  235. success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));
  236. } else if (command.starts_with("bp")) {
  237. success = handle_breakpoint_command(command);
  238. }
  239. if (success && !command.is_empty()) {
  240. // Don't add repeated commands to history
  241. if (editor.history().is_empty() || editor.history().last() != command)
  242. editor.add_to_history(command);
  243. }
  244. if (!success) {
  245. print_help();
  246. }
  247. if (decision.has_value())
  248. return decision.value();
  249. }
  250. });
  251. }