Serenity Operating System
1/*
2 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
3 * Copyright (c) 2022, the SerenityOS developers.
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include <AK/Assertions.h>
9#include <AK/ByteBuffer.h>
10#include <AK/OwnPtr.h>
11#include <AK/Platform.h>
12#include <AK/StringBuilder.h>
13#include <AK/Try.h>
14#include <LibCore/ArgsParser.h>
15#include <LibCore/System.h>
16#include <LibDebug/DebugInfo.h>
17#include <LibDebug/DebugSession.h>
18#include <LibLine/Editor.h>
19#include <LibMain/Main.h>
20#include <LibX86/Disassembler.h>
21#include <LibX86/Instruction.h>
22#include <signal.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <sys/arch/regs.h>
26#include <unistd.h>
27
28RefPtr<Line::Editor> editor;
29
30OwnPtr<Debug::DebugSession> g_debug_session;
31
32static void handle_sigint(int)
33{
34 outln("Debugger: SIGINT");
35
36 // The destructor of DebugSession takes care of detaching
37 g_debug_session = nullptr;
38}
39
40static void handle_print_registers(PtraceRegisters const& regs)
41{
42#if ARCH(X86_64)
43 outln("rax={:p} rbx={:p} rcx={:p} rdx={:p}", regs.rax, regs.rbx, regs.rcx, regs.rdx);
44 outln("rsp={:p} rbp={:p} rsi={:p} rdi={:p}", regs.rsp, regs.rbp, regs.rsi, regs.rdi);
45 outln("r8 ={:p} r9 ={:p} r10={:p} r11={:p}", regs.r8, regs.r9, regs.r10, regs.r11);
46 outln("r12={:p} r13={:p} r14={:p} r15={:p}", regs.r12, regs.r13, regs.r14, regs.r15);
47 outln("rip={:p} rflags={:p}", regs.rip, regs.rflags);
48#elif ARCH(AARCH64)
49 (void)regs;
50 TODO_AARCH64();
51#else
52# error Unknown architecture
53#endif
54}
55
56static bool handle_disassemble_command(DeprecatedString const& command, FlatPtr first_instruction)
57{
58 auto parts = command.split(' ');
59 size_t number_of_instructions_to_disassemble = 5;
60 if (parts.size() == 2) {
61 auto number = parts[1].to_uint();
62 if (!number.has_value())
63 return false;
64 number_of_instructions_to_disassemble = number.value();
65 }
66
67 // FIXME: Instead of using a fixed "dump_size",
68 // we can feed instructions to the disassembler one by one
69 constexpr size_t dump_size = 0x100;
70 ByteBuffer code;
71 for (size_t i = 0; i < dump_size / sizeof(u32); ++i) {
72 auto value = g_debug_session->peek(first_instruction + i * sizeof(u32));
73 if (!value.has_value())
74 break;
75 if (code.try_append(&value, sizeof(u32)).is_error())
76 break;
77 }
78
79 X86::SimpleInstructionStream stream(code.data(), code.size());
80 X86::Disassembler disassembler(stream);
81
82 for (size_t i = 0; i < number_of_instructions_to_disassemble; ++i) {
83 auto offset = stream.offset();
84 auto insn = disassembler.next();
85 if (!insn.has_value())
86 break;
87
88 outln(" {:p} <+{}>:\t{}", offset + first_instruction, offset, insn.value().to_deprecated_string(offset));
89 }
90
91 return true;
92}
93
94static bool handle_backtrace_command(PtraceRegisters const& regs)
95{
96 (void)regs;
97 TODO();
98 return true;
99}
100
101static bool insert_breakpoint_at_address(FlatPtr address)
102{
103 return g_debug_session->insert_breakpoint(address);
104}
105
106static bool insert_breakpoint_at_source_position(DeprecatedString const& file, size_t line)
107{
108 auto result = g_debug_session->insert_breakpoint(file, line);
109 if (!result.has_value()) {
110 warnln("Could not insert breakpoint at {}:{}", file, line);
111 return false;
112 }
113 outln("Breakpoint inserted [{}:{} ({}:{:p})]", result.value().filename, result.value().line_number, result.value().library_name, result.value().address);
114 return true;
115}
116
117static bool insert_breakpoint_at_symbol(DeprecatedString const& symbol)
118{
119 auto result = g_debug_session->insert_breakpoint(symbol);
120 if (!result.has_value()) {
121 warnln("Could not insert breakpoint at symbol: {}", symbol);
122 return false;
123 }
124 outln("Breakpoint inserted [{}:{:p}]", result.value().library_name, result.value().address);
125 return true;
126}
127
128static bool handle_breakpoint_command(DeprecatedString const& command)
129{
130 auto parts = command.split(' ');
131 if (parts.size() != 2)
132 return false;
133
134 auto argument = parts[1];
135 if (argument.is_empty())
136 return false;
137
138 if (argument.contains(":"sv)) {
139 auto source_arguments = argument.split(':');
140 if (source_arguments.size() != 2)
141 return false;
142 auto line = source_arguments[1].to_uint();
143 if (!line.has_value())
144 return false;
145 auto file = source_arguments[0];
146 return insert_breakpoint_at_source_position(file, line.value());
147 }
148 if ((argument.starts_with("0x"sv))) {
149 return insert_breakpoint_at_address(strtoul(argument.characters() + 2, nullptr, 16));
150 }
151
152 return insert_breakpoint_at_symbol(argument);
153}
154
155static bool handle_examine_command(DeprecatedString const& command)
156{
157 auto parts = command.split(' ');
158 if (parts.size() != 2)
159 return false;
160
161 auto argument = parts[1];
162 if (argument.is_empty())
163 return false;
164
165 if (!(argument.starts_with("0x"sv))) {
166 return false;
167 }
168 FlatPtr address = strtoul(argument.characters() + 2, nullptr, 16);
169 auto res = g_debug_session->peek(address);
170 if (!res.has_value()) {
171 outln("Could not examine memory at address {:p}", address);
172 return true;
173 }
174 outln("{:#x}", res.value());
175 return true;
176}
177
178static void print_help()
179{
180 out("Options:\n"
181 "cont - Continue execution\n"
182 "si - step to the next instruction\n"
183 "sl - step to the next source line\n"
184 "line - show the position of the current instruction in the source code\n"
185 "regs - Print registers\n"
186 "dis [number of instructions] - Print disassembly\n"
187 "bp <address/symbol/file:line> - Insert a breakpoint\n"
188 "bt - show backtrace for current thread\n"
189 "x <address> - examine dword in memory\n");
190}
191
192static NonnullOwnPtr<Debug::DebugSession> create_debug_session(StringView command, pid_t pid_to_debug)
193{
194 if (!command.is_null()) {
195 auto result = Debug::DebugSession::exec_and_attach(command);
196 if (!result) {
197 warnln("Failed to start debugging session for: \"{}\"", command);
198 exit(1);
199 }
200 return result.release_nonnull();
201 }
202
203 if (pid_to_debug == -1) {
204 warnln("Either a command or a pid must be specified");
205 exit(1);
206 }
207
208 auto result = Debug::DebugSession::attach(pid_to_debug);
209 if (!result) {
210 warnln("Failed to attach to pid: {}", pid_to_debug);
211 exit(1);
212 }
213 return result.release_nonnull();
214}
215
216ErrorOr<int> serenity_main(Main::Arguments arguments)
217{
218 editor = Line::Editor::construct();
219
220 TRY(Core::System::pledge("stdio proc ptrace exec rpath tty sigaction cpath unix"));
221
222 StringView command;
223 pid_t pid_to_debug = -1;
224 Core::ArgsParser args_parser;
225 args_parser.add_positional_argument(command,
226 "The program to be debugged, along with its arguments",
227 "program", Core::ArgsParser::Required::No);
228 args_parser.add_option(pid_to_debug, "Attach debugger to running process", "pid", 'p', "PID");
229 args_parser.parse(arguments);
230
231 g_debug_session = create_debug_session(command, pid_to_debug);
232
233 struct sigaction sa {
234 };
235 sa.sa_handler = handle_sigint;
236 TRY(Core::System::sigaction(SIGINT, &sa, nullptr));
237
238 Debug::DebugInfo::SourcePosition previous_source_position;
239 bool in_step_line = false;
240
241 g_debug_session->run(Debug::DebugSession::DesiredInitialDebugeeState::Stopped, [&](Debug::DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) {
242 if (reason == Debug::DebugSession::DebugBreakReason::Exited) {
243 outln("Program exited.");
244 return Debug::DebugSession::DebugDecision::Detach;
245 }
246
247 VERIFY(optional_regs.has_value());
248 const PtraceRegisters& regs = optional_regs.value();
249#if ARCH(X86_64)
250 const FlatPtr ip = regs.rip;
251#elif ARCH(AARCH64)
252 const FlatPtr ip = 0; // FIXME
253 TODO_AARCH64();
254#else
255# error Unknown architecture
256#endif
257
258 auto symbol_at_ip = g_debug_session->symbolicate(ip);
259
260 auto source_position = g_debug_session->get_source_position(ip);
261
262 if (in_step_line) {
263 bool no_source_info = !source_position.has_value();
264 if (no_source_info || source_position.value() != previous_source_position) {
265 if (no_source_info)
266 outln("No source information for current instruction! stopping.");
267 in_step_line = false;
268 } else {
269 return Debug::DebugSession::DebugDecision::SingleStep;
270 }
271 }
272
273 if (symbol_at_ip.has_value())
274 outln("Program is stopped at: {:p} ({}:{})", ip, symbol_at_ip.value().library_name, symbol_at_ip.value().symbol);
275 else
276 outln("Program is stopped at: {:p}", ip);
277
278 if (source_position.has_value()) {
279 previous_source_position = source_position.value();
280 outln("Source location: {}:{}", source_position.value().file_path, source_position.value().line_number);
281 } else {
282 outln("(No source location information for the current instruction)");
283 }
284
285 for (;;) {
286 auto command_result = editor->get_line("(sdb) ");
287
288 if (command_result.is_error())
289 return Debug::DebugSession::DebugDecision::Detach;
290
291 auto& command = command_result.value();
292
293 bool success = false;
294 Optional<Debug::DebugSession::DebugDecision> decision;
295
296 if (command.is_empty() && !editor->history().is_empty()) {
297 command = editor->history().last().entry;
298 }
299 if (command == "cont") {
300 decision = Debug::DebugSession::DebugDecision::Continue;
301 success = true;
302 } else if (command == "si") {
303 decision = Debug::DebugSession::DebugDecision::SingleStep;
304 success = true;
305 } else if (command == "sl") {
306 if (source_position.has_value()) {
307 decision = Debug::DebugSession::DebugDecision::SingleStep;
308 in_step_line = true;
309 success = true;
310 } else {
311 outln("No source location information for the current instruction");
312 }
313 } else if (command == "regs") {
314 handle_print_registers(regs);
315 success = true;
316
317 } else if (command.starts_with("dis"sv)) {
318 success = handle_disassemble_command(command, ip);
319
320 } else if (command.starts_with("bp"sv)) {
321 success = handle_breakpoint_command(command);
322 } else if (command.starts_with("x"sv)) {
323 success = handle_examine_command(command);
324 } else if (command.starts_with("bt"sv)) {
325 success = handle_backtrace_command(regs);
326 }
327
328 if (success && !command.is_empty()) {
329 // Don't add repeated commands to history
330 if (editor->history().is_empty() || editor->history().last().entry != command)
331 editor->add_to_history(command);
332 }
333 if (!success) {
334 print_help();
335 }
336 if (decision.has_value())
337 return decision.value();
338 }
339 });
340
341 return 0;
342}