1 //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===// 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 "NativeProcessNetBSD.h" 10 11 12 13 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 14 #include "lldb/Host/HostProcess.h" 15 #include "lldb/Host/common/NativeRegisterContext.h" 16 #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 17 #include "lldb/Target/Process.h" 18 #include "lldb/Utility/State.h" 19 #include "llvm/Support/Errno.h" 20 21 // System includes - They have to be included after framework includes because 22 // they define some macros which collide with variable names in other modules 23 // clang-format off 24 #include <sys/types.h> 25 #include <sys/ptrace.h> 26 #include <sys/sysctl.h> 27 #include <sys/wait.h> 28 #include <uvm/uvm_prot.h> 29 #include <elf.h> 30 #include <util.h> 31 // clang-format on 32 33 using namespace lldb; 34 using namespace lldb_private; 35 using namespace lldb_private::process_netbsd; 36 using namespace llvm; 37 38 // Simple helper function to ensure flags are enabled on the given file 39 // descriptor. 40 static Status EnsureFDFlags(int fd, int flags) { 41 Status error; 42 43 int status = fcntl(fd, F_GETFL); 44 if (status == -1) { 45 error.SetErrorToErrno(); 46 return error; 47 } 48 49 if (fcntl(fd, F_SETFL, status | flags) == -1) { 50 error.SetErrorToErrno(); 51 return error; 52 } 53 54 return error; 55 } 56 57 // ----------------------------------------------------------------------------- 58 // Public Static Methods 59 // ----------------------------------------------------------------------------- 60 61 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 62 NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info, 63 NativeDelegate &native_delegate, 64 MainLoop &mainloop) const { 65 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 66 67 Status status; 68 ::pid_t pid = ProcessLauncherPosixFork() 69 .LaunchProcess(launch_info, status) 70 .GetProcessId(); 71 LLDB_LOG(log, "pid = {0:x}", pid); 72 if (status.Fail()) { 73 LLDB_LOG(log, "failed to launch process: {0}", status); 74 return status.ToError(); 75 } 76 77 // Wait for the child process to trap on its call to execve. 78 int wstatus; 79 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 80 assert(wpid == pid); 81 (void)wpid; 82 if (!WIFSTOPPED(wstatus)) { 83 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 84 WaitStatus::Decode(wstatus)); 85 return llvm::make_error<StringError>("Could not sync with inferior process", 86 llvm::inconvertibleErrorCode()); 87 } 88 LLDB_LOG(log, "inferior started, now in stopped state"); 89 90 ProcessInstanceInfo Info; 91 if (!Host::GetProcessInfo(pid, Info)) { 92 return llvm::make_error<StringError>("Cannot get process architecture", 93 llvm::inconvertibleErrorCode()); 94 } 95 96 // Set the architecture to the exe architecture. 97 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 98 Info.GetArchitecture().GetArchitectureName()); 99 100 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD( 101 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate, 102 Info.GetArchitecture(), mainloop)); 103 104 status = process_up->ReinitializeThreads(); 105 if (status.Fail()) 106 return status.ToError(); 107 108 for (const auto &thread : process_up->m_threads) 109 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 110 process_up->SetState(StateType::eStateStopped, false); 111 112 return std::move(process_up); 113 } 114 115 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 116 NativeProcessNetBSD::Factory::Attach( 117 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 118 MainLoop &mainloop) const { 119 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 120 LLDB_LOG(log, "pid = {0:x}", pid); 121 122 // Retrieve the architecture for the running process. 123 ProcessInstanceInfo Info; 124 if (!Host::GetProcessInfo(pid, Info)) { 125 return llvm::make_error<StringError>("Cannot get process architecture", 126 llvm::inconvertibleErrorCode()); 127 } 128 129 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD( 130 pid, -1, native_delegate, Info.GetArchitecture(), mainloop)); 131 132 Status status = process_up->Attach(); 133 if (!status.Success()) 134 return status.ToError(); 135 136 return std::move(process_up); 137 } 138 139 // ----------------------------------------------------------------------------- 140 // Public Instance Methods 141 // ----------------------------------------------------------------------------- 142 143 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd, 144 NativeDelegate &delegate, 145 const ArchSpec &arch, 146 MainLoop &mainloop) 147 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { 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. 160 void NativeProcessNetBSD::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 171 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) { 172 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_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 185 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) { 186 ptrace_siginfo_t info; 187 188 const auto siginfo_err = 189 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 190 191 // Get details on the signal raised. 192 if (siginfo_err.Success()) { 193 // Handle SIGSTOP from LLGS (LLDB GDB Server) 194 if (info.psi_siginfo.si_code == SI_USER && 195 info.psi_siginfo.si_pid == ::getpid()) { 196 /* Stop Tracking all Threads attached to Process */ 197 for (const auto &thread : m_threads) { 198 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal( 199 SIGSTOP, &info.psi_siginfo); 200 } 201 } 202 } 203 } 204 205 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) { 206 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 207 ptrace_siginfo_t info; 208 209 const auto siginfo_err = 210 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 211 212 // Get details on the signal raised. 213 if (siginfo_err.Fail()) { 214 return; 215 } 216 217 switch (info.psi_siginfo.si_code) { 218 case TRAP_BRKPT: 219 for (const auto &thread : m_threads) { 220 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint(); 221 FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread)); 222 } 223 SetState(StateType::eStateStopped, true); 224 break; 225 case TRAP_TRACE: 226 for (const auto &thread : m_threads) 227 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace(); 228 SetState(StateType::eStateStopped, true); 229 break; 230 case TRAP_EXEC: { 231 Status error = ReinitializeThreads(); 232 if (error.Fail()) { 233 SetState(StateType::eStateInvalid); 234 return; 235 } 236 237 // Let our delegate know we have just exec'd. 238 NotifyDidExec(); 239 240 for (const auto &thread : m_threads) 241 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec(); 242 SetState(StateType::eStateStopped, true); 243 } break; 244 case TRAP_DBREG: { 245 // If a watchpoint was hit, report it 246 uint32_t wp_index; 247 Status error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid]) 248 .GetRegisterContext() 249 .GetWatchpointHitIndex( 250 wp_index, (uintptr_t)info.psi_siginfo.si_addr); 251 if (error.Fail()) 252 LLDB_LOG(log, 253 "received error while checking for watchpoint hits, pid = " 254 "{0}, LWP = {1}, error = {2}", 255 GetID(), info.psi_lwpid, error); 256 if (wp_index != LLDB_INVALID_INDEX32) { 257 for (const auto &thread : m_threads) 258 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint( 259 wp_index); 260 SetState(StateType::eStateStopped, true); 261 break; 262 } 263 264 // If a breakpoint was hit, report it 265 uint32_t bp_index; 266 error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid]) 267 .GetRegisterContext() 268 .GetHardwareBreakHitIndex(bp_index, 269 (uintptr_t)info.psi_siginfo.si_addr); 270 if (error.Fail()) 271 LLDB_LOG(log, 272 "received error while checking for hardware " 273 "breakpoint hits, pid = {0}, LWP = {1}, error = {2}", 274 GetID(), info.psi_lwpid, error); 275 if (bp_index != LLDB_INVALID_INDEX32) { 276 for (const auto &thread : m_threads) 277 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint(); 278 SetState(StateType::eStateStopped, true); 279 break; 280 } 281 } break; 282 } 283 } 284 285 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) { 286 ptrace_siginfo_t info; 287 const auto siginfo_err = 288 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 289 290 for (const auto &thread : m_threads) { 291 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal( 292 info.psi_siginfo.si_signo, &info.psi_siginfo); 293 } 294 SetState(StateType::eStateStopped, true); 295 } 296 297 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 298 int data, int *result) { 299 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 300 Status error; 301 int ret; 302 303 errno = 0; 304 ret = ptrace(req, static_cast<::pid_t>(pid), addr, data); 305 306 if (ret == -1) 307 error.SetErrorToErrno(); 308 309 if (result) 310 *result = ret; 311 312 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret); 313 314 if (error.Fail()) 315 LLDB_LOG(log, "ptrace() failed: {0}", error); 316 317 return error; 318 } 319 320 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { 321 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 322 LLDB_LOG(log, "pid {0}", GetID()); 323 324 const auto &thread = m_threads[0]; 325 const ResumeAction *const action = 326 resume_actions.GetActionForThread(thread->GetID(), true); 327 328 if (action == nullptr) { 329 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 330 thread->GetID()); 331 return Status(); 332 } 333 334 Status error; 335 336 switch (action->state) { 337 case eStateRunning: { 338 // Run the thread, possibly feeding it the signal. 339 error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1, 340 action->signal); 341 if (!error.Success()) 342 return error; 343 for (const auto &thread : m_threads) 344 static_cast<NativeThreadNetBSD &>(*thread).SetRunning(); 345 SetState(eStateRunning, true); 346 break; 347 } 348 case eStateStepping: 349 // Run the thread, possibly feeding it the signal. 350 error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1, 351 action->signal); 352 if (!error.Success()) 353 return error; 354 for (const auto &thread : m_threads) 355 static_cast<NativeThreadNetBSD &>(*thread).SetStepping(); 356 SetState(eStateStepping, true); 357 break; 358 359 case eStateSuspended: 360 case eStateStopped: 361 llvm_unreachable("Unexpected state"); 362 363 default: 364 return Status("NativeProcessNetBSD::%s (): unexpected state %s specified " 365 "for pid %" PRIu64 ", tid %" PRIu64, 366 __FUNCTION__, StateAsCString(action->state), GetID(), 367 thread->GetID()); 368 } 369 370 return Status(); 371 } 372 373 Status NativeProcessNetBSD::Halt() { 374 Status error; 375 376 if (kill(GetID(), SIGSTOP) != 0) 377 error.SetErrorToErrno(); 378 379 return error; 380 } 381 382 Status NativeProcessNetBSD::Detach() { 383 Status error; 384 385 // Stop monitoring the inferior. 386 m_sigchld_handle.reset(); 387 388 // Tell ptrace to detach from the process. 389 if (GetID() == LLDB_INVALID_PROCESS_ID) 390 return error; 391 392 return PtraceWrapper(PT_DETACH, GetID()); 393 } 394 395 Status NativeProcessNetBSD::Signal(int signo) { 396 Status error; 397 398 if (kill(GetID(), signo)) 399 error.SetErrorToErrno(); 400 401 return error; 402 } 403 404 Status NativeProcessNetBSD::Kill() { 405 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 406 LLDB_LOG(log, "pid {0}", GetID()); 407 408 Status error; 409 410 switch (m_state) { 411 case StateType::eStateInvalid: 412 case StateType::eStateExited: 413 case StateType::eStateCrashed: 414 case StateType::eStateDetached: 415 case StateType::eStateUnloaded: 416 // Nothing to do - the process is already dead. 417 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 418 StateAsCString(m_state)); 419 return error; 420 421 case StateType::eStateConnected: 422 case StateType::eStateAttaching: 423 case StateType::eStateLaunching: 424 case StateType::eStateStopped: 425 case StateType::eStateRunning: 426 case StateType::eStateStepping: 427 case StateType::eStateSuspended: 428 // We can try to kill a process in these states. 429 break; 430 } 431 432 if (kill(GetID(), SIGKILL) != 0) { 433 error.SetErrorToErrno(); 434 return error; 435 } 436 437 return error; 438 } 439 440 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, 441 MemoryRegionInfo &range_info) { 442 443 if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 444 // We're done. 445 return Status("unsupported"); 446 } 447 448 Status error = PopulateMemoryRegionCache(); 449 if (error.Fail()) { 450 return error; 451 } 452 453 lldb::addr_t prev_base_address = 0; 454 // FIXME start by finding the last region that is <= target address using 455 // binary search. Data is sorted. 456 // There can be a ton of regions on pthreads apps with lots of threads. 457 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 458 ++it) { 459 MemoryRegionInfo &proc_entry_info = it->first; 460 // Sanity check assumption that memory map entries are ascending. 461 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 462 "descending memory map entries detected, unexpected"); 463 prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 464 UNUSED_IF_ASSERT_DISABLED(prev_base_address); 465 // If the target address comes before this entry, indicate distance to next 466 // region. 467 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 468 range_info.GetRange().SetRangeBase(load_addr); 469 range_info.GetRange().SetByteSize( 470 proc_entry_info.GetRange().GetRangeBase() - load_addr); 471 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 472 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 473 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 474 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 475 return error; 476 } else if (proc_entry_info.GetRange().Contains(load_addr)) { 477 // The target address is within the memory region we're processing here. 478 range_info = proc_entry_info; 479 return error; 480 } 481 // The target memory address comes somewhere after the region we just 482 // parsed. 483 } 484 // If we made it here, we didn't find an entry that contained the given 485 // address. Return the load_addr as start and the amount of bytes betwwen 486 // load address and the end of the memory as size. 487 range_info.GetRange().SetRangeBase(load_addr); 488 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 489 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 490 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 491 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 492 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 493 return error; 494 } 495 496 Status NativeProcessNetBSD::PopulateMemoryRegionCache() { 497 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 498 // If our cache is empty, pull the latest. There should always be at least 499 // one memory region if memory region handling is supported. 500 if (!m_mem_region_cache.empty()) { 501 LLDB_LOG(log, "reusing {0} cached memory region entries", 502 m_mem_region_cache.size()); 503 return Status(); 504 } 505 506 struct kinfo_vmentry *vm; 507 size_t count, i; 508 vm = kinfo_getvmmap(GetID(), &count); 509 if (vm == NULL) { 510 m_supports_mem_region = LazyBool::eLazyBoolNo; 511 Status error; 512 error.SetErrorString("not supported"); 513 return error; 514 } 515 for (i = 0; i < count; i++) { 516 MemoryRegionInfo info; 517 info.Clear(); 518 info.GetRange().SetRangeBase(vm[i].kve_start); 519 info.GetRange().SetRangeEnd(vm[i].kve_end); 520 info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 521 522 if (vm[i].kve_protection & VM_PROT_READ) 523 info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 524 else 525 info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 526 527 if (vm[i].kve_protection & VM_PROT_WRITE) 528 info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 529 else 530 info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 531 532 if (vm[i].kve_protection & VM_PROT_EXECUTE) 533 info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 534 else 535 info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 536 537 if (vm[i].kve_path[0]) 538 info.SetName(vm[i].kve_path); 539 540 m_mem_region_cache.emplace_back( 541 info, FileSpec(info.GetName().GetCString())); 542 } 543 free(vm); 544 545 if (m_mem_region_cache.empty()) { 546 // No entries after attempting to read them. This shouldn't happen. Assume 547 // we don't support map entries. 548 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support " 549 "for memory region metadata retrieval"); 550 m_supports_mem_region = LazyBool::eLazyBoolNo; 551 Status error; 552 error.SetErrorString("not supported"); 553 return error; 554 } 555 LLDB_LOG(log, "read {0} memory region entries from process {1}", 556 m_mem_region_cache.size(), GetID()); 557 // We support memory retrieval, remember that. 558 m_supports_mem_region = LazyBool::eLazyBoolYes; 559 return Status(); 560 } 561 562 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions, 563 lldb::addr_t &addr) { 564 return Status("Unimplemented"); 565 } 566 567 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) { 568 return Status("Unimplemented"); 569 } 570 571 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() { 572 // punt on this for now 573 return LLDB_INVALID_ADDRESS; 574 } 575 576 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); } 577 578 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, 579 bool hardware) { 580 if (hardware) 581 return Status("NativeProcessNetBSD does not support hardware breakpoints"); 582 else 583 return SetSoftwareBreakpoint(addr, size); 584 } 585 586 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path, 587 FileSpec &file_spec) { 588 return Status("Unimplemented"); 589 } 590 591 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name, 592 lldb::addr_t &load_addr) { 593 load_addr = LLDB_INVALID_ADDRESS; 594 return Status(); 595 } 596 597 void NativeProcessNetBSD::SigchldHandler() { 598 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 599 // Process all pending waitpid notifications. 600 int status; 601 ::pid_t wait_pid = 602 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG); 603 604 if (wait_pid == 0) 605 return; // We are done. 606 607 if (wait_pid == -1) { 608 Status error(errno, eErrorTypePOSIX); 609 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error); 610 } 611 612 WaitStatus wait_status = WaitStatus::Decode(status); 613 bool exited = wait_status.type == WaitStatus::Exit || 614 (wait_status.type == WaitStatus::Signal && 615 wait_pid == static_cast<::pid_t>(GetID())); 616 617 LLDB_LOG(log, 618 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}", 619 GetID(), wait_pid, status, exited); 620 621 if (exited) 622 MonitorExited(wait_pid, wait_status); 623 else { 624 assert(wait_status.type == WaitStatus::Stop); 625 MonitorCallback(wait_pid, wait_status.status); 626 } 627 } 628 629 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) { 630 for (const auto &thread : m_threads) { 631 assert(thread && "thread list should not contain NULL threads"); 632 if (thread->GetID() == thread_id) { 633 // We have this thread. 634 return true; 635 } 636 } 637 638 // We don't have this thread. 639 return false; 640 } 641 642 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) { 643 644 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 645 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 646 647 assert(!HasThreadNoLock(thread_id) && 648 "attempted to add a thread by id that already exists"); 649 650 // If this is the first thread, save it as the current thread 651 if (m_threads.empty()) 652 SetCurrentThreadID(thread_id); 653 654 m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id)); 655 return static_cast<NativeThreadNetBSD &>(*m_threads.back()); 656 } 657 658 Status NativeProcessNetBSD::Attach() { 659 // Attach to the requested process. 660 // An attach will cause the thread to stop with a SIGSTOP. 661 Status status = PtraceWrapper(PT_ATTACH, m_pid); 662 if (status.Fail()) 663 return status; 664 665 int wstatus; 666 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this 667 // point we should have a thread stopped if waitpid succeeds. 668 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, 669 m_pid, nullptr, WALLSIG)) < 0) 670 return Status(errno, eErrorTypePOSIX); 671 672 /* Initialize threads */ 673 status = ReinitializeThreads(); 674 if (status.Fail()) 675 return status; 676 677 for (const auto &thread : m_threads) 678 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 679 680 // Let our process instance know the thread has stopped. 681 SetState(StateType::eStateStopped); 682 return Status(); 683 } 684 685 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, 686 size_t size, size_t &bytes_read) { 687 unsigned char *dst = static_cast<unsigned char *>(buf); 688 struct ptrace_io_desc io; 689 690 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 691 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 692 693 bytes_read = 0; 694 io.piod_op = PIOD_READ_D; 695 io.piod_len = size; 696 697 do { 698 io.piod_offs = (void *)(addr + bytes_read); 699 io.piod_addr = dst + bytes_read; 700 701 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 702 if (error.Fail()) 703 return error; 704 705 bytes_read = io.piod_len; 706 io.piod_len = size - bytes_read; 707 } while (bytes_read < size); 708 709 return Status(); 710 } 711 712 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, 713 size_t size, size_t &bytes_written) { 714 const unsigned char *src = static_cast<const unsigned char *>(buf); 715 Status error; 716 struct ptrace_io_desc io; 717 718 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 719 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 720 721 bytes_written = 0; 722 io.piod_op = PIOD_WRITE_D; 723 io.piod_len = size; 724 725 do { 726 io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written)); 727 io.piod_offs = (void *)(addr + bytes_written); 728 729 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 730 if (error.Fail()) 731 return error; 732 733 bytes_written = io.piod_len; 734 io.piod_len = size - bytes_written; 735 } while (bytes_written < size); 736 737 return error; 738 } 739 740 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 741 NativeProcessNetBSD::GetAuxvData() const { 742 /* 743 * ELF_AUX_ENTRIES is currently restricted to kernel 744 * (<sys/exec_elf.h> r. 1.155 specifies 15) 745 * 746 * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this 747 * information isn't needed. 748 */ 749 size_t auxv_size = 100 * sizeof(AuxInfo); 750 751 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf = 752 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size); 753 754 struct ptrace_io_desc io; 755 io.piod_op = PIOD_READ_AUXV; 756 io.piod_offs = 0; 757 io.piod_addr = static_cast<void *>(buf.get()->getBufferStart()); 758 io.piod_len = auxv_size; 759 760 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 761 762 if (error.Fail()) 763 return std::error_code(error.GetError(), std::generic_category()); 764 765 if (io.piod_len < 1) 766 return std::error_code(ECANCELED, std::generic_category()); 767 768 return std::move(buf); 769 } 770 771 Status NativeProcessNetBSD::ReinitializeThreads() { 772 // Clear old threads 773 m_threads.clear(); 774 775 // Initialize new thread 776 struct ptrace_lwpinfo info = {}; 777 Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 778 if (error.Fail()) { 779 return error; 780 } 781 // Reinitialize from scratch threads and register them in process 782 while (info.pl_lwpid != 0) { 783 AddThread(info.pl_lwpid); 784 error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 785 if (error.Fail()) { 786 return error; 787 } 788 } 789 790 return error; 791 } 792