Serenity Operating System
at master 341 lines 12 kB view raw
1/* 2 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#pragma once 8 9#include <AK/Demangle.h> 10#include <AK/DeprecatedString.h> 11#include <AK/Function.h> 12#include <AK/HashMap.h> 13#include <AK/NonnullRefPtr.h> 14#include <AK/Optional.h> 15#include <AK/OwnPtr.h> 16#include <LibCore/MappedFile.h> 17#include <LibDebug/DebugInfo.h> 18#include <LibDebug/ProcessInspector.h> 19#include <signal.h> 20#include <stdio.h> 21#include <sys/arch/regs.h> 22#include <sys/ptrace.h> 23#include <sys/wait.h> 24#include <unistd.h> 25 26namespace Debug { 27 28class DebugSession : public ProcessInspector { 29public: 30 static OwnPtr<DebugSession> exec_and_attach(DeprecatedString const& command, DeprecatedString source_root = {}, Function<ErrorOr<void>()> setup_child = {}, Function<void(float)> on_initialization_progress = {}); 31 static OwnPtr<DebugSession> attach(pid_t pid, DeprecatedString source_root = {}, Function<void(float)> on_initialization_progress = {}); 32 33 virtual ~DebugSession() override; 34 35 // ^Debug::ProcessInspector 36 virtual bool poke(FlatPtr address, FlatPtr data) override; 37 virtual Optional<FlatPtr> peek(FlatPtr address) const override; 38 virtual PtraceRegisters get_registers() const override; 39 virtual void set_registers(PtraceRegisters const&) override; 40 virtual void for_each_loaded_library(Function<IterationDecision(LoadedLibrary const&)>) const override; 41 42 int pid() const { return m_debuggee_pid; } 43 44 bool poke_debug(u32 register_index, FlatPtr data) const; 45 Optional<FlatPtr> peek_debug(u32 register_index) const; 46 47 enum class BreakPointState { 48 Enabled, 49 Disabled, 50 }; 51 52 struct BreakPoint { 53 FlatPtr address { 0 }; 54 FlatPtr original_first_word { 0 }; 55 BreakPointState state { BreakPointState::Disabled }; 56 }; 57 58 struct InsertBreakpointAtSymbolResult { 59 DeprecatedString library_name; 60 FlatPtr address { 0 }; 61 }; 62 63 Optional<InsertBreakpointAtSymbolResult> insert_breakpoint(DeprecatedString const& symbol_name); 64 65 struct InsertBreakpointAtSourcePositionResult { 66 DeprecatedString library_name; 67 DeprecatedString filename; 68 size_t line_number { 0 }; 69 FlatPtr address { 0 }; 70 }; 71 72 Optional<InsertBreakpointAtSourcePositionResult> insert_breakpoint(DeprecatedString const& filename, size_t line_number); 73 74 bool insert_breakpoint(FlatPtr address); 75 bool disable_breakpoint(FlatPtr address); 76 bool enable_breakpoint(FlatPtr address); 77 bool remove_breakpoint(FlatPtr address); 78 bool breakpoint_exists(FlatPtr address) const; 79 80 struct WatchPoint { 81 FlatPtr address { 0 }; 82 u32 debug_register_index { 0 }; 83 u32 ebp { 0 }; 84 }; 85 86 bool insert_watchpoint(FlatPtr address, u32 ebp); 87 bool remove_watchpoint(FlatPtr address); 88 bool disable_watchpoint(FlatPtr address); 89 bool watchpoint_exists(FlatPtr address) const; 90 91 void dump_breakpoints() 92 { 93 for (auto addr : m_breakpoints.keys()) { 94 dbgln("{}", addr); 95 } 96 } 97 98 enum class ContinueType { 99 FreeRun, 100 Syscall, 101 }; 102 void continue_debuggee(ContinueType type = ContinueType::FreeRun); 103 void stop_debuggee(); 104 105 // Returns the wstatus result of waitpid() 106 int continue_debuggee_and_wait(ContinueType type = ContinueType::FreeRun); 107 108 // Returns the new eip 109 FlatPtr single_step(); 110 111 void detach(); 112 113 enum DesiredInitialDebugeeState { 114 Running, 115 Stopped 116 }; 117 template<typename Callback> 118 void run(DesiredInitialDebugeeState, Callback); 119 120 enum DebugDecision { 121 Continue, 122 SingleStep, 123 ContinueBreakAtSyscall, 124 Detach, 125 Kill, 126 }; 127 128 enum DebugBreakReason { 129 Breakpoint, 130 Syscall, 131 Exited, 132 }; 133 134private: 135 explicit DebugSession(pid_t, DeprecatedString source_root, Function<void(float)> on_initialization_progress = {}); 136 137 // x86 breakpoint instruction "int3" 138 static constexpr u8 BREAKPOINT_INSTRUCTION = 0xcc; 139 140 void update_loaded_libs(); 141 142 int m_debuggee_pid { -1 }; 143 DeprecatedString m_source_root; 144 bool m_is_debuggee_dead { false }; 145 146 HashMap<FlatPtr, BreakPoint> m_breakpoints; 147 HashMap<FlatPtr, WatchPoint> m_watchpoints; 148 149 // Maps from library name to LoadedLibrary object 150 HashMap<DeprecatedString, NonnullOwnPtr<LoadedLibrary>> m_loaded_libraries; 151 152 Function<void(float)> m_on_initialization_progress; 153}; 154 155template<typename Callback> 156void DebugSession::run(DesiredInitialDebugeeState initial_debugee_state, Callback callback) 157{ 158 enum class State { 159 FirstIteration, 160 FreeRun, 161 Syscall, 162 ConsecutiveBreakpoint, 163 SingleStep, 164 }; 165 166 State state { State::FirstIteration }; 167 168 auto do_continue_and_wait = [&]() { 169 int wstatus = continue_debuggee_and_wait((state == State::Syscall) ? ContinueType::Syscall : ContinueType::FreeRun); 170 171 // FIXME: This check actually only checks whether the debuggee 172 // stopped because it hit a breakpoint/syscall/is in single stepping mode or not 173 if (WSTOPSIG(wstatus) != SIGTRAP && WSTOPSIG(wstatus) != SIGSTOP) { 174 callback(DebugBreakReason::Exited, Optional<PtraceRegisters>()); 175 m_is_debuggee_dead = true; 176 return true; 177 } 178 return false; 179 }; 180 181 for (;;) { 182 if ((state == State::FirstIteration && initial_debugee_state == DesiredInitialDebugeeState::Running) || state == State::FreeRun || state == State::Syscall) { 183 if (do_continue_and_wait()) 184 break; 185 } 186 if (state == State::FirstIteration) 187 state = State::FreeRun; 188 189 auto regs = get_registers(); 190 191#if ARCH(X86_64) 192 FlatPtr current_instruction = regs.rip; 193#elif ARCH(AARCH64) 194 FlatPtr current_instruction; 195 TODO_AARCH64(); 196#else 197# error Unknown architecture 198#endif 199 200 auto debug_status = peek_debug(DEBUG_STATUS_REGISTER); 201 if (debug_status.has_value() && (debug_status.value() & 0b1111) > 0) { 202 // Tripped a watchpoint 203 auto watchpoint_index = debug_status.value() & 0b1111; 204 Optional<WatchPoint> watchpoint {}; 205 for (auto wp : m_watchpoints) { 206 if ((watchpoint_index & (1 << wp.value.debug_register_index)) == 0) 207 continue; 208 watchpoint = wp.value; 209 break; 210 } 211 if (watchpoint.has_value()) { 212 auto required_ebp = watchpoint.value().ebp; 213 auto found_ebp = false; 214 215#if ARCH(X86_64) 216 FlatPtr current_ebp = regs.rbp; 217#elif ARCH(AARCH64) 218 FlatPtr current_ebp; 219 TODO_AARCH64(); 220#else 221# error Unknown architecture 222#endif 223 224 do { 225 if (current_ebp == required_ebp) { 226 found_ebp = true; 227 break; 228 } 229 auto return_address = peek(current_ebp + sizeof(FlatPtr)); 230 auto next_ebp = peek(current_ebp); 231 VERIFY(return_address.has_value()); 232 VERIFY(next_ebp.has_value()); 233 current_instruction = return_address.value(); 234 current_ebp = next_ebp.value(); 235 } while (current_ebp && current_instruction); 236 237 if (!found_ebp) { 238 dbgln("Removing watchpoint at {:p} because it went out of scope!", watchpoint.value().address); 239 remove_watchpoint(watchpoint.value().address); 240 continue; 241 } 242 } 243 } 244 245 Optional<BreakPoint> current_breakpoint; 246 247 if (state == State::FreeRun || state == State::Syscall) { 248 current_breakpoint = m_breakpoints.get(current_instruction - 1); 249 if (current_breakpoint.has_value()) 250 state = State::FreeRun; 251 } else { 252 current_breakpoint = m_breakpoints.get(current_instruction); 253 } 254 255 if (current_breakpoint.has_value()) { 256 // We want to make the breakpoint transparent to the user of the debugger. 257 // To achieve this, we perform two rollbacks: 258 // 1. Set regs.eip to point at the actual address of the instruction we broke on. 259 // regs.eip currently points to one byte after the address of the original instruction, 260 // because the cpu has just executed the INT3 we patched into the instruction. 261 // 2. We restore the original first byte of the instruction, 262 // because it was patched with INT3. 263 auto breakpoint_addr = bit_cast<FlatPtr>(current_breakpoint.value().address); 264#if ARCH(X86_64) 265 regs.rip = breakpoint_addr; 266#elif ARCH(AARCH64) 267 (void)breakpoint_addr; 268 TODO_AARCH64(); 269#else 270# error Unknown architecture 271#endif 272 set_registers(regs); 273 disable_breakpoint(current_breakpoint.value().address); 274 } 275 276 DebugBreakReason reason = (state == State::Syscall && !current_breakpoint.has_value()) ? DebugBreakReason::Syscall : DebugBreakReason::Breakpoint; 277 278 DebugDecision decision = callback(reason, regs); 279 280 if (reason == DebugBreakReason::Syscall) { 281 // skip the exit from the syscall 282 if (do_continue_and_wait()) 283 break; 284 } 285 286 if (decision == DebugDecision::Continue) { 287 state = State::FreeRun; 288 } else if (decision == DebugDecision::ContinueBreakAtSyscall) { 289 state = State::Syscall; 290 } 291 292 bool did_single_step = false; 293 294 // Re-enable the breakpoint if it wasn't removed by the user 295 if (current_breakpoint.has_value()) { 296 auto current_breakpoint_address = bit_cast<FlatPtr>(current_breakpoint.value().address); 297 if (m_breakpoints.contains(current_breakpoint_address)) { 298 // The current breakpoint was removed to make it transparent to the user. 299 // We now want to re-enable it - the code execution flow could hit it again. 300 // To re-enable the breakpoint, we first perform a single step and execute the 301 // instruction of the breakpoint, and then redo the INT3 patch in its first byte. 302 303 // If the user manually inserted a breakpoint at the current instruction, 304 // we need to disable that breakpoint because we want to singlestep over that 305 // instruction (we re-enable it again later anyways). 306 if (m_breakpoints.contains(current_breakpoint_address) && m_breakpoints.get(current_breakpoint_address).value().state == BreakPointState::Enabled) { 307 disable_breakpoint(current_breakpoint.value().address); 308 } 309 auto stopped_address = single_step(); 310 enable_breakpoint(current_breakpoint.value().address); 311 did_single_step = true; 312 // If there is another breakpoint after the current one, 313 // Then we are already on it (because of single_step) 314 auto breakpoint_at_next_instruction = m_breakpoints.get(stopped_address); 315 if (breakpoint_at_next_instruction.has_value() 316 && breakpoint_at_next_instruction.value().state == BreakPointState::Enabled) { 317 state = State::ConsecutiveBreakpoint; 318 } 319 } 320 } 321 322 if (decision == DebugDecision::SingleStep) { 323 state = State::SingleStep; 324 } 325 326 if (decision == DebugDecision::Detach) { 327 detach(); 328 break; 329 } 330 if (decision == DebugDecision::Kill) { 331 kill(m_debuggee_pid, SIGTERM); 332 break; 333 } 334 335 if (state == State::SingleStep && !did_single_step) { 336 single_step(); 337 } 338 } 339} 340 341}