Serenity Operating System
at master 518 lines 16 kB view raw
1/* 2 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include "DebugSession.h" 8#include <AK/JsonObject.h> 9#include <AK/JsonValue.h> 10#include <AK/LexicalPath.h> 11#include <AK/Optional.h> 12#include <AK/Platform.h> 13#include <LibCore/DeprecatedFile.h> 14#include <LibRegex/Regex.h> 15#include <stdlib.h> 16#include <sys/mman.h> 17 18namespace Debug { 19 20DebugSession::DebugSession(pid_t pid, DeprecatedString source_root, Function<void(float)> on_initialization_progress) 21 : m_debuggee_pid(pid) 22 , m_source_root(source_root) 23 , m_on_initialization_progress(move(on_initialization_progress)) 24{ 25} 26 27DebugSession::~DebugSession() 28{ 29 if (m_is_debuggee_dead) 30 return; 31 32 for (auto const& bp : m_breakpoints) { 33 disable_breakpoint(bp.key); 34 } 35 m_breakpoints.clear(); 36 37 for (auto const& wp : m_watchpoints) { 38 disable_watchpoint(wp.key); 39 } 40 m_watchpoints.clear(); 41 42 if (ptrace(PT_DETACH, m_debuggee_pid, 0, 0) < 0) { 43 perror("PT_DETACH"); 44 } 45} 46 47void DebugSession::for_each_loaded_library(Function<IterationDecision(LoadedLibrary const&)> func) const 48{ 49 for (auto const& lib_name : m_loaded_libraries.keys()) { 50 auto const& lib = *m_loaded_libraries.get(lib_name).value(); 51 if (func(lib) == IterationDecision::Break) 52 break; 53 } 54} 55 56OwnPtr<DebugSession> DebugSession::exec_and_attach(DeprecatedString const& command, 57 DeprecatedString source_root, 58 Function<ErrorOr<void>()> setup_child, 59 Function<void(float)> on_initialization_progress) 60{ 61 auto pid = fork(); 62 63 if (pid < 0) { 64 perror("fork"); 65 exit(1); 66 } 67 68 if (!pid) { 69 70 if (setup_child) { 71 if (setup_child().is_error()) { 72 perror("DebugSession::setup_child"); 73 exit(1); 74 } 75 } 76 77 if (ptrace(PT_TRACE_ME, 0, 0, 0) < 0) { 78 perror("PT_TRACE_ME"); 79 exit(1); 80 } 81 82 auto parts = command.split(' '); 83 VERIFY(!parts.is_empty()); 84 char const** args = bit_cast<char const**>(calloc(parts.size() + 1, sizeof(char const*))); 85 for (size_t i = 0; i < parts.size(); i++) { 86 args[i] = parts[i].characters(); 87 } 88 char const** envp = bit_cast<char const**>(calloc(2, sizeof(char const*))); 89 // This causes loader to stop on a breakpoint before jumping to the entry point of the program. 90 envp[0] = "_LOADER_BREAKPOINT=1"; 91 int rc = execvpe(args[0], const_cast<char**>(args), const_cast<char**>(envp)); 92 if (rc < 0) { 93 perror("execvp"); 94 exit(1); 95 } 96 } 97 98 if (waitpid(pid, nullptr, WSTOPPED) != pid) { 99 perror("waitpid"); 100 return {}; 101 } 102 103 if (ptrace(PT_ATTACH, pid, 0, 0) < 0) { 104 perror("PT_ATTACH"); 105 return {}; 106 } 107 108 // We want to continue until the exit from the 'execve' syscall. 109 // This ensures that when we start debugging the process 110 // it executes the target image, and not the forked image of the tracing process. 111 // NOTE: we only need to do this when we are debugging a new process (i.e not attaching to a process that's already running!) 112 113 if (waitpid(pid, nullptr, WSTOPPED) != pid) { 114 perror("wait_pid"); 115 return {}; 116 } 117 118 auto debug_session = adopt_own(*new DebugSession(pid, source_root, move(on_initialization_progress))); 119 120 // Continue until breakpoint before entry point of main program 121 int wstatus = debug_session->continue_debuggee_and_wait(); 122 if (WSTOPSIG(wstatus) != SIGTRAP) { 123 dbgln("expected SIGTRAP"); 124 return {}; 125 } 126 127 // At this point, libraries should have been loaded 128 debug_session->update_loaded_libs(); 129 130 return debug_session; 131} 132 133OwnPtr<DebugSession> DebugSession::attach(pid_t pid, DeprecatedString source_root, Function<void(float)> on_initialization_progress) 134{ 135 if (ptrace(PT_ATTACH, pid, 0, 0) < 0) { 136 perror("PT_ATTACH"); 137 return {}; 138 } 139 140 int status = 0; 141 if (waitpid(pid, &status, WSTOPPED | WEXITED) != pid || !WIFSTOPPED(status)) { 142 perror("waitpid"); 143 return {}; 144 } 145 146 auto debug_session = adopt_own(*new DebugSession(pid, source_root, move(on_initialization_progress))); 147 // At this point, libraries should have been loaded 148 debug_session->update_loaded_libs(); 149 150 return debug_session; 151} 152 153bool DebugSession::poke(FlatPtr address, FlatPtr data) 154{ 155 if (ptrace(PT_POKE, m_debuggee_pid, bit_cast<void*>(address), bit_cast<void*>(data)) < 0) { 156 perror("PT_POKE"); 157 return false; 158 } 159 return true; 160} 161 162Optional<FlatPtr> DebugSession::peek(FlatPtr address) const 163{ 164 Optional<FlatPtr> result; 165 auto rc = ptrace(PT_PEEK, m_debuggee_pid, bit_cast<void*>(address), nullptr); 166 if (errno == 0) 167 result = static_cast<FlatPtr>(rc); 168 return result; 169} 170 171bool DebugSession::poke_debug(u32 register_index, FlatPtr data) const 172{ 173 if (ptrace(PT_POKEDEBUG, m_debuggee_pid, bit_cast<void*>(static_cast<FlatPtr>(register_index)), bit_cast<void*>(data)) < 0) { 174 perror("PT_POKEDEBUG"); 175 return false; 176 } 177 return true; 178} 179 180Optional<FlatPtr> DebugSession::peek_debug(u32 register_index) const 181{ 182 auto rc = ptrace(PT_PEEKDEBUG, m_debuggee_pid, bit_cast<void*>(static_cast<FlatPtr>(register_index)), nullptr); 183 if (errno == 0) 184 return static_cast<FlatPtr>(rc); 185 186 return {}; 187} 188 189bool DebugSession::insert_breakpoint(FlatPtr address) 190{ 191 // We insert a software breakpoint by 192 // patching the first byte of the instruction at 'address' 193 // with the breakpoint instruction (int3) 194 195 if (m_breakpoints.contains(address)) 196 return false; 197 198 auto original_bytes = peek(address); 199 200 if (!original_bytes.has_value()) 201 return false; 202 203 VERIFY((original_bytes.value() & 0xff) != BREAKPOINT_INSTRUCTION); 204 205 BreakPoint breakpoint { address, original_bytes.value(), BreakPointState::Disabled }; 206 207 m_breakpoints.set(address, breakpoint); 208 209 enable_breakpoint(breakpoint.address); 210 211 return true; 212} 213 214bool DebugSession::disable_breakpoint(FlatPtr address) 215{ 216 auto breakpoint = m_breakpoints.get(address); 217 VERIFY(breakpoint.has_value()); 218 if (!poke(breakpoint.value().address, breakpoint.value().original_first_word)) 219 return false; 220 221 auto bp = m_breakpoints.get(breakpoint.value().address).value(); 222 bp.state = BreakPointState::Disabled; 223 m_breakpoints.set(bp.address, bp); 224 return true; 225} 226 227bool DebugSession::enable_breakpoint(FlatPtr address) 228{ 229 auto breakpoint = m_breakpoints.get(address); 230 VERIFY(breakpoint.has_value()); 231 232 VERIFY(breakpoint.value().state == BreakPointState::Disabled); 233 234 if (!poke(breakpoint.value().address, (breakpoint.value().original_first_word & ~static_cast<FlatPtr>(0xff)) | BREAKPOINT_INSTRUCTION)) 235 return false; 236 237 auto bp = m_breakpoints.get(breakpoint.value().address).value(); 238 bp.state = BreakPointState::Enabled; 239 m_breakpoints.set(bp.address, bp); 240 return true; 241} 242 243bool DebugSession::remove_breakpoint(FlatPtr address) 244{ 245 if (!disable_breakpoint(address)) 246 return false; 247 248 m_breakpoints.remove(address); 249 return true; 250} 251 252bool DebugSession::breakpoint_exists(FlatPtr address) const 253{ 254 return m_breakpoints.contains(address); 255} 256 257bool DebugSession::insert_watchpoint(FlatPtr address, u32 ebp) 258{ 259 auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER); 260 if (!current_register_status.has_value()) 261 return false; 262 // FIXME: 64 bit support 263 u32 dr7_value = static_cast<u32>(current_register_status.value()); 264 u32 next_available_index; 265 for (next_available_index = 0; next_available_index < 4; next_available_index++) { 266 auto bitmask = 1 << (next_available_index * 2); 267 if ((dr7_value & bitmask) == 0) 268 break; 269 } 270 if (next_available_index > 3) 271 return false; 272 WatchPoint watchpoint { address, next_available_index, ebp }; 273 274 if (!poke_debug(next_available_index, bit_cast<FlatPtr>(address))) 275 return false; 276 277 dr7_value |= (1u << (next_available_index * 2)); // Enable local breakpoint for our index 278 auto condition_shift = 16 + (next_available_index * 4); 279 dr7_value &= ~(0b11u << condition_shift); 280 dr7_value |= 1u << condition_shift; // Trigger on writes 281 auto length_shift = 18 + (next_available_index * 4); 282 dr7_value &= ~(0b11u << length_shift); 283 // FIXME: take variable size into account? 284 dr7_value |= 0b11u << length_shift; // 4 bytes wide 285 if (!poke_debug(DEBUG_CONTROL_REGISTER, dr7_value)) 286 return false; 287 288 m_watchpoints.set(address, watchpoint); 289 return true; 290} 291 292bool DebugSession::remove_watchpoint(FlatPtr address) 293{ 294 if (!disable_watchpoint(address)) 295 return false; 296 return m_watchpoints.remove(address); 297} 298 299bool DebugSession::disable_watchpoint(FlatPtr address) 300{ 301 VERIFY(watchpoint_exists(address)); 302 auto watchpoint = m_watchpoints.get(address).value(); 303 if (!poke_debug(watchpoint.debug_register_index, 0)) 304 return false; 305 auto current_register_status = peek_debug(DEBUG_CONTROL_REGISTER); 306 if (!current_register_status.has_value()) 307 return false; 308 u32 dr7_value = current_register_status.value(); 309 dr7_value &= ~(1u << watchpoint.debug_register_index * 2); 310 if (!poke_debug(watchpoint.debug_register_index, dr7_value)) 311 return false; 312 return true; 313} 314 315bool DebugSession::watchpoint_exists(FlatPtr address) const 316{ 317 return m_watchpoints.contains(address); 318} 319 320PtraceRegisters DebugSession::get_registers() const 321{ 322 PtraceRegisters regs; 323 if (ptrace(PT_GETREGS, m_debuggee_pid, &regs, 0) < 0) { 324 perror("PT_GETREGS"); 325 VERIFY_NOT_REACHED(); 326 } 327 return regs; 328} 329 330void DebugSession::set_registers(PtraceRegisters const& regs) 331{ 332 if (ptrace(PT_SETREGS, m_debuggee_pid, bit_cast<void*>(&regs), 0) < 0) { 333 perror("PT_SETREGS"); 334 VERIFY_NOT_REACHED(); 335 } 336} 337 338void DebugSession::continue_debuggee(ContinueType type) 339{ 340 int command = (type == ContinueType::FreeRun) ? PT_CONTINUE : PT_SYSCALL; 341 if (ptrace(command, m_debuggee_pid, 0, 0) < 0) { 342 perror("continue"); 343 VERIFY_NOT_REACHED(); 344 } 345} 346 347int DebugSession::continue_debuggee_and_wait(ContinueType type) 348{ 349 continue_debuggee(type); 350 int wstatus = 0; 351 if (waitpid(m_debuggee_pid, &wstatus, WSTOPPED | WEXITED) != m_debuggee_pid) { 352 perror("waitpid"); 353 VERIFY_NOT_REACHED(); 354 } 355 return wstatus; 356} 357 358FlatPtr DebugSession::single_step() 359{ 360 // Single stepping works by setting the x86 TRAP flag bit in the eflags register. 361 // This flag causes the cpu to enter single-stepping mode, which causes 362 // Interrupt 1 (debug interrupt) to be emitted after every instruction. 363 // To single step the program, we set the TRAP flag and continue the debuggee. 364 // After the debuggee has stopped, we clear the TRAP flag. 365 366 auto regs = get_registers(); 367#if ARCH(X86_64) 368 constexpr u32 TRAP_FLAG = 0x100; 369 regs.rflags |= TRAP_FLAG; 370#elif ARCH(AARCH64) 371 TODO_AARCH64(); 372#else 373# error Unknown architecture 374#endif 375 set_registers(regs); 376 377 continue_debuggee(); 378 379 if (waitpid(m_debuggee_pid, 0, WSTOPPED) != m_debuggee_pid) { 380 perror("waitpid"); 381 VERIFY_NOT_REACHED(); 382 } 383 384 regs = get_registers(); 385#if ARCH(X86_64) 386 regs.rflags &= ~(TRAP_FLAG); 387#elif ARCH(AARCH64) 388 TODO_AARCH64(); 389#else 390# error Unknown architecture 391#endif 392 set_registers(regs); 393 return regs.ip(); 394} 395 396void DebugSession::detach() 397{ 398 for (auto& breakpoint : m_breakpoints.keys()) { 399 remove_breakpoint(breakpoint); 400 } 401 for (auto& watchpoint : m_watchpoints.keys()) 402 remove_watchpoint(watchpoint); 403 continue_debuggee(); 404} 405 406Optional<DebugSession::InsertBreakpointAtSymbolResult> DebugSession::insert_breakpoint(DeprecatedString const& symbol_name) 407{ 408 Optional<InsertBreakpointAtSymbolResult> result; 409 for_each_loaded_library([this, symbol_name, &result](auto& lib) { 410 // The loader contains its own definitions for LibC symbols, so we don't want to include it in the search. 411 if (lib.name == "Loader.so") 412 return IterationDecision::Continue; 413 414 auto symbol = lib.debug_info->elf().find_demangled_function(symbol_name); 415 if (!symbol.has_value()) 416 return IterationDecision::Continue; 417 418 FlatPtr breakpoint_address = symbol->value() + lib.base_address; 419 bool rc = this->insert_breakpoint(breakpoint_address); 420 if (!rc) 421 return IterationDecision::Break; 422 423 result = InsertBreakpointAtSymbolResult { lib.name, breakpoint_address }; 424 return IterationDecision::Break; 425 }); 426 return result; 427} 428 429Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::insert_breakpoint(DeprecatedString const& filename, size_t line_number) 430{ 431 auto address_and_source_position = get_address_from_source_position(filename, line_number); 432 if (!address_and_source_position.has_value()) 433 return {}; 434 435 auto address = address_and_source_position.value().address; 436 bool rc = this->insert_breakpoint(address); 437 if (!rc) 438 return {}; 439 440 auto lib = library_at(address); 441 VERIFY(lib); 442 443 return InsertBreakpointAtSourcePositionResult { lib->name, address_and_source_position.value().file, address_and_source_position.value().line, address }; 444} 445 446void DebugSession::update_loaded_libs() 447{ 448 auto file = Core::DeprecatedFile::construct(DeprecatedString::formatted("/proc/{}/vm", m_debuggee_pid)); 449 bool rc = file->open(Core::OpenMode::ReadOnly); 450 VERIFY(rc); 451 452 auto file_contents = file->read_all(); 453 auto json = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors(); 454 455 auto const& vm_entries = json.as_array(); 456 Regex<PosixExtended> segment_name_re("(.+): "); 457 458 auto get_path_to_object = [&segment_name_re](DeprecatedString const& vm_name) -> Optional<DeprecatedString> { 459 if (vm_name == "/usr/lib/Loader.so") 460 return vm_name; 461 RegexResult result; 462 auto rc = segment_name_re.search(vm_name, result); 463 if (!rc) 464 return {}; 465 auto lib_name = result.capture_group_matches.at(0).at(0).view.string_view().to_deprecated_string(); 466 if (lib_name.starts_with('/')) 467 return lib_name; 468 return DeprecatedString::formatted("/usr/lib/{}", lib_name); 469 }; 470 471 ScopeGuard progress_guard([this]() { 472 m_on_initialization_progress(0); 473 }); 474 475 size_t vm_entry_index = 0; 476 477 vm_entries.for_each([&](auto& entry) { 478 ++vm_entry_index; 479 if (m_on_initialization_progress) 480 m_on_initialization_progress(vm_entry_index / static_cast<float>(vm_entries.size())); 481 482 // TODO: check that region is executable 483 auto vm_name = entry.as_object().get_deprecated_string("name"sv).value(); 484 485 auto object_path = get_path_to_object(vm_name); 486 if (!object_path.has_value()) 487 return IterationDecision::Continue; 488 489 DeprecatedString lib_name = object_path.value(); 490 if (Core::DeprecatedFile::looks_like_shared_library(lib_name)) 491 lib_name = LexicalPath::basename(object_path.value()); 492 493 FlatPtr base_address = entry.as_object().get_addr("address"sv).value_or(0); 494 if (auto it = m_loaded_libraries.find(lib_name); it != m_loaded_libraries.end()) { 495 // We expect the VM regions to be sorted by address. 496 VERIFY(base_address >= it->value->base_address); 497 return IterationDecision::Continue; 498 } 499 500 auto file_or_error = Core::MappedFile::map(object_path.value()); 501 if (file_or_error.is_error()) 502 return IterationDecision::Continue; 503 504 auto image = make<ELF::Image>(file_or_error.value()->bytes()); 505 auto debug_info = make<DebugInfo>(*image, m_source_root, base_address); 506 auto lib = make<LoadedLibrary>(lib_name, file_or_error.release_value(), move(image), move(debug_info), base_address); 507 m_loaded_libraries.set(lib_name, move(lib)); 508 509 return IterationDecision::Continue; 510 }); 511} 512 513void DebugSession::stop_debuggee() 514{ 515 kill(pid(), SIGSTOP); 516} 517 518}