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