main.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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/File.h>
  34. #include <LibDebug/DebugSession.h>
  35. #include <LibX86/Disassembler.h>
  36. #include <LibX86/Instruction.h>
  37. #include <signal.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <unistd.h>
  42. static int usage()
  43. {
  44. printf("usage: sdb [command...]\n");
  45. return 1;
  46. }
  47. OwnPtr<DebugSession> g_debug_session;
  48. static void handle_sigint(int)
  49. {
  50. printf("Debugger: SIGINT\n");
  51. // The destructor of DebugSession takes care of detaching
  52. g_debug_session = nullptr;
  53. }
  54. String get_command()
  55. {
  56. printf("(sdb) ");
  57. fflush(stdout);
  58. char* line = nullptr;
  59. size_t allocated_size = 0;
  60. ssize_t nread = getline(&line, &allocated_size, stdin);
  61. if (nread < 0) {
  62. if (errno == 0) {
  63. fprintf(stderr, "\n");
  64. } else {
  65. perror("getline");
  66. exit(1);
  67. }
  68. }
  69. String command(line);
  70. free(line);
  71. if (command.ends_with('\n'))
  72. command = command.substring(0, command.length() - 1);
  73. return command;
  74. }
  75. void handle_print_registers(const PtraceRegisters& regs)
  76. {
  77. printf("eax: 0x%x\n", regs.eax);
  78. printf("ecx: 0x%x\n", regs.ecx);
  79. printf("edx: 0x%x\n", regs.edx);
  80. printf("ebx: 0x%x\n", regs.ebx);
  81. printf("esp: 0x%x\n", regs.esp);
  82. printf("ebp: 0x%x\n", regs.ebp);
  83. printf("esi: 0x%x\n", regs.esi);
  84. printf("edi: 0x%x\n", regs.edi);
  85. printf("eip: 0x%x\n", regs.eip);
  86. printf("eflags: 0x%x\n", regs.eflags);
  87. }
  88. bool handle_disassemble_command(const String& command, void* first_instruction)
  89. {
  90. (void)demangle("foo");
  91. auto parts = command.split(' ');
  92. size_t number_of_instructions_to_disassemble = 5;
  93. if (parts.size() == 2) {
  94. bool ok;
  95. number_of_instructions_to_disassemble = parts[1].to_uint(ok);
  96. if (!ok)
  97. return false;
  98. }
  99. // FIXME: Instead of using a fixed "dump_size",
  100. // we can feed instructions to the disassembler one by one
  101. constexpr size_t dump_size = 0x100;
  102. ByteBuffer code;
  103. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  104. auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
  105. if (!value.has_value())
  106. break;
  107. code.append(&value, sizeof(u32));
  108. }
  109. X86::SimpleInstructionStream stream(code.data(), code.size());
  110. X86::Disassembler disassembler(stream);
  111. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  112. auto offset = stream.offset();
  113. auto insn = disassembler.next();
  114. if (!insn.has_value())
  115. break;
  116. printf(String::format(" %08x ", offset + reinterpret_cast<size_t>(first_instruction)).characters());
  117. printf("<+%lu>:\t", reinterpret_cast<size_t>(offset));
  118. printf("%s\n", insn.value().to_string(offset).characters());
  119. }
  120. return true;
  121. }
  122. bool handle_breakpoint_command(const String& command)
  123. {
  124. auto parts = command.split(' ');
  125. if (parts.size() != 2)
  126. return false;
  127. auto argument = parts[1];
  128. if (argument.is_empty())
  129. return false;
  130. u32 breakpoint_address = 0;
  131. if ((argument[0] >= '0' && argument[0] <= '9')) {
  132. breakpoint_address = strtoul(argument.characters(), nullptr, 16);
  133. } else {
  134. auto symbol = g_debug_session->elf().find_demangled_function(argument);
  135. if (!symbol.has_value()) {
  136. printf("symbol %s not found\n", parts[1].characters());
  137. return false;
  138. }
  139. breakpoint_address = reinterpret_cast<u32>(symbol.value().value());
  140. }
  141. bool success = g_debug_session->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
  142. if (!success) {
  143. fprintf(stderr, "coult not insert breakpoint at: %08x\n", breakpoint_address);
  144. return false;
  145. }
  146. printf("breakpoint insterted at: %08x\n", breakpoint_address);
  147. return true;
  148. }
  149. void print_help()
  150. {
  151. printf("Options:\n"
  152. "cont - Continue execution\n"
  153. "s - step over the current instruction\n"
  154. "regs - Print registers\n"
  155. "dis [number of instructions] - Print disassembly\n"
  156. "bp <address/symbol> - Insert a breakpoint\n");
  157. }
  158. int main(int argc, char** argv)
  159. {
  160. if (pledge("stdio proc exec rpath", nullptr) < 0) {
  161. perror("pledge");
  162. return 1;
  163. }
  164. if (argc == 1)
  165. return usage();
  166. StringBuilder command;
  167. command.append(argv[1]);
  168. for (int i = 2; i < argc; ++i) {
  169. command.appendf("%s ", argv[i]);
  170. }
  171. auto result = DebugSession::exec_and_attach(command.to_string());
  172. if (!result) {
  173. fprintf(stderr, "Failed to start debugging session for: \"%s\"\n", command.to_string().characters());
  174. exit(1);
  175. }
  176. g_debug_session = result.release_nonnull();
  177. struct sigaction sa;
  178. memset(&sa, 0, sizeof(struct sigaction));
  179. sa.sa_handler = handle_sigint;
  180. sigaction(SIGINT, &sa, nullptr);
  181. bool rc = g_debug_session->insert_breakpoint(g_debug_session->elf().entry().as_ptr());
  182. ASSERT(rc);
  183. String previous_command;
  184. g_debug_session->run([&](DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
  185. if (reason == DebugSession::DebugBreakReason::Exited) {
  186. printf("Program exited.\n");
  187. return DebugSession::DebugDecision::Detach;
  188. }
  189. ASSERT(optional_regs.has_value());
  190. const PtraceRegisters& regs = optional_regs.value();
  191. auto symbol_at_ip = g_debug_session->elf().symbolicate(regs.eip);
  192. printf("Program is stopped at: 0x%x (%s)\n", regs.eip, symbol_at_ip.characters());
  193. for (;;) {
  194. auto command = get_command();
  195. bool success = false;
  196. Optional<DebugSession::DebugDecision> decision;
  197. if (command.is_empty() && !previous_command.is_empty()) {
  198. command = previous_command;
  199. }
  200. if (command == "cont") {
  201. decision = DebugSession::DebugDecision::Continue;
  202. success = true;
  203. }
  204. if (command == "s") {
  205. decision = DebugSession::DebugDecision::SingleStep;
  206. success = true;
  207. }
  208. if (command == "regs") {
  209. handle_print_registers(regs);
  210. success = true;
  211. } else if (command.starts_with("dis")) {
  212. success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));
  213. } else if (command.starts_with("bp")) {
  214. success = handle_breakpoint_command(command);
  215. }
  216. if (success && !command.is_empty()) {
  217. previous_command = command;
  218. }
  219. if (!success) {
  220. print_help();
  221. }
  222. if (decision.has_value())
  223. return decision.value();
  224. }
  225. });
  226. }