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