1//===-- NativeProcessFreeBSD.cpp ------------------------------------------===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8 9#include "NativeProcessFreeBSD.h" 10 11// clang-format off 12#include <sys/types.h> 13#include <sys/ptrace.h> 14#include <sys/sysctl.h> 15#include <sys/user.h> 16#include <sys/wait.h> 17#include <machine/elf.h> 18// clang-format on 19 20#include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 21#include "lldb/Host/HostProcess.h" 22#include "lldb/Host/posix/ProcessLauncherPosixFork.h" 23#include "lldb/Target/Process.h" 24#include "lldb/Utility/State.h" 25#include "llvm/Support/Errno.h" 26 27using namespace lldb; 28using namespace lldb_private; 29using namespace lldb_private::process_freebsd; 30using namespace llvm; 31 32// Simple helper function to ensure flags are enabled on the given file 33// descriptor. 34static Status EnsureFDFlags(int fd, int flags) { 35 Status error; 36 37 int status = fcntl(fd, F_GETFL); 38 if (status == -1) { 39 error.SetErrorToErrno(); 40 return error; 41 } 42 43 if (fcntl(fd, F_SETFL, status | flags) == -1) { 44 error.SetErrorToErrno(); 45 return error; 46 } 47 48 return error; 49} 50 51// Public Static Methods 52 53llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 54NativeProcessFreeBSD::Manager::Launch(ProcessLaunchInfo &launch_info, 55 NativeDelegate &native_delegate) { 56 Log *log = GetLog(POSIXLog::Process); 57 58 Status status; 59 ::pid_t pid = ProcessLauncherPosixFork() 60 .LaunchProcess(launch_info, status) 61 .GetProcessId(); 62 LLDB_LOG(log, "pid = {0:x}", pid); 63 if (status.Fail()) { 64 LLDB_LOG(log, "failed to launch process: {0}", status); 65 return status.ToError(); 66 } 67 68 // Wait for the child process to trap on its call to execve. 69 int wstatus; 70 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 71 assert(wpid == pid); 72 UNUSED_IF_ASSERT_DISABLED(wpid); 73 if (!WIFSTOPPED(wstatus)) { 74 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 75 WaitStatus::Decode(wstatus)); 76 return llvm::make_error<StringError>("Could not sync with inferior process", 77 llvm::inconvertibleErrorCode()); 78 } 79 LLDB_LOG(log, "inferior started, now in stopped state"); 80 81 ProcessInstanceInfo Info; 82 if (!Host::GetProcessInfo(pid, Info)) { 83 return llvm::make_error<StringError>("Cannot get process architecture", 84 llvm::inconvertibleErrorCode()); 85 } 86 87 // Set the architecture to the exe architecture. 88 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 89 Info.GetArchitecture().GetArchitectureName()); 90 91 std::unique_ptr<NativeProcessFreeBSD> process_up(new NativeProcessFreeBSD( 92 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate, 93 Info.GetArchitecture(), m_mainloop)); 94 95 status = process_up->SetupTrace(); 96 if (status.Fail()) 97 return status.ToError(); 98 99 for (const auto &thread : process_up->m_threads) 100 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 101 process_up->SetState(StateType::eStateStopped, false); 102 103 return std::move(process_up); 104} 105 106llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 107NativeProcessFreeBSD::Manager::Attach( 108 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate) { 109 Log *log = GetLog(POSIXLog::Process); 110 LLDB_LOG(log, "pid = {0:x}", pid); 111 112 // Retrieve the architecture for the running process. 113 ProcessInstanceInfo Info; 114 if (!Host::GetProcessInfo(pid, Info)) { 115 return llvm::make_error<StringError>("Cannot get process architecture", 116 llvm::inconvertibleErrorCode()); 117 } 118 119 std::unique_ptr<NativeProcessFreeBSD> process_up(new NativeProcessFreeBSD( 120 pid, -1, native_delegate, Info.GetArchitecture(), m_mainloop)); 121 122 Status status = process_up->Attach(); 123 if (!status.Success()) 124 return status.ToError(); 125 126 return std::move(process_up); 127} 128 129NativeProcessFreeBSD::Extension 130NativeProcessFreeBSD::Manager::GetSupportedExtensions() const { 131 return 132#if defined(PT_COREDUMP) 133 Extension::savecore | 134#endif 135 Extension::multiprocess | Extension::fork | Extension::vfork | 136 Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 | 137 Extension::siginfo_read; 138} 139 140// Public Instance Methods 141 142NativeProcessFreeBSD::NativeProcessFreeBSD(::pid_t pid, int terminal_fd, 143 NativeDelegate &delegate, 144 const ArchSpec &arch, 145 MainLoop &mainloop) 146 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch), 147 m_main_loop(mainloop) { 148 if (m_terminal_fd != -1) { 149 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 150 assert(status.Success()); 151 } 152 153 Status status; 154 m_sigchld_handle = mainloop.RegisterSignal( 155 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 156 assert(m_sigchld_handle && status.Success()); 157} 158 159// Handles all waitpid events from the inferior process. 160void NativeProcessFreeBSD::MonitorCallback(lldb::pid_t pid, int signal) { 161 switch (signal) { 162 case SIGTRAP: 163 return MonitorSIGTRAP(pid); 164 case SIGSTOP: 165 return MonitorSIGSTOP(pid); 166 default: 167 return MonitorSignal(pid, signal); 168 } 169} 170 171void NativeProcessFreeBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) { 172 Log *log = GetLog(POSIXLog::Process); 173 174 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid); 175 176 /* Stop Tracking All Threads attached to Process */ 177 m_threads.clear(); 178 179 SetExitStatus(status, true); 180 181 // Notify delegate that our process has exited. 182 SetState(StateType::eStateExited, true); 183} 184 185void NativeProcessFreeBSD::MonitorSIGSTOP(lldb::pid_t pid) { 186 /* Stop all Threads attached to Process */ 187 for (const auto &thread : m_threads) { 188 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP, 189 nullptr); 190 } 191 SetState(StateType::eStateStopped, true); 192} 193 194void NativeProcessFreeBSD::MonitorSIGTRAP(lldb::pid_t pid) { 195 Log *log = GetLog(POSIXLog::Process); 196 struct ptrace_lwpinfo info; 197 198 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info)); 199 if (siginfo_err.Fail()) { 200 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err); 201 return; 202 } 203 assert(info.pl_event == PL_EVENT_SIGNAL); 204 205 LLDB_LOG(log, "got SIGTRAP, pid = {0}, lwpid = {1}, flags = {2:x}", pid, 206 info.pl_lwpid, info.pl_flags); 207 NativeThreadFreeBSD *thread = nullptr; 208 209 if (info.pl_flags & (PL_FLAG_BORN | PL_FLAG_EXITED)) { 210 if (info.pl_flags & PL_FLAG_BORN) { 211 LLDB_LOG(log, "monitoring new thread, tid = {0}", info.pl_lwpid); 212 NativeThreadFreeBSD &t = AddThread(info.pl_lwpid); 213 214 // Technically, the FreeBSD kernel copies the debug registers to new 215 // threads. However, there is a non-negligible delay between acquiring 216 // the DR values and reporting the new thread during which the user may 217 // establish a new watchpoint. In order to ensure that watchpoints 218 // established during this period are propagated to new threads, 219 // explicitly copy the DR value at the time the new thread is reported. 220 // 221 // See also: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=250954 222 223 llvm::Error error = t.CopyWatchpointsFrom( 224 static_cast<NativeThreadFreeBSD &>(*GetCurrentThread())); 225 if (error) { 226 LLDB_LOG_ERROR(log, std::move(error), 227 "failed to copy watchpoints to new thread {1}: {0}", 228 info.pl_lwpid); 229 SetState(StateType::eStateInvalid); 230 return; 231 } 232 } else /*if (info.pl_flags & PL_FLAG_EXITED)*/ { 233 LLDB_LOG(log, "thread exited, tid = {0}", info.pl_lwpid); 234 RemoveThread(info.pl_lwpid); 235 } 236 237 Status error = 238 PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0); 239 if (error.Fail()) 240 SetState(StateType::eStateInvalid); 241 return; 242 } 243 244 if (info.pl_flags & PL_FLAG_EXEC) { 245 Status error = ReinitializeThreads(); 246 if (error.Fail()) { 247 SetState(StateType::eStateInvalid); 248 return; 249 } 250 251 // Let our delegate know we have just exec'd. 252 NotifyDidExec(); 253 254 for (const auto &thread : m_threads) 255 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedByExec(); 256 SetCurrentThreadID(m_threads.front()->GetID()); 257 SetState(StateType::eStateStopped, true); 258 return; 259 } 260 261 if (info.pl_lwpid > 0) { 262 for (const auto &t : m_threads) { 263 if (t->GetID() == static_cast<lldb::tid_t>(info.pl_lwpid)) 264 thread = static_cast<NativeThreadFreeBSD *>(t.get()); 265 static_cast<NativeThreadFreeBSD *>(t.get())->SetStoppedWithNoReason(); 266 } 267 if (!thread) 268 LLDB_LOG(log, "thread not found in m_threads, pid = {0}, LWP = {1}", pid, 269 info.pl_lwpid); 270 } 271 272 if (info.pl_flags & PL_FLAG_FORKED) { 273 assert(thread); 274 MonitorClone(info.pl_child_pid, info.pl_flags & PL_FLAG_VFORKED, *thread); 275 return; 276 } 277 278 if (info.pl_flags & PL_FLAG_VFORK_DONE) { 279 assert(thread); 280 if ((m_enabled_extensions & Extension::vfork) == Extension::vfork) { 281 thread->SetStoppedByVForkDone(); 282 SetState(StateType::eStateStopped, true); 283 } else { 284 Status error = 285 PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0); 286 if (error.Fail()) 287 SetState(StateType::eStateInvalid); 288 } 289 return; 290 } 291 292 if (info.pl_flags & PL_FLAG_SI) { 293 assert(info.pl_siginfo.si_signo == SIGTRAP); 294 LLDB_LOG(log, "SIGTRAP siginfo: si_code = {0}, pid = {1}", 295 info.pl_siginfo.si_code, info.pl_siginfo.si_pid); 296 297 switch (info.pl_siginfo.si_code) { 298 case TRAP_BRKPT: 299 LLDB_LOG(log, "SIGTRAP/TRAP_BRKPT: si_addr: {0}", 300 info.pl_siginfo.si_addr); 301 302 if (thread) { 303 auto thread_info = 304 m_threads_stepping_with_breakpoint.find(thread->GetID()); 305 if (thread_info != m_threads_stepping_with_breakpoint.end()) { 306 thread->SetStoppedByTrace(); 307 Status brkpt_error = RemoveBreakpoint(thread_info->second); 308 if (brkpt_error.Fail()) 309 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 310 thread_info->first, brkpt_error); 311 m_threads_stepping_with_breakpoint.erase(thread_info); 312 } else 313 thread->SetStoppedByBreakpoint(); 314 FixupBreakpointPCAsNeeded(*thread); 315 SetCurrentThreadID(thread->GetID()); 316 } 317 SetState(StateType::eStateStopped, true); 318 return; 319 case TRAP_TRACE: 320 LLDB_LOG(log, "SIGTRAP/TRAP_TRACE: si_addr: {0}", 321 info.pl_siginfo.si_addr); 322 323 if (thread) { 324 auto ®ctx = static_cast<NativeRegisterContextFreeBSD &>( 325 thread->GetRegisterContext()); 326 uint32_t wp_index = LLDB_INVALID_INDEX32; 327 Status error = regctx.GetWatchpointHitIndex( 328 wp_index, reinterpret_cast<uintptr_t>(info.pl_siginfo.si_addr)); 329 if (error.Fail()) 330 LLDB_LOG(log, 331 "received error while checking for watchpoint hits, pid = " 332 "{0}, LWP = {1}, error = {2}", 333 pid, info.pl_lwpid, error); 334 if (wp_index != LLDB_INVALID_INDEX32) { 335 regctx.ClearWatchpointHit(wp_index); 336 thread->SetStoppedByWatchpoint(wp_index); 337 SetCurrentThreadID(thread->GetID()); 338 SetState(StateType::eStateStopped, true); 339 break; 340 } 341 342 thread->SetStoppedByTrace(); 343 SetCurrentThreadID(thread->GetID()); 344 } 345 346 SetState(StateType::eStateStopped, true); 347 return; 348 } 349 } 350 351 // Either user-generated SIGTRAP or an unknown event that would 352 // otherwise leave the debugger hanging. 353 LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler"); 354 MonitorSignal(pid, SIGTRAP); 355} 356 357void NativeProcessFreeBSD::MonitorSignal(lldb::pid_t pid, int signal) { 358 Log *log = GetLog(POSIXLog::Process); 359 struct ptrace_lwpinfo info; 360 361 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info)); 362 if (siginfo_err.Fail()) { 363 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err); 364 return; 365 } 366 assert(info.pl_event == PL_EVENT_SIGNAL); 367 // TODO: do we need to handle !PL_FLAG_SI? 368 assert(info.pl_flags & PL_FLAG_SI); 369 assert(info.pl_siginfo.si_signo == signal); 370 371 for (const auto &abs_thread : m_threads) { 372 NativeThreadFreeBSD &thread = 373 static_cast<NativeThreadFreeBSD &>(*abs_thread); 374 assert(info.pl_lwpid >= 0); 375 if (info.pl_lwpid == 0 || 376 static_cast<lldb::tid_t>(info.pl_lwpid) == thread.GetID()) { 377 thread.SetStoppedBySignal(info.pl_siginfo.si_signo, &info.pl_siginfo); 378 SetCurrentThreadID(thread.GetID()); 379 } else 380 thread.SetStoppedWithNoReason(); 381 } 382 SetState(StateType::eStateStopped, true); 383} 384 385Status NativeProcessFreeBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 386 int data, int *result) { 387 Log *log = GetLog(POSIXLog::Ptrace); 388 Status error; 389 int ret; 390 391 errno = 0; 392 ret = 393 ptrace(req, static_cast<::pid_t>(pid), static_cast<caddr_t>(addr), data); 394 395 if (ret == -1) 396 error.SetErrorToErrno(); 397 398 if (result) 399 *result = ret; 400 401 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret); 402 403 if (error.Fail()) 404 LLDB_LOG(log, "ptrace() failed: {0}", error); 405 406 return error; 407} 408 409llvm::Expected<llvm::ArrayRef<uint8_t>> 410NativeProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 411 static const uint8_t g_arm_opcode[] = {0xfe, 0xde, 0xff, 0xe7}; 412 static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 413 414 switch (GetArchitecture().GetMachine()) { 415 case llvm::Triple::arm: 416 switch (size_hint) { 417 case 2: 418 return llvm::ArrayRef(g_thumb_opcode); 419 case 4: 420 return llvm::ArrayRef(g_arm_opcode); 421 default: 422 return llvm::createStringError(llvm::inconvertibleErrorCode(), 423 "Unrecognised trap opcode size hint!"); 424 } 425 default: 426 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 427 } 428} 429 430Status NativeProcessFreeBSD::Resume(const ResumeActionList &resume_actions) { 431 Log *log = GetLog(POSIXLog::Process); 432 LLDB_LOG(log, "pid {0}", GetID()); 433 434 Status ret; 435 436 int signal = 0; 437 for (const auto &abs_thread : m_threads) { 438 assert(abs_thread && "thread list should not contain NULL threads"); 439 NativeThreadFreeBSD &thread = 440 static_cast<NativeThreadFreeBSD &>(*abs_thread); 441 442 const ResumeAction *action = 443 resume_actions.GetActionForThread(thread.GetID(), true); 444 // we need to explicit issue suspend requests, so it is simpler to map it 445 // into proper action 446 ResumeAction suspend_action{thread.GetID(), eStateSuspended, 447 LLDB_INVALID_SIGNAL_NUMBER}; 448 449 if (action == nullptr) { 450 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 451 thread.GetID()); 452 action = &suspend_action; 453 } 454 455 LLDB_LOG( 456 log, 457 "processing resume action state {0} signal {1} for pid {2} tid {3}", 458 action->state, action->signal, GetID(), thread.GetID()); 459 460 switch (action->state) { 461 case eStateRunning: 462 ret = thread.Resume(); 463 break; 464 case eStateStepping: 465 ret = thread.SingleStep(); 466 break; 467 case eStateSuspended: 468 case eStateStopped: 469 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) 470 return Status("Passing signal to suspended thread unsupported"); 471 472 ret = thread.Suspend(); 473 break; 474 475 default: 476 return Status( 477 "NativeProcessFreeBSD::%s (): unexpected state %s specified " 478 "for pid %" PRIu64 ", tid %" PRIu64, 479 __FUNCTION__, StateAsCString(action->state), GetID(), thread.GetID()); 480 } 481 482 if (!ret.Success()) 483 return ret; 484 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) 485 signal = action->signal; 486 } 487 488 ret = 489 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal); 490 if (ret.Success()) 491 SetState(eStateRunning, true); 492 return ret; 493} 494 495Status NativeProcessFreeBSD::Halt() { 496 Status error; 497 498 // Do not try to stop a process that's already stopped, this may cause 499 // the SIGSTOP to get queued and stop the process again once resumed. 500 if (StateIsStoppedState(m_state, false)) 501 return error; 502 if (kill(GetID(), SIGSTOP) != 0) 503 error.SetErrorToErrno(); 504 return error; 505} 506 507Status NativeProcessFreeBSD::Detach() { 508 Status error; 509 510 // Stop monitoring the inferior. 511 m_sigchld_handle.reset(); 512 513 // Tell ptrace to detach from the process. 514 if (GetID() == LLDB_INVALID_PROCESS_ID) 515 return error; 516 517 return PtraceWrapper(PT_DETACH, GetID()); 518} 519 520Status NativeProcessFreeBSD::Signal(int signo) { 521 Status error; 522 523 if (kill(GetID(), signo)) 524 error.SetErrorToErrno(); 525 526 return error; 527} 528 529Status NativeProcessFreeBSD::Interrupt() { return Halt(); } 530 531Status NativeProcessFreeBSD::Kill() { 532 Log *log = GetLog(POSIXLog::Process); 533 LLDB_LOG(log, "pid {0}", GetID()); 534 535 Status error; 536 537 switch (m_state) { 538 case StateType::eStateInvalid: 539 case StateType::eStateExited: 540 case StateType::eStateCrashed: 541 case StateType::eStateDetached: 542 case StateType::eStateUnloaded: 543 // Nothing to do - the process is already dead. 544 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 545 StateAsCString(m_state)); 546 return error; 547 548 case StateType::eStateConnected: 549 case StateType::eStateAttaching: 550 case StateType::eStateLaunching: 551 case StateType::eStateStopped: 552 case StateType::eStateRunning: 553 case StateType::eStateStepping: 554 case StateType::eStateSuspended: 555 // We can try to kill a process in these states. 556 break; 557 } 558 559 return PtraceWrapper(PT_KILL, m_pid); 560} 561 562Status NativeProcessFreeBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, 563 MemoryRegionInfo &range_info) { 564 565 if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 566 // We're done. 567 return Status("unsupported"); 568 } 569 570 Status error = PopulateMemoryRegionCache(); 571 if (error.Fail()) { 572 return error; 573 } 574 575 lldb::addr_t prev_base_address = 0; 576 // FIXME start by finding the last region that is <= target address using 577 // binary search. Data is sorted. 578 // There can be a ton of regions on pthreads apps with lots of threads. 579 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 580 ++it) { 581 MemoryRegionInfo &proc_entry_info = it->first; 582 // Sanity check assumption that memory map entries are ascending. 583 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 584 "descending memory map entries detected, unexpected"); 585 prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 586 UNUSED_IF_ASSERT_DISABLED(prev_base_address); 587 // If the target address comes before this entry, indicate distance to next 588 // region. 589 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 590 range_info.GetRange().SetRangeBase(load_addr); 591 range_info.GetRange().SetByteSize( 592 proc_entry_info.GetRange().GetRangeBase() - load_addr); 593 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 594 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 595 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 596 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 597 return error; 598 } else if (proc_entry_info.GetRange().Contains(load_addr)) { 599 // The target address is within the memory region we're processing here. 600 range_info = proc_entry_info; 601 return error; 602 } 603 // The target memory address comes somewhere after the region we just 604 // parsed. 605 } 606 // If we made it here, we didn't find an entry that contained the given 607 // address. Return the load_addr as start and the amount of bytes betwwen 608 // load address and the end of the memory as size. 609 range_info.GetRange().SetRangeBase(load_addr); 610 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 611 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 612 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 613 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 614 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 615 return error; 616} 617 618Status NativeProcessFreeBSD::PopulateMemoryRegionCache() { 619 Log *log = GetLog(POSIXLog::Process); 620 // If our cache is empty, pull the latest. There should always be at least 621 // one memory region if memory region handling is supported. 622 if (!m_mem_region_cache.empty()) { 623 LLDB_LOG(log, "reusing {0} cached memory region entries", 624 m_mem_region_cache.size()); 625 return Status(); 626 } 627 628 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, static_cast<int>(m_pid)}; 629 int ret; 630 size_t len; 631 632 ret = ::sysctl(mib, 4, nullptr, &len, nullptr, 0); 633 if (ret != 0) { 634 m_supports_mem_region = LazyBool::eLazyBoolNo; 635 return Status("sysctl() for KERN_PROC_VMMAP failed"); 636 } 637 638 std::unique_ptr<WritableMemoryBuffer> buf = 639 llvm::WritableMemoryBuffer::getNewMemBuffer(len); 640 ret = ::sysctl(mib, 4, buf->getBufferStart(), &len, nullptr, 0); 641 if (ret != 0) { 642 m_supports_mem_region = LazyBool::eLazyBoolNo; 643 return Status("sysctl() for KERN_PROC_VMMAP failed"); 644 } 645 646 char *bp = buf->getBufferStart(); 647 char *end = bp + len; 648 while (bp < end) { 649 auto *kv = reinterpret_cast<struct kinfo_vmentry *>(bp); 650 if (kv->kve_structsize == 0) 651 break; 652 bp += kv->kve_structsize; 653 654 MemoryRegionInfo info; 655 info.Clear(); 656 info.GetRange().SetRangeBase(kv->kve_start); 657 info.GetRange().SetRangeEnd(kv->kve_end); 658 info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 659 660 if (kv->kve_protection & VM_PROT_READ) 661 info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 662 else 663 info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 664 665 if (kv->kve_protection & VM_PROT_WRITE) 666 info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 667 else 668 info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 669 670 if (kv->kve_protection & VM_PROT_EXECUTE) 671 info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 672 else 673 info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 674 675 if (kv->kve_path[0]) 676 info.SetName(kv->kve_path); 677 678 m_mem_region_cache.emplace_back(info, 679 FileSpec(info.GetName().GetCString())); 680 } 681 682 if (m_mem_region_cache.empty()) { 683 // No entries after attempting to read them. This shouldn't happen. Assume 684 // we don't support map entries. 685 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support " 686 "for memory region metadata retrieval"); 687 m_supports_mem_region = LazyBool::eLazyBoolNo; 688 return Status("not supported"); 689 } 690 LLDB_LOG(log, "read {0} memory region entries from process {1}", 691 m_mem_region_cache.size(), GetID()); 692 // We support memory retrieval, remember that. 693 m_supports_mem_region = LazyBool::eLazyBoolYes; 694 695 return Status(); 696} 697 698size_t NativeProcessFreeBSD::UpdateThreads() { return m_threads.size(); } 699 700Status NativeProcessFreeBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, 701 bool hardware) { 702 if (hardware) 703 return SetHardwareBreakpoint(addr, size); 704 return SetSoftwareBreakpoint(addr, size); 705} 706 707Status NativeProcessFreeBSD::GetLoadedModuleFileSpec(const char *module_path, 708 FileSpec &file_spec) { 709 Status error = PopulateMemoryRegionCache(); 710 if (error.Fail()) 711 return error; 712 713 FileSpec module_file_spec(module_path); 714 FileSystem::Instance().Resolve(module_file_spec); 715 716 file_spec.Clear(); 717 for (const auto &it : m_mem_region_cache) { 718 if (it.second.GetFilename() == module_file_spec.GetFilename()) { 719 file_spec = it.second; 720 return Status(); 721 } 722 } 723 return Status("Module file (%s) not found in process' memory map!", 724 module_file_spec.GetFilename().AsCString()); 725} 726 727Status 728NativeProcessFreeBSD::GetFileLoadAddress(const llvm::StringRef &file_name, 729 lldb::addr_t &load_addr) { 730 load_addr = LLDB_INVALID_ADDRESS; 731 Status error = PopulateMemoryRegionCache(); 732 if (error.Fail()) 733 return error; 734 735 FileSpec file(file_name); 736 for (const auto &it : m_mem_region_cache) { 737 if (it.second == file) { 738 load_addr = it.first.GetRange().GetRangeBase(); 739 return Status(); 740 } 741 } 742 return Status("No load address found for file %s.", file_name.str().c_str()); 743} 744 745void NativeProcessFreeBSD::SigchldHandler() { 746 Log *log = GetLog(POSIXLog::Process); 747 int status; 748 ::pid_t wait_pid = 749 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WNOHANG); 750 751 if (wait_pid == 0) 752 return; 753 754 if (wait_pid == -1) { 755 Status error(errno, eErrorTypePOSIX); 756 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error); 757 return; 758 } 759 760 WaitStatus wait_status = WaitStatus::Decode(status); 761 bool exited = wait_status.type == WaitStatus::Exit || 762 (wait_status.type == WaitStatus::Signal && 763 wait_pid == static_cast<::pid_t>(GetID())); 764 765 LLDB_LOG(log, 766 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}", 767 GetID(), wait_pid, status, exited); 768 769 if (exited) 770 MonitorExited(wait_pid, wait_status); 771 else { 772 assert(wait_status.type == WaitStatus::Stop); 773 MonitorCallback(wait_pid, wait_status.status); 774 } 775} 776 777bool NativeProcessFreeBSD::HasThreadNoLock(lldb::tid_t thread_id) { 778 for (const auto &thread : m_threads) { 779 assert(thread && "thread list should not contain NULL threads"); 780 if (thread->GetID() == thread_id) { 781 // We have this thread. 782 return true; 783 } 784 } 785 786 // We don't have this thread. 787 return false; 788} 789 790NativeThreadFreeBSD &NativeProcessFreeBSD::AddThread(lldb::tid_t thread_id) { 791 Log *log = GetLog(POSIXLog::Thread); 792 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 793 794 assert(thread_id > 0); 795 assert(!HasThreadNoLock(thread_id) && 796 "attempted to add a thread by id that already exists"); 797 798 // If this is the first thread, save it as the current thread 799 if (m_threads.empty()) 800 SetCurrentThreadID(thread_id); 801 802 m_threads.push_back(std::make_unique<NativeThreadFreeBSD>(*this, thread_id)); 803 return static_cast<NativeThreadFreeBSD &>(*m_threads.back()); 804} 805 806void NativeProcessFreeBSD::RemoveThread(lldb::tid_t thread_id) { 807 Log *log = GetLog(POSIXLog::Thread); 808 LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id); 809 810 assert(thread_id > 0); 811 assert(HasThreadNoLock(thread_id) && 812 "attempted to remove a thread that does not exist"); 813 814 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 815 if ((*it)->GetID() == thread_id) { 816 m_threads.erase(it); 817 break; 818 } 819 } 820 821 if (GetCurrentThreadID() == thread_id) 822 SetCurrentThreadID(m_threads.front()->GetID()); 823} 824 825Status NativeProcessFreeBSD::Attach() { 826 // Attach to the requested process. 827 // An attach will cause the thread to stop with a SIGSTOP. 828 Status status = PtraceWrapper(PT_ATTACH, m_pid); 829 if (status.Fail()) 830 return status; 831 832 int wstatus; 833 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this 834 // point we should have a thread stopped if waitpid succeeds. 835 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr, 0)) < 836 0) 837 return Status(errno, eErrorTypePOSIX); 838 839 // Initialize threads and tracing status 840 // NB: this needs to be called before we set thread state 841 status = SetupTrace(); 842 if (status.Fail()) 843 return status; 844 845 for (const auto &thread : m_threads) 846 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 847 848 // Let our process instance know the thread has stopped. 849 SetCurrentThreadID(m_threads.front()->GetID()); 850 SetState(StateType::eStateStopped, false); 851 return Status(); 852} 853 854Status NativeProcessFreeBSD::ReadMemory(lldb::addr_t addr, void *buf, 855 size_t size, size_t &bytes_read) { 856 unsigned char *dst = static_cast<unsigned char *>(buf); 857 struct ptrace_io_desc io; 858 859 Log *log = GetLog(POSIXLog::Memory); 860 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 861 862 bytes_read = 0; 863 io.piod_op = PIOD_READ_D; 864 io.piod_len = size; 865 866 do { 867 io.piod_offs = (void *)(addr + bytes_read); 868 io.piod_addr = dst + bytes_read; 869 870 Status error = NativeProcessFreeBSD::PtraceWrapper(PT_IO, GetID(), &io); 871 if (error.Fail() || io.piod_len == 0) 872 return error; 873 874 bytes_read += io.piod_len; 875 io.piod_len = size - bytes_read; 876 } while (bytes_read < size); 877 878 return Status(); 879} 880 881Status NativeProcessFreeBSD::WriteMemory(lldb::addr_t addr, const void *buf, 882 size_t size, size_t &bytes_written) { 883 const unsigned char *src = static_cast<const unsigned char *>(buf); 884 Status error; 885 struct ptrace_io_desc io; 886 887 Log *log = GetLog(POSIXLog::Memory); 888 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 889 890 bytes_written = 0; 891 io.piod_op = PIOD_WRITE_D; 892 io.piod_len = size; 893 894 do { 895 io.piod_addr = 896 const_cast<void *>(static_cast<const void *>(src + bytes_written)); 897 io.piod_offs = (void *)(addr + bytes_written); 898 899 Status error = NativeProcessFreeBSD::PtraceWrapper(PT_IO, GetID(), &io); 900 if (error.Fail() || io.piod_len == 0) 901 return error; 902 903 bytes_written += io.piod_len; 904 io.piod_len = size - bytes_written; 905 } while (bytes_written < size); 906 907 return error; 908} 909 910llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 911NativeProcessFreeBSD::GetAuxvData() const { 912 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, static_cast<int>(GetID())}; 913 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo); 914 std::unique_ptr<WritableMemoryBuffer> buf = 915 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size); 916 917 if (::sysctl(mib, 4, buf->getBufferStart(), &auxv_size, nullptr, 0) != 0) 918 return std::error_code(errno, std::generic_category()); 919 920 return buf; 921} 922 923Status NativeProcessFreeBSD::SetupTrace() { 924 // Enable event reporting 925 int events; 926 Status status = 927 PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events)); 928 if (status.Fail()) 929 return status; 930 events |= PTRACE_LWP | PTRACE_FORK | PTRACE_VFORK; 931 status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events)); 932 if (status.Fail()) 933 return status; 934 935 return ReinitializeThreads(); 936} 937 938Status NativeProcessFreeBSD::ReinitializeThreads() { 939 // Clear old threads 940 m_threads.clear(); 941 942 int num_lwps; 943 Status error = PtraceWrapper(PT_GETNUMLWPS, GetID(), nullptr, 0, &num_lwps); 944 if (error.Fail()) 945 return error; 946 947 std::vector<lwpid_t> lwp_ids; 948 lwp_ids.resize(num_lwps); 949 error = PtraceWrapper(PT_GETLWPLIST, GetID(), lwp_ids.data(), 950 lwp_ids.size() * sizeof(lwpid_t), &num_lwps); 951 if (error.Fail()) 952 return error; 953 954 // Reinitialize from scratch threads and register them in process 955 for (lwpid_t lwp : lwp_ids) 956 AddThread(lwp); 957 958 return error; 959} 960 961bool NativeProcessFreeBSD::SupportHardwareSingleStepping() const { 962 return !m_arch.IsMIPS(); 963} 964 965void NativeProcessFreeBSD::MonitorClone(::pid_t child_pid, bool is_vfork, 966 NativeThreadFreeBSD &parent_thread) { 967 Log *log = GetLog(POSIXLog::Process); 968 LLDB_LOG(log, "fork, child_pid={0}", child_pid); 969 970 int status; 971 ::pid_t wait_pid = 972 llvm::sys::RetryAfterSignal(-1, ::waitpid, child_pid, &status, 0); 973 if (wait_pid != child_pid) { 974 LLDB_LOG(log, 975 "waiting for pid {0} failed. Assuming the pid has " 976 "disappeared in the meantime", 977 child_pid); 978 return; 979 } 980 if (WIFEXITED(status)) { 981 LLDB_LOG(log, 982 "waiting for pid {0} returned an 'exited' event. Not " 983 "tracking it.", 984 child_pid); 985 return; 986 } 987 988 struct ptrace_lwpinfo info; 989 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, child_pid, &info, sizeof(info)); 990 if (siginfo_err.Fail()) { 991 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err); 992 return; 993 } 994 assert(info.pl_event == PL_EVENT_SIGNAL); 995 lldb::tid_t child_tid = info.pl_lwpid; 996 997 std::unique_ptr<NativeProcessFreeBSD> child_process{ 998 new NativeProcessFreeBSD(static_cast<::pid_t>(child_pid), m_terminal_fd, 999 m_delegate, m_arch, m_main_loop)}; 1000 if (!is_vfork) 1001 child_process->m_software_breakpoints = m_software_breakpoints; 1002 1003 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork; 1004 if ((m_enabled_extensions & expected_ext) == expected_ext) { 1005 child_process->SetupTrace(); 1006 for (const auto &thread : child_process->m_threads) 1007 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 1008 child_process->SetState(StateType::eStateStopped, false); 1009 1010 m_delegate.NewSubprocess(this, std::move(child_process)); 1011 if (is_vfork) 1012 parent_thread.SetStoppedByVFork(child_pid, child_tid); 1013 else 1014 parent_thread.SetStoppedByFork(child_pid, child_tid); 1015 SetState(StateType::eStateStopped, true); 1016 } else { 1017 child_process->Detach(); 1018 Status pt_error = 1019 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 0); 1020 if (pt_error.Fail()) { 1021 LLDB_LOG_ERROR(log, pt_error.ToError(), 1022 "unable to resume parent process {1}: {0}", GetID()); 1023 SetState(StateType::eStateInvalid); 1024 } 1025 } 1026} 1027 1028llvm::Expected<std::string> 1029NativeProcessFreeBSD::SaveCore(llvm::StringRef path_hint) { 1030#if defined(PT_COREDUMP) 1031 using namespace llvm::sys::fs; 1032 1033 llvm::SmallString<128> path{path_hint}; 1034 Status error; 1035 struct ptrace_coredump pc = {}; 1036 1037 // Try with the suggested path first. If there is no suggested path or it 1038 // failed to open, use a temporary file. 1039 if (path.empty() || 1040 openFile(path, pc.pc_fd, CD_CreateNew, FA_Write, OF_None)) { 1041 if (std::error_code errc = 1042 createTemporaryFile("lldb", "core", pc.pc_fd, path)) 1043 return llvm::createStringError(errc, "Unable to create a temporary file"); 1044 } 1045 error = PtraceWrapper(PT_COREDUMP, GetID(), &pc, sizeof(pc)); 1046 1047 std::error_code close_err = closeFile(pc.pc_fd); 1048 if (error.Fail()) 1049 return error.ToError(); 1050 if (close_err) 1051 return llvm::createStringError( 1052 close_err, "Unable to close the core dump after writing"); 1053 return path.str().str(); 1054#else // !defined(PT_COREDUMP) 1055 return llvm::createStringError( 1056 llvm::inconvertibleErrorCode(), 1057 "PT_COREDUMP not supported in the FreeBSD version used to build LLDB"); 1058#endif 1059} 1060