main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. RefPtr<Line::Editor> editor;
  46. OwnPtr<Debug::DebugSession> g_debug_session;
  47. static void handle_sigint(int)
  48. {
  49. outln("Debugger: SIGINT");
  50. // The destructor of DebugSession takes care of detaching
  51. g_debug_session = nullptr;
  52. }
  53. static void handle_print_registers(const PtraceRegisters& regs)
  54. {
  55. outln("eax={:08x} ebx={:08x} ecx={:08x} edx={:08x}", regs.eax, regs.ebx, regs.ecx, regs.edx);
  56. outln("esp={:08x} ebp={:08x} esi={:08x} edi={:08x}", regs.esp, regs.ebp, regs.esi, regs.edi);
  57. outln("eip={:08x} eflags={:08x}", regs.eip, regs.eflags);
  58. }
  59. static bool handle_disassemble_command(const String& command, void* first_instruction)
  60. {
  61. auto parts = command.split(' ');
  62. size_t number_of_instructions_to_disassemble = 5;
  63. if (parts.size() == 2) {
  64. auto number = parts[1].to_uint();
  65. if (!number.has_value())
  66. return false;
  67. number_of_instructions_to_disassemble = number.value();
  68. }
  69. // FIXME: Instead of using a fixed "dump_size",
  70. // we can feed instructions to the disassembler one by one
  71. constexpr size_t dump_size = 0x100;
  72. ByteBuffer code;
  73. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  74. auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
  75. if (!value.has_value())
  76. break;
  77. code.append(&value, sizeof(u32));
  78. }
  79. X86::SimpleInstructionStream stream(code.data(), code.size());
  80. X86::Disassembler disassembler(stream);
  81. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  82. auto offset = stream.offset();
  83. auto insn = disassembler.next();
  84. if (!insn.has_value())
  85. break;
  86. outln(" {:p} <+{}>:\t{}", offset + reinterpret_cast<size_t>(first_instruction), offset, insn.value().to_string(offset));
  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().file_name, 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. printf("could not examine memory at address 0x%x\n", address);
  152. return true;
  153. }
  154. printf("0x%x\n", 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. "x <address> - examine dword in memory\n");
  168. }
  169. int main(int argc, char** argv)
  170. {
  171. editor = Line::Editor::construct();
  172. if (pledge("stdio proc ptrace exec rpath tty sigaction cpath unix fattr", nullptr) < 0) {
  173. perror("pledge");
  174. return 1;
  175. }
  176. const char* command = nullptr;
  177. Core::ArgsParser args_parser;
  178. args_parser.add_positional_argument(command,
  179. "The program to be debugged, along with its arguments",
  180. "program", Core::ArgsParser::Required::Yes);
  181. args_parser.parse(argc, argv);
  182. auto result = Debug::DebugSession::exec_and_attach(command);
  183. if (!result) {
  184. warnln("Failed to start debugging session for: \"{}\"", command);
  185. exit(1);
  186. }
  187. g_debug_session = result.release_nonnull();
  188. struct sigaction sa;
  189. memset(&sa, 0, sizeof(struct sigaction));
  190. sa.sa_handler = handle_sigint;
  191. sigaction(SIGINT, &sa, nullptr);
  192. Debug::DebugInfo::SourcePosition previous_source_position;
  193. bool in_step_line = false;
  194. g_debug_session->run(Debug::DebugSession::DesiredInitialDebugeeState::Stopped, [&](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  195. if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
  196. outln("Program exited.");
  197. return Debug::DebugSession::DebugDecision::Detach;
  198. }
  199. ASSERT(optional_regs.has_value());
  200. const PtraceRegisters& regs = optional_regs.value();
  201. auto symbol_at_ip = g_debug_session->symbolicate(regs.eip);
  202. auto source_position = g_debug_session->get_source_position(regs.eip);
  203. if (in_step_line) {
  204. bool no_source_info = !source_position.has_value();
  205. if (no_source_info || source_position.value() != previous_source_position) {
  206. if (no_source_info)
  207. outln("No source information for current instruction! stoppoing.");
  208. in_step_line = false;
  209. } else {
  210. return Debug::DebugSession::DebugDecision::SingleStep;
  211. }
  212. }
  213. if (symbol_at_ip.has_value())
  214. outln("Program is stopped at: {:p} ({}:{})", regs.eip, symbol_at_ip.value().library_name, symbol_at_ip.value().symbol);
  215. else
  216. outln("Program is stopped at: {:p}", regs.eip);
  217. if (source_position.has_value()) {
  218. previous_source_position = source_position.value();
  219. outln("Source location: {}:{}", source_position.value().file_path, source_position.value().line_number);
  220. } else {
  221. outln("(No source location information for the current instruction)");
  222. }
  223. for (;;) {
  224. auto command_result = editor->get_line("(sdb) ");
  225. if (command_result.is_error())
  226. return Debug::DebugSession::DebugDecision::Detach;
  227. auto& command = command_result.value();
  228. bool success = false;
  229. Optional<Debug::DebugSession::DebugDecision> decision;
  230. if (command.is_empty() && !editor->history().is_empty()) {
  231. command = editor->history().last().entry;
  232. }
  233. if (command == "cont") {
  234. decision = Debug::DebugSession::DebugDecision::Continue;
  235. success = true;
  236. } else if (command == "si") {
  237. decision = Debug::DebugSession::DebugDecision::SingleStep;
  238. success = true;
  239. } else if (command == "sl") {
  240. if (source_position.has_value()) {
  241. decision = Debug::DebugSession::DebugDecision::SingleStep;
  242. in_step_line = true;
  243. success = true;
  244. } else {
  245. outln("No source location information for the current instruction");
  246. }
  247. } else if (command == "regs") {
  248. handle_print_registers(regs);
  249. success = true;
  250. } else if (command.starts_with("dis")) {
  251. success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));
  252. } else if (command.starts_with("bp")) {
  253. success = handle_breakpoint_command(command);
  254. } else if (command.starts_with("x")) {
  255. success = handle_examine_command(command);
  256. }
  257. if (success && !command.is_empty()) {
  258. // Don't add repeated commands to history
  259. if (editor->history().is_empty() || editor->history().last().entry != command)
  260. editor->add_to_history(command);
  261. }
  262. if (!success) {
  263. print_help();
  264. }
  265. if (decision.has_value())
  266. return decision.value();
  267. }
  268. });
  269. }