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