main.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 "DebugSession.h"
  27. #include <AK/Assertions.h>
  28. #include <AK/ByteBuffer.h>
  29. #include <AK/Demangle.h>
  30. #include <AK/LogStream.h>
  31. #include <AK/StringBuilder.h>
  32. #include <AK/kmalloc.h>
  33. #include <LibC/sys/arch/i386/regs.h>
  34. #include <LibCore/File.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. auto parts = command.split(' ');
  91. size_t number_of_instructions_to_disassemble = 5;
  92. if (parts.size() == 2) {
  93. bool ok;
  94. number_of_instructions_to_disassemble = parts[1].to_uint(ok);
  95. if (!ok)
  96. return false;
  97. }
  98. // FIXME: Instead of using a fixed "dump_size",
  99. // we can feed instructions to the disassembler one by one
  100. constexpr size_t dump_size = 0x100;
  101. ByteBuffer code;
  102. for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
  103. auto value = g_debug_session->peek(reinterpret_cast<u32*>(first_instruction) + i);
  104. if (!value.has_value())
  105. break;
  106. code.append(&value, sizeof(u32));
  107. }
  108. X86::SimpleInstructionStream stream(code.data(), code.size());
  109. X86::Disassembler disassembler(stream);
  110. for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
  111. auto offset = stream.offset();
  112. auto insn = disassembler.next();
  113. if (!insn.has_value())
  114. break;
  115. printf(String::format(" %08x ", offset + reinterpret_cast<size_t>(first_instruction)).characters());
  116. printf("<+%lu>:\t", reinterpret_cast<size_t>(offset));
  117. printf("%s\n", insn.value().to_string(offset).characters());
  118. }
  119. return true;
  120. }
  121. bool handle_breakpoint_command(const String& command)
  122. {
  123. auto parts = command.split(' ');
  124. if (parts.size() != 2)
  125. return false;
  126. auto argument = parts[1];
  127. if (argument.is_empty())
  128. return false;
  129. u32 breakpoint_address = 0;
  130. if ((argument[0] >= '0' && argument[0] <= '9')) {
  131. breakpoint_address = strtoul(argument.characters(), nullptr, 16);
  132. } else {
  133. auto symbol = g_debug_session->elf().find_demangled_function(argument);
  134. if (!symbol.has_value()) {
  135. printf("symbol %s not found\n", parts[1].characters());
  136. return false;
  137. }
  138. breakpoint_address = reinterpret_cast<u32>(symbol.value().value());
  139. }
  140. bool success = g_debug_session->insert_breakpoint(reinterpret_cast<void*>(breakpoint_address));
  141. if (!success) {
  142. fprintf(stderr, "coult not insert breakpoint at: %08x\n", breakpoint_address);
  143. return false;
  144. }
  145. printf("breakpoint insterted at: %08x\n", breakpoint_address);
  146. return true;
  147. }
  148. void print_help()
  149. {
  150. printf("Options:\n"
  151. "cont - Continue execution\n"
  152. "regs - Print registers\n"
  153. "dis [number of instructions] - Print disassembly\n"
  154. "bp <address/symbol> - Insert a breakpoint\n");
  155. }
  156. int main(int argc, char** argv)
  157. {
  158. if (pledge("stdio proc exec rpath", nullptr) < 0) {
  159. perror("pledge");
  160. return 1;
  161. }
  162. if (argc == 1)
  163. return usage();
  164. StringBuilder command;
  165. command.append(argv[1]);
  166. for (int i = 2; i < argc; ++i) {
  167. command.appendf("%s ", argv[i]);
  168. }
  169. auto result = DebugSession::exec_and_attach(command.to_string());
  170. if (!result) {
  171. fprintf(stderr, "Failed to start debugging session for: \"%s\"\n", command.to_string().characters());
  172. exit(1);
  173. }
  174. g_debug_session = result.release_nonnull();
  175. struct sigaction sa;
  176. memset(&sa, 0, sizeof(struct sigaction));
  177. sa.sa_handler = handle_sigint;
  178. sigaction(SIGINT, &sa, nullptr);
  179. bool rc = g_debug_session->insert_breakpoint(g_debug_session->elf().entry().as_ptr());
  180. ASSERT(rc);
  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. printf("Program is stopped at: 0x%x\n", regs.eip);
  189. for (;;) {
  190. auto command = get_command();
  191. bool success = false;
  192. if (command == "cont") {
  193. return DebugSession::DebugDecision::Continue;
  194. }
  195. if (command == "regs") {
  196. handle_print_registers(regs);
  197. success = true;
  198. } else if (command.starts_with("dis")) {
  199. success = handle_disassemble_command(command, reinterpret_cast<void*>(regs.eip));
  200. } else if (command.starts_with("bp")) {
  201. success = handle_breakpoint_command(command);
  202. }
  203. if (!success)
  204. print_help();
  205. }
  206. });
  207. }