ProcessFreeBSD.cpp revision 360660
1//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++ 2//-*-===// 3// 4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 5// See https://llvm.org/LICENSE.txt for license information. 6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7// 8//===----------------------------------------------------------------------===// 9 10#include <errno.h> 11#include <pthread.h> 12#include <pthread_np.h> 13#include <stdlib.h> 14#include <sys/sysctl.h> 15#include <sys/types.h> 16#include <sys/user.h> 17#include <machine/elf.h> 18 19#include <mutex> 20#include <unordered_map> 21 22#include "lldb/Core/PluginManager.h" 23#include "lldb/Host/FileSystem.h" 24#include "lldb/Host/Host.h" 25#include "lldb/Symbol/ObjectFile.h" 26#include "lldb/Target/DynamicLoader.h" 27#include "lldb/Target/Target.h" 28#include "lldb/Utility/RegisterValue.h" 29#include "lldb/Utility/State.h" 30 31#include "FreeBSDThread.h" 32#include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 33#include "Plugins/Process/Utility/FreeBSDSignals.h" 34#include "Plugins/Process/Utility/InferiorCallPOSIX.h" 35#include "ProcessFreeBSD.h" 36#include "ProcessMonitor.h" 37 38#include "lldb/Breakpoint/BreakpointLocation.h" 39#include "lldb/Breakpoint/Watchpoint.h" 40#include "lldb/Core/Module.h" 41#include "lldb/Core/ModuleSpec.h" 42#include "lldb/Core/PluginManager.h" 43#include "lldb/Host/Host.h" 44#include "lldb/Symbol/ObjectFile.h" 45#include "lldb/Target/DynamicLoader.h" 46#include "lldb/Target/Platform.h" 47#include "lldb/Target/Target.h" 48#include "lldb/Utility/DataBufferHeap.h" 49#include "lldb/Utility/FileSpec.h" 50#include "lldb/Utility/State.h" 51 52#include "lldb/Host/posix/Fcntl.h" 53 54#include "llvm/Support/FileSystem.h" 55#include "llvm/Support/Threading.h" 56 57using namespace lldb; 58using namespace lldb_private; 59 60namespace { 61UnixSignalsSP &GetFreeBSDSignals() { 62 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals()); 63 return s_freebsd_signals_sp; 64} 65} 66 67// Static functions. 68 69lldb::ProcessSP 70ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp, 71 lldb::ListenerSP listener_sp, 72 const FileSpec *crash_file_path) { 73 lldb::ProcessSP process_sp; 74 if (crash_file_path == NULL) 75 process_sp.reset( 76 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals())); 77 return process_sp; 78} 79 80void ProcessFreeBSD::Initialize() { 81 static llvm::once_flag g_once_flag; 82 83 llvm::call_once(g_once_flag, []() { 84 PluginManager::RegisterPlugin(GetPluginNameStatic(), 85 GetPluginDescriptionStatic(), CreateInstance); 86 }); 87} 88 89lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() { 90 static ConstString g_name("freebsd"); 91 return g_name; 92} 93 94const char *ProcessFreeBSD::GetPluginDescriptionStatic() { 95 return "Process plugin for FreeBSD"; 96} 97 98// ProcessInterface protocol. 99 100lldb_private::ConstString ProcessFreeBSD::GetPluginName() { 101 return GetPluginNameStatic(); 102} 103 104uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; } 105 106void ProcessFreeBSD::Terminate() {} 107 108Status ProcessFreeBSD::DoDetach(bool keep_stopped) { 109 Status error; 110 if (keep_stopped) { 111 error.SetErrorString("Detaching with keep_stopped true is not currently " 112 "supported on FreeBSD."); 113 return error; 114 } 115 116 error = m_monitor->Detach(GetID()); 117 118 if (error.Success()) 119 SetPrivateState(eStateDetached); 120 121 return error; 122} 123 124Status ProcessFreeBSD::DoResume() { 125 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 126 127 SetPrivateState(eStateRunning); 128 129 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 130 bool do_step = false; 131 bool software_single_step = !SupportHardwareSingleStepping(); 132 133 for (tid_collection::const_iterator t_pos = m_run_tids.begin(), 134 t_end = m_run_tids.end(); 135 t_pos != t_end; ++t_pos) { 136 m_monitor->ThreadSuspend(*t_pos, false); 137 } 138 for (tid_collection::const_iterator t_pos = m_step_tids.begin(), 139 t_end = m_step_tids.end(); 140 t_pos != t_end; ++t_pos) { 141 m_monitor->ThreadSuspend(*t_pos, false); 142 do_step = true; 143 if (software_single_step) { 144 Status error = SetupSoftwareSingleStepping(*t_pos); 145 if (error.Fail()) 146 return error; 147 } 148 } 149 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(), 150 t_end = m_suspend_tids.end(); 151 t_pos != t_end; ++t_pos) { 152 m_monitor->ThreadSuspend(*t_pos, true); 153 // XXX Cannot PT_CONTINUE properly with suspended threads. 154 do_step = true; 155 } 156 157 if (log) 158 log->Printf("process %" PRIu64 " resuming (%s)", GetID(), 159 do_step ? "step" : "continue"); 160 if (do_step && !software_single_step) 161 m_monitor->SingleStep(GetID(), m_resume_signo); 162 else 163 m_monitor->Resume(GetID(), m_resume_signo); 164 165 return Status(); 166} 167 168bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, 169 ThreadList &new_thread_list) { 170 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 171 if (log) 172 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__, 173 GetID()); 174 175 std::vector<lldb::pid_t> tds; 176 if (!GetMonitor().GetCurrentThreadIDs(tds)) { 177 return false; 178 } 179 180 ThreadList old_thread_list_copy(old_thread_list); 181 for (size_t i = 0; i < tds.size(); ++i) { 182 tid_t tid = tds[i]; 183 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false)); 184 if (!thread_sp) { 185 thread_sp.reset(new FreeBSDThread(*this, tid)); 186 if (log) 187 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid); 188 } else { 189 if (log) 190 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__, 191 tid); 192 } 193 new_thread_list.AddThread(thread_sp); 194 } 195 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) { 196 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false)); 197 if (old_thread_sp) { 198 if (log) 199 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__); 200 } 201 } 202 203 return true; 204} 205 206Status ProcessFreeBSD::WillResume() { 207 m_resume_signo = 0; 208 m_suspend_tids.clear(); 209 m_run_tids.clear(); 210 m_step_tids.clear(); 211 return Process::WillResume(); 212} 213 214void ProcessFreeBSD::SendMessage(const ProcessMessage &message) { 215 std::lock_guard<std::recursive_mutex> guard(m_message_mutex); 216 217 switch (message.GetKind()) { 218 case ProcessMessage::eInvalidMessage: 219 return; 220 221 case ProcessMessage::eAttachMessage: 222 SetPrivateState(eStateStopped); 223 return; 224 225 case ProcessMessage::eLimboMessage: 226 case ProcessMessage::eExitMessage: 227 SetExitStatus(message.GetExitStatus(), NULL); 228 break; 229 230 case ProcessMessage::eSignalMessage: 231 case ProcessMessage::eSignalDeliveredMessage: 232 case ProcessMessage::eBreakpointMessage: 233 case ProcessMessage::eTraceMessage: 234 case ProcessMessage::eWatchpointMessage: 235 case ProcessMessage::eCrashMessage: 236 SetPrivateState(eStateStopped); 237 break; 238 239 case ProcessMessage::eNewThreadMessage: 240 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD"); 241 break; 242 243 case ProcessMessage::eExecMessage: 244 SetPrivateState(eStateStopped); 245 break; 246 } 247 248 m_message_queue.push(message); 249} 250 251// Constructors and destructors. 252 253ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp, 254 lldb::ListenerSP listener_sp, 255 UnixSignalsSP &unix_signals_sp) 256 : Process(target_sp, listener_sp, unix_signals_sp), 257 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL), 258 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(), 259 m_resume_signo(0) { 260 // FIXME: Putting this code in the ctor and saving the byte order in a 261 // member variable is a hack to avoid const qual issues in GetByteOrder. 262 lldb::ModuleSP module = GetTarget().GetExecutableModule(); 263 if (module && module->GetObjectFile()) 264 m_byte_order = module->GetObjectFile()->GetByteOrder(); 265} 266 267ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; } 268 269// Process protocol. 270void ProcessFreeBSD::Finalize() { 271 Process::Finalize(); 272 273 if (m_monitor) 274 m_monitor->StopMonitor(); 275} 276 277bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp, 278 bool plugin_specified_by_name) { 279 // For now we are just making sure the file exists for a given module 280 ModuleSP exe_module_sp(target_sp->GetExecutableModule()); 281 if (exe_module_sp.get()) 282 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec()); 283 // If there is no executable module, we return true since we might be 284 // preparing to attach. 285 return true; 286} 287 288Status 289ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid, 290 const ProcessAttachInfo &attach_info) { 291 Status error; 292 assert(m_monitor == NULL); 293 294 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 295 LLDB_LOGV(log, "pid = {0}", GetID()); 296 297 m_monitor = new ProcessMonitor(this, pid, error); 298 299 if (!error.Success()) 300 return error; 301 302 PlatformSP platform_sp(GetTarget().GetPlatform()); 303 assert(platform_sp.get()); 304 if (!platform_sp) 305 return error; // FIXME: Detatch? 306 307 // Find out what we can about this process 308 ProcessInstanceInfo process_info; 309 platform_sp->GetProcessInfo(pid, process_info); 310 311 // Resolve the executable module 312 ModuleSP exe_module_sp; 313 FileSpecList executable_search_paths( 314 Target::GetDefaultExecutableSearchPaths()); 315 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), 316 GetTarget().GetArchitecture()); 317 error = platform_sp->ResolveExecutable( 318 exe_module_spec, exe_module_sp, 319 executable_search_paths.GetSize() ? &executable_search_paths : NULL); 320 if (!error.Success()) 321 return error; 322 323 // Fix the target architecture if necessary 324 const ArchSpec &module_arch = exe_module_sp->GetArchitecture(); 325 if (module_arch.IsValid() && 326 !GetTarget().GetArchitecture().IsExactMatch(module_arch)) 327 GetTarget().SetArchitecture(module_arch); 328 329 // Initialize the target module list 330 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes); 331 332 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD()); 333 334 SetID(pid); 335 336 return error; 337} 338 339Status ProcessFreeBSD::WillLaunch(Module *module) { 340 Status error; 341 return error; 342} 343 344FileSpec 345ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action, 346 const FileSpec &default_file_spec, 347 const FileSpec &dbg_pts_file_spec) { 348 FileSpec file_spec{}; 349 350 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) { 351 file_spec = file_action->GetFileSpec(); 352 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts). 353 // If so, convert to using a different default path instead to redirect I/O 354 // to the debugger console. This should also handle user overrides to 355 // /dev/null or a different file. 356 if (!file_spec || file_spec == dbg_pts_file_spec) 357 file_spec = default_file_spec; 358 } 359 return file_spec; 360} 361 362Status ProcessFreeBSD::DoLaunch(Module *module, 363 ProcessLaunchInfo &launch_info) { 364 Status error; 365 assert(m_monitor == NULL); 366 367 FileSpec working_dir = launch_info.GetWorkingDirectory(); 368 if (working_dir) { 369 FileSystem::Instance().Resolve(working_dir); 370 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) { 371 error.SetErrorStringWithFormat("No such file or directory: %s", 372 working_dir.GetCString()); 373 return error; 374 } 375 } 376 377 SetPrivateState(eStateLaunching); 378 379 const lldb_private::FileAction *file_action; 380 381 // Default of empty will mean to use existing open file descriptors 382 FileSpec stdin_file_spec{}; 383 FileSpec stdout_file_spec{}; 384 FileSpec stderr_file_spec{}; 385 386 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)}; 387 388 file_action = launch_info.GetFileActionForFD(STDIN_FILENO); 389 stdin_file_spec = 390 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec); 391 392 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO); 393 stdout_file_spec = 394 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec); 395 396 file_action = launch_info.GetFileActionForFD(STDERR_FILENO); 397 stderr_file_spec = 398 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec); 399 400 m_monitor = new ProcessMonitor( 401 this, module, launch_info.GetArguments().GetConstArgumentVector(), 402 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec, 403 stderr_file_spec, working_dir, launch_info, error); 404 405 m_module = module; 406 407 if (!error.Success()) 408 return error; 409 410 int terminal = m_monitor->GetTerminalFD(); 411 if (terminal >= 0) { 412// The reader thread will close the file descriptor when done, so we pass it a 413// copy. 414#ifdef F_DUPFD_CLOEXEC 415 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0); 416 if (stdio == -1) { 417 error.SetErrorToErrno(); 418 return error; 419 } 420#else 421 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD) 422 int stdio = fcntl(terminal, F_DUPFD, 0); 423 if (stdio == -1) { 424 error.SetErrorToErrno(); 425 return error; 426 } 427 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC); 428 if (stdio == -1) { 429 error.SetErrorToErrno(); 430 return error; 431 } 432#endif 433 SetSTDIOFileDescriptor(stdio); 434 } 435 436 SetID(m_monitor->GetPID()); 437 return error; 438} 439 440void ProcessFreeBSD::DidLaunch() {} 441 442addr_t ProcessFreeBSD::GetImageInfoAddress() { 443 Target *target = &GetTarget(); 444 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); 445 Address addr = obj_file->GetImageInfoAddress(target); 446 447 if (addr.IsValid()) 448 return addr.GetLoadAddress(target); 449 return LLDB_INVALID_ADDRESS; 450} 451 452Status ProcessFreeBSD::DoHalt(bool &caused_stop) { 453 Status error; 454 455 if (IsStopped()) { 456 caused_stop = false; 457 } else if (kill(GetID(), SIGSTOP)) { 458 caused_stop = false; 459 error.SetErrorToErrno(); 460 } else { 461 caused_stop = true; 462 } 463 return error; 464} 465 466Status ProcessFreeBSD::DoSignal(int signal) { 467 Status error; 468 469 if (kill(GetID(), signal)) 470 error.SetErrorToErrno(); 471 472 return error; 473} 474 475Status ProcessFreeBSD::DoDestroy() { 476 Status error; 477 478 if (!HasExited()) { 479 assert(m_monitor); 480 m_exit_now = true; 481 if (GetID() == LLDB_INVALID_PROCESS_ID) { 482 error.SetErrorString("invalid process id"); 483 return error; 484 } 485 if (!m_monitor->Kill()) { 486 error.SetErrorToErrno(); 487 return error; 488 } 489 490 SetPrivateState(eStateExited); 491 } 492 493 return error; 494} 495 496void ProcessFreeBSD::DoDidExec() { 497 Target *target = &GetTarget(); 498 if (target) { 499 PlatformSP platform_sp(target->GetPlatform()); 500 assert(platform_sp.get()); 501 if (platform_sp) { 502 ProcessInstanceInfo process_info; 503 platform_sp->GetProcessInfo(GetID(), process_info); 504 ModuleSP exe_module_sp; 505 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), 506 target->GetArchitecture()); 507 FileSpecList executable_search_paths( 508 Target::GetDefaultExecutableSearchPaths()); 509 Status error = platform_sp->ResolveExecutable( 510 exe_module_spec, exe_module_sp, 511 executable_search_paths.GetSize() ? &executable_search_paths : NULL); 512 if (!error.Success()) 513 return; 514 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes); 515 } 516 } 517} 518 519bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) { 520 bool added_to_set = false; 521 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid); 522 if (it == m_seen_initial_stop.end()) { 523 m_seen_initial_stop.insert(stop_tid); 524 added_to_set = true; 525 } 526 return added_to_set; 527} 528 529bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) { 530 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end()); 531} 532 533FreeBSDThread * 534ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process, 535 lldb::tid_t tid) { 536 return new FreeBSDThread(process, tid); 537} 538 539void ProcessFreeBSD::RefreshStateAfterStop() { 540 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 541 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size()); 542 543 std::lock_guard<std::recursive_mutex> guard(m_message_mutex); 544 545 // This method used to only handle one message. Changing it to loop allows 546 // it to handle the case where we hit a breakpoint while handling a different 547 // breakpoint. 548 while (!m_message_queue.empty()) { 549 ProcessMessage &message = m_message_queue.front(); 550 551 // Resolve the thread this message corresponds to and pass it along. 552 lldb::tid_t tid = message.GetTID(); 553 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}", 554 m_message_queue.size(), tid); 555 556 m_thread_list.RefreshStateAfterStop(); 557 558 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 559 GetThreadList().FindThreadByID(tid, false).get()); 560 if (thread) 561 thread->Notify(message); 562 563 if (message.GetKind() == ProcessMessage::eExitMessage) { 564 // FIXME: We should tell the user about this, but the limbo message is 565 // probably better for that. 566 LLDB_LOG(log, "removing thread, tid = {0}", tid); 567 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 568 569 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false); 570 thread_sp.reset(); 571 m_seen_initial_stop.erase(tid); 572 } 573 574 m_message_queue.pop(); 575 } 576} 577 578bool ProcessFreeBSD::IsAlive() { 579 StateType state = GetPrivateState(); 580 return state != eStateDetached && state != eStateExited && 581 state != eStateInvalid && state != eStateUnloaded; 582} 583 584size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size, 585 Status &error) { 586 assert(m_monitor); 587 return m_monitor->ReadMemory(vm_addr, buf, size, error); 588} 589 590size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf, 591 size_t size, Status &error) { 592 assert(m_monitor); 593 return m_monitor->WriteMemory(vm_addr, buf, size, error); 594} 595 596addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions, 597 Status &error) { 598 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 599 600 unsigned prot = 0; 601 if (permissions & lldb::ePermissionsReadable) 602 prot |= eMmapProtRead; 603 if (permissions & lldb::ePermissionsWritable) 604 prot |= eMmapProtWrite; 605 if (permissions & lldb::ePermissionsExecutable) 606 prot |= eMmapProtExec; 607 608 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 609 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 610 m_addr_to_mmap_size[allocated_addr] = size; 611 error.Clear(); 612 } else { 613 allocated_addr = LLDB_INVALID_ADDRESS; 614 error.SetErrorStringWithFormat( 615 "unable to allocate %zu bytes of memory with permissions %s", size, 616 GetPermissionsAsCString(permissions)); 617 } 618 619 return allocated_addr; 620} 621 622Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) { 623 Status error; 624 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 625 if (pos != m_addr_to_mmap_size.end() && 626 InferiorCallMunmap(this, addr, pos->second)) 627 m_addr_to_mmap_size.erase(pos); 628 else 629 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, 630 addr); 631 632 return error; 633} 634 635size_t 636ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) { 637 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4}; 638 static const uint8_t g_i386_opcode[] = {0xCC}; 639 640 ArchSpec arch = GetTarget().GetArchitecture(); 641 const uint8_t *opcode = NULL; 642 size_t opcode_size = 0; 643 644 switch (arch.GetMachine()) { 645 default: 646 assert(false && "CPU type not supported!"); 647 break; 648 649 case llvm::Triple::arm: { 650 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 651 // linux kernel does otherwise. 652 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 653 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde}; 654 655 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0)); 656 AddressClass addr_class = AddressClass::eUnknown; 657 658 if (bp_loc_sp) 659 addr_class = bp_loc_sp->GetAddress().GetAddressClass(); 660 661 if (addr_class == AddressClass::eCodeAlternateISA || 662 (addr_class == AddressClass::eUnknown && 663 bp_loc_sp->GetAddress().GetOffset() & 1)) { 664 opcode = g_thumb_breakpoint_opcode; 665 opcode_size = sizeof(g_thumb_breakpoint_opcode); 666 } else { 667 opcode = g_arm_breakpoint_opcode; 668 opcode_size = sizeof(g_arm_breakpoint_opcode); 669 } 670 } break; 671 case llvm::Triple::aarch64: 672 opcode = g_aarch64_opcode; 673 opcode_size = sizeof(g_aarch64_opcode); 674 break; 675 676 case llvm::Triple::x86: 677 case llvm::Triple::x86_64: 678 opcode = g_i386_opcode; 679 opcode_size = sizeof(g_i386_opcode); 680 break; 681 } 682 683 bp_site->SetTrapOpcode(opcode, opcode_size); 684 return opcode_size; 685} 686 687Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) { 688 return EnableSoftwareBreakpoint(bp_site); 689} 690 691Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) { 692 return DisableSoftwareBreakpoint(bp_site); 693} 694 695Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) { 696 Status error; 697 if (wp) { 698 user_id_t watchID = wp->GetID(); 699 addr_t addr = wp->GetLoadAddress(); 700 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS)); 701 if (log) 702 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")", 703 watchID); 704 if (wp->IsEnabled()) { 705 if (log) 706 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 707 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 708 watchID, (uint64_t)addr); 709 return error; 710 } 711 712 // Try to find a vacant watchpoint slot in the inferiors' main thread 713 uint32_t wp_hw_index = LLDB_INVALID_INDEX32; 714 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 715 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 716 m_thread_list.GetThreadAtIndex(0, false).get()); 717 718 if (thread) 719 wp_hw_index = thread->FindVacantWatchpointIndex(); 720 721 if (wp_hw_index == LLDB_INVALID_INDEX32) { 722 error.SetErrorString("Setting hardware watchpoint failed."); 723 } else { 724 wp->SetHardwareIndex(wp_hw_index); 725 bool wp_enabled = true; 726 uint32_t thread_count = m_thread_list.GetSize(false); 727 for (uint32_t i = 0; i < thread_count; ++i) { 728 thread = static_cast<FreeBSDThread *>( 729 m_thread_list.GetThreadAtIndex(i, false).get()); 730 if (thread) 731 wp_enabled &= thread->EnableHardwareWatchpoint(wp); 732 else 733 wp_enabled = false; 734 } 735 if (wp_enabled) { 736 wp->SetEnabled(true, notify); 737 return error; 738 } else { 739 // Watchpoint enabling failed on at least one of the threads so roll 740 // back all of them 741 DisableWatchpoint(wp, false); 742 error.SetErrorString("Setting hardware watchpoint failed"); 743 } 744 } 745 } else 746 error.SetErrorString("Watchpoint argument was NULL."); 747 return error; 748} 749 750Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) { 751 Status error; 752 if (wp) { 753 user_id_t watchID = wp->GetID(); 754 addr_t addr = wp->GetLoadAddress(); 755 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS)); 756 if (log) 757 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")", 758 watchID); 759 if (!wp->IsEnabled()) { 760 if (log) 761 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 762 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.", 763 watchID, (uint64_t)addr); 764 // This is needed (for now) to keep watchpoints disabled correctly 765 wp->SetEnabled(false, notify); 766 return error; 767 } 768 769 if (wp->IsHardware()) { 770 bool wp_disabled = true; 771 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 772 uint32_t thread_count = m_thread_list.GetSize(false); 773 for (uint32_t i = 0; i < thread_count; ++i) { 774 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 775 m_thread_list.GetThreadAtIndex(i, false).get()); 776 if (thread) 777 wp_disabled &= thread->DisableHardwareWatchpoint(wp); 778 else 779 wp_disabled = false; 780 } 781 if (wp_disabled) { 782 wp->SetHardwareIndex(LLDB_INVALID_INDEX32); 783 wp->SetEnabled(false, notify); 784 return error; 785 } else 786 error.SetErrorString("Disabling hardware watchpoint failed"); 787 } 788 } else 789 error.SetErrorString("Watchpoint argument was NULL."); 790 return error; 791} 792 793Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) { 794 Status error; 795 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 796 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 797 m_thread_list.GetThreadAtIndex(0, false).get()); 798 if (thread) 799 num = thread->NumSupportedHardwareWatchpoints(); 800 else 801 error.SetErrorString("Process does not exist."); 802 return error; 803} 804 805Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) { 806 Status error = GetWatchpointSupportInfo(num); 807 // Watchpoints trigger and halt the inferior after the corresponding 808 // instruction has been executed. 809 after = true; 810 return error; 811} 812 813uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() { 814 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 815 // Do not allow recursive updates. 816 return m_thread_list.GetSize(false); 817} 818 819ByteOrder ProcessFreeBSD::GetByteOrder() const { 820 // FIXME: We should be able to extract this value directly. See comment in 821 // ProcessFreeBSD(). 822 return m_byte_order; 823} 824 825size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) { 826 ssize_t status; 827 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) { 828 error.SetErrorToErrno(); 829 return 0; 830 } 831 return status; 832} 833 834// Utility functions. 835 836bool ProcessFreeBSD::HasExited() { 837 switch (GetPrivateState()) { 838 default: 839 break; 840 841 case eStateDetached: 842 case eStateExited: 843 return true; 844 } 845 846 return false; 847} 848 849bool ProcessFreeBSD::IsStopped() { 850 switch (GetPrivateState()) { 851 default: 852 break; 853 854 case eStateStopped: 855 case eStateCrashed: 856 case eStateSuspended: 857 return true; 858 } 859 860 return false; 861} 862 863bool ProcessFreeBSD::IsAThreadRunning() { 864 bool is_running = false; 865 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 866 uint32_t thread_count = m_thread_list.GetSize(false); 867 for (uint32_t i = 0; i < thread_count; ++i) { 868 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 869 m_thread_list.GetThreadAtIndex(i, false).get()); 870 StateType thread_state = thread->GetState(); 871 if (thread_state == eStateRunning || thread_state == eStateStepping) { 872 is_running = true; 873 break; 874 } 875 } 876 return is_running; 877} 878 879lldb_private::DataExtractor ProcessFreeBSD::GetAuxvData() { 880 // If we're the local platform, we can ask the host for auxv data. 881 PlatformSP platform_sp = GetTarget().GetPlatform(); 882 assert(platform_sp && platform_sp->IsHost()); 883 884 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()}; 885 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo); 886 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0)); 887 888 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) { 889 perror("sysctl failed on auxv"); 890 buf_sp.reset(); 891 } 892 893 return DataExtractor(buf_sp, GetByteOrder(), GetAddressByteSize()); 894} 895 896struct EmulatorBaton { 897 ProcessFreeBSD *m_process; 898 RegisterContext *m_reg_context; 899 900 // eRegisterKindDWARF -> RegisterValue 901 std::unordered_map<uint32_t, RegisterValue> m_register_values; 902 903 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context) 904 : m_process(process), m_reg_context(reg_context) {} 905}; 906 907static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 908 const EmulateInstruction::Context &context, 909 lldb::addr_t addr, void *dst, size_t length) { 910 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 911 912 Status error; 913 size_t bytes_read = 914 emulator_baton->m_process->DoReadMemory(addr, dst, length, error); 915 if (!error.Success()) 916 bytes_read = 0; 917 return bytes_read; 918} 919 920static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 921 const RegisterInfo *reg_info, 922 RegisterValue ®_value) { 923 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 924 925 auto it = emulator_baton->m_register_values.find( 926 reg_info->kinds[eRegisterKindDWARF]); 927 if (it != emulator_baton->m_register_values.end()) { 928 reg_value = it->second; 929 return true; 930 } 931 932 // The emulator only fills in the dwarf register numbers (and in some cases 933 // the generic register numbers). Get the full register info from the 934 // register context based on the dwarf register numbers. 935 const RegisterInfo *full_reg_info = 936 emulator_baton->m_reg_context->GetRegisterInfo( 937 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 938 939 bool error = 940 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value); 941 return error; 942} 943 944static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 945 const EmulateInstruction::Context &context, 946 const RegisterInfo *reg_info, 947 const RegisterValue ®_value) { 948 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 949 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 950 reg_value; 951 return true; 952} 953 954static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 955 const EmulateInstruction::Context &context, 956 lldb::addr_t addr, const void *dst, 957 size_t length) { 958 return length; 959} 960 961bool ProcessFreeBSD::SingleStepBreakpointHit( 962 void *baton, lldb_private::StoppointCallbackContext *context, 963 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) { 964 return false; 965} 966 967Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, 968 lldb::addr_t addr) { 969 Status error; 970 971 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 972 if (log) { 973 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr); 974 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr); 975 } 976 977 // Validate the address. 978 if (addr == LLDB_INVALID_ADDRESS) 979 return Status("ProcessFreeBSD::%s invalid load address specified.", 980 __FUNCTION__); 981 982 Breakpoint *const sw_step_break = 983 m_process->GetTarget().CreateBreakpoint(addr, true, false).get(); 984 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true); 985 sw_step_break->SetBreakpointKind("software-signle-step"); 986 987 if (log) 988 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS", 989 __FUNCTION__, addr); 990 991 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()}); 992 return Status(); 993} 994 995bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) { 996 ThreadSP thread = GetThreadList().FindThreadByID(tid); 997 if (!thread) 998 return false; 999 1000 assert(thread->GetRegisterContext()); 1001 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC(); 1002 1003 const auto &iter = m_threads_stepping_with_breakpoint.find(tid); 1004 if (iter == m_threads_stepping_with_breakpoint.end()) 1005 return false; 1006 1007 lldb::break_id_t bp_id = iter->second; 1008 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id); 1009 if (!bp) 1010 return false; 1011 1012 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc); 1013 if (!bp_loc) 1014 return false; 1015 1016 GetTarget().RemoveBreakpointByID(bp_id); 1017 m_threads_stepping_with_breakpoint.erase(tid); 1018 return true; 1019} 1020 1021bool ProcessFreeBSD::SupportHardwareSingleStepping() const { 1022 lldb_private::ArchSpec arch = GetTarget().GetArchitecture(); 1023 if (arch.GetMachine() == llvm::Triple::arm || arch.IsMIPS()) 1024 return false; 1025 return true; 1026} 1027 1028Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { 1029 std::unique_ptr<EmulateInstruction> emulator_up( 1030 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(), 1031 eInstructionTypePCModifying, nullptr)); 1032 1033 if (emulator_up == nullptr) 1034 return Status("Instruction emulator not found!"); 1035 1036 FreeBSDThread *thread = static_cast<FreeBSDThread *>( 1037 m_thread_list.FindThreadByID(tid, false).get()); 1038 if (thread == NULL) 1039 return Status("Thread not found not found!"); 1040 1041 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext(); 1042 1043 EmulatorBaton baton(this, register_context_sp.get()); 1044 emulator_up->SetBaton(&baton); 1045 emulator_up->SetReadMemCallback(&ReadMemoryCallback); 1046 emulator_up->SetReadRegCallback(&ReadRegisterCallback); 1047 emulator_up->SetWriteMemCallback(&WriteMemoryCallback); 1048 emulator_up->SetWriteRegCallback(&WriteRegisterCallback); 1049 1050 if (!emulator_up->ReadInstruction()) 1051 return Status("Read instruction failed!"); 1052 1053 bool emulation_result = 1054 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 1055 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo( 1056 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 1057 auto pc_it = 1058 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 1059 1060 lldb::addr_t next_pc; 1061 if (emulation_result) { 1062 assert(pc_it != baton.m_register_values.end() && 1063 "Emulation was successful but PC wasn't updated"); 1064 next_pc = pc_it->second.GetAsUInt64(); 1065 } else if (pc_it == baton.m_register_values.end()) { 1066 // Emulate instruction failed and it haven't changed PC. Advance PC with 1067 // the size of the current opcode because the emulation of all 1068 // PC modifying instruction should be successful. The failure most 1069 // likely caused by a not supported instruction which don't modify PC. 1070 next_pc = 1071 register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize(); 1072 } else { 1073 // The instruction emulation failed after it modified the PC. It is an 1074 // unknown error where we can't continue because the next instruction is 1075 // modifying the PC but we don't know how. 1076 return Status("Instruction emulation failed unexpectedly"); 1077 } 1078 1079 SetSoftwareSingleStepBreakpoint(tid, next_pc); 1080 return Status(); 1081} 1082