1 //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include <errno.h> 11 #include <stdlib.h> 12 13 #include <mutex> 14 15 #include "lldb/Core/Debugger.h" 16 #include "lldb/Core/Module.h" 17 #include "lldb/Core/ModuleSpec.h" 18 #include "lldb/Core/PluginManager.h" 19 #include "lldb/Host/ConnectionFileDescriptor.h" 20 #include "lldb/Host/Host.h" 21 #include "lldb/Host/Symbols.h" 22 #include "lldb/Host/ThreadLauncher.h" 23 #include "lldb/Host/common/TCPSocket.h" 24 #include "lldb/Interpreter/CommandInterpreter.h" 25 #include "lldb/Interpreter/CommandObject.h" 26 #include "lldb/Interpreter/CommandObjectMultiword.h" 27 #include "lldb/Interpreter/CommandReturnObject.h" 28 #include "lldb/Interpreter/OptionGroupString.h" 29 #include "lldb/Interpreter/OptionGroupUInt64.h" 30 #include "lldb/Interpreter/OptionValueProperties.h" 31 #include "lldb/Symbol/ObjectFile.h" 32 #include "lldb/Target/RegisterContext.h" 33 #include "lldb/Target/Target.h" 34 #include "lldb/Target/Thread.h" 35 #include "lldb/Utility/State.h" 36 #include "lldb/Utility/StringExtractor.h" 37 #include "lldb/Utility/UUID.h" 38 39 #include "llvm/Support/Threading.h" 40 41 #define USEC_PER_SEC 1000000 42 43 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h" 44 #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h" 45 #include "ProcessKDP.h" 46 #include "ProcessKDPLog.h" 47 #include "ThreadKDP.h" 48 49 using namespace lldb; 50 using namespace lldb_private; 51 52 namespace { 53 54 static constexpr PropertyDefinition g_properties[] = { 55 {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, {}, 56 "Specify the default packet timeout in seconds."}}; 57 58 enum { ePropertyPacketTimeout }; 59 60 class PluginProperties : public Properties { 61 public: 62 static ConstString GetSettingName() { 63 return ProcessKDP::GetPluginNameStatic(); 64 } 65 66 PluginProperties() : Properties() { 67 m_collection_sp.reset(new OptionValueProperties(GetSettingName())); 68 m_collection_sp->Initialize(g_properties); 69 } 70 71 virtual ~PluginProperties() {} 72 73 uint64_t GetPacketTimeout() { 74 const uint32_t idx = ePropertyPacketTimeout; 75 return m_collection_sp->GetPropertyAtIndexAsUInt64( 76 NULL, idx, g_properties[idx].default_uint_value); 77 } 78 }; 79 80 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP; 81 82 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() { 83 static ProcessKDPPropertiesSP g_settings_sp; 84 if (!g_settings_sp) 85 g_settings_sp.reset(new PluginProperties()); 86 return g_settings_sp; 87 } 88 89 } // anonymous namespace end 90 91 static const lldb::tid_t g_kernel_tid = 1; 92 93 ConstString ProcessKDP::GetPluginNameStatic() { 94 static ConstString g_name("kdp-remote"); 95 return g_name; 96 } 97 98 const char *ProcessKDP::GetPluginDescriptionStatic() { 99 return "KDP Remote protocol based debugging plug-in for darwin kernel " 100 "debugging."; 101 } 102 103 void ProcessKDP::Terminate() { 104 PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance); 105 } 106 107 lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp, 108 ListenerSP listener_sp, 109 const FileSpec *crash_file_path) { 110 lldb::ProcessSP process_sp; 111 if (crash_file_path == NULL) 112 process_sp.reset(new ProcessKDP(target_sp, listener_sp)); 113 return process_sp; 114 } 115 116 bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) { 117 if (plugin_specified_by_name) 118 return true; 119 120 // For now we are just making sure the file exists for a given module 121 Module *exe_module = target_sp->GetExecutableModulePointer(); 122 if (exe_module) { 123 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple(); 124 switch (triple_ref.getOS()) { 125 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for 126 // iOS, but accept darwin just in case 127 case llvm::Triple::MacOSX: // For desktop targets 128 case llvm::Triple::IOS: // For arm targets 129 case llvm::Triple::TvOS: 130 case llvm::Triple::WatchOS: 131 if (triple_ref.getVendor() == llvm::Triple::Apple) { 132 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 133 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && 134 exe_objfile->GetStrata() == ObjectFile::eStrataKernel) 135 return true; 136 } 137 break; 138 139 default: 140 break; 141 } 142 } 143 return false; 144 } 145 146 //---------------------------------------------------------------------- 147 // ProcessKDP constructor 148 //---------------------------------------------------------------------- 149 ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp) 150 : Process(target_sp, listener_sp), 151 m_comm("lldb.process.kdp-remote.communication"), 152 m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"), 153 m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS), 154 m_command_sp(), m_kernel_thread_wp() { 155 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, 156 "async thread should exit"); 157 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, 158 "async thread continue"); 159 const uint64_t timeout_seconds = 160 GetGlobalPluginProperties()->GetPacketTimeout(); 161 if (timeout_seconds > 0) 162 m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); 163 } 164 165 //---------------------------------------------------------------------- 166 // Destructor 167 //---------------------------------------------------------------------- 168 ProcessKDP::~ProcessKDP() { 169 Clear(); 170 // We need to call finalize on the process before destroying ourselves to 171 // make sure all of the broadcaster cleanup goes as planned. If we destruct 172 // this class, then Process::~Process() might have problems trying to fully 173 // destroy the broadcaster. 174 Finalize(); 175 } 176 177 //---------------------------------------------------------------------- 178 // PluginInterface 179 //---------------------------------------------------------------------- 180 lldb_private::ConstString ProcessKDP::GetPluginName() { 181 return GetPluginNameStatic(); 182 } 183 184 uint32_t ProcessKDP::GetPluginVersion() { return 1; } 185 186 Status ProcessKDP::WillLaunch(Module *module) { 187 Status error; 188 error.SetErrorString("launching not supported in kdp-remote plug-in"); 189 return error; 190 } 191 192 Status ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) { 193 Status error; 194 error.SetErrorString( 195 "attaching to a by process ID not supported in kdp-remote plug-in"); 196 return error; 197 } 198 199 Status ProcessKDP::WillAttachToProcessWithName(const char *process_name, 200 bool wait_for_launch) { 201 Status error; 202 error.SetErrorString( 203 "attaching to a by process name not supported in kdp-remote plug-in"); 204 return error; 205 } 206 207 bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) { 208 uint32_t cpu = m_comm.GetCPUType(); 209 if (cpu) { 210 uint32_t sub = m_comm.GetCPUSubtype(); 211 arch.SetArchitecture(eArchTypeMachO, cpu, sub); 212 // Leave architecture vendor as unspecified unknown 213 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor); 214 arch.GetTriple().setVendorName(llvm::StringRef()); 215 return true; 216 } 217 arch.Clear(); 218 return false; 219 } 220 221 Status ProcessKDP::DoConnectRemote(Stream *strm, llvm::StringRef remote_url) { 222 Status error; 223 224 // Don't let any JIT happen when doing KDP as we can't allocate memory and we 225 // don't want to be mucking with threads that might already be handling 226 // exceptions 227 SetCanJIT(false); 228 229 if (remote_url.empty()) { 230 error.SetErrorStringWithFormat("empty connection URL"); 231 return error; 232 } 233 234 std::unique_ptr<ConnectionFileDescriptor> conn_ap( 235 new ConnectionFileDescriptor()); 236 if (conn_ap.get()) { 237 // Only try once for now. 238 // TODO: check if we should be retrying? 239 const uint32_t max_retry_count = 1; 240 for (uint32_t retry_count = 0; retry_count < max_retry_count; 241 ++retry_count) { 242 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess) 243 break; 244 usleep(100000); 245 } 246 } 247 248 if (conn_ap->IsConnected()) { 249 const TCPSocket &socket = 250 static_cast<const TCPSocket &>(*conn_ap->GetReadObject()); 251 const uint16_t reply_port = socket.GetLocalPortNumber(); 252 253 if (reply_port != 0) { 254 m_comm.SetConnection(conn_ap.release()); 255 256 if (m_comm.SendRequestReattach(reply_port)) { 257 if (m_comm.SendRequestConnect(reply_port, reply_port, 258 "Greetings from LLDB...")) { 259 m_comm.GetVersion(); 260 261 Target &target = GetTarget(); 262 ArchSpec kernel_arch; 263 // The host architecture 264 GetHostArchitecture(kernel_arch); 265 ArchSpec target_arch = target.GetArchitecture(); 266 // Merge in any unspecified stuff into the target architecture in 267 // case the target arch isn't set at all or incompletely. 268 target_arch.MergeFrom(kernel_arch); 269 target.SetArchitecture(target_arch); 270 271 /* Get the kernel's UUID and load address via KDP_KERNELVERSION 272 * packet. */ 273 /* An EFI kdp session has neither UUID nor load address. */ 274 275 UUID kernel_uuid = m_comm.GetUUID(); 276 addr_t kernel_load_addr = m_comm.GetLoadAddress(); 277 278 if (m_comm.RemoteIsEFI()) { 279 // Select an invalid plugin name for the dynamic loader so one 280 // doesn't get used since EFI does its own manual loading via 281 // python scripting 282 static ConstString g_none_dynamic_loader("none"); 283 m_dyld_plugin_name = g_none_dynamic_loader; 284 285 if (kernel_uuid.IsValid()) { 286 // If EFI passed in a UUID= try to lookup UUID The slide will not 287 // be provided. But the UUID lookup will be used to launch EFI 288 // debug scripts from the dSYM, that can load all of the symbols. 289 ModuleSpec module_spec; 290 module_spec.GetUUID() = kernel_uuid; 291 module_spec.GetArchitecture() = target.GetArchitecture(); 292 293 // Lookup UUID locally, before attempting dsymForUUID like action 294 module_spec.GetSymbolFileSpec() = 295 Symbols::LocateExecutableSymbolFile(module_spec); 296 if (module_spec.GetSymbolFileSpec()) { 297 ModuleSpec executable_module_spec = 298 Symbols::LocateExecutableObjectFile(module_spec); 299 if (FileSystem::Instance().Exists( 300 executable_module_spec.GetFileSpec())) { 301 module_spec.GetFileSpec() = 302 executable_module_spec.GetFileSpec(); 303 } 304 } 305 if (!module_spec.GetSymbolFileSpec() || 306 !module_spec.GetSymbolFileSpec()) 307 Symbols::DownloadObjectAndSymbolFile(module_spec, true); 308 309 if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) { 310 ModuleSP module_sp(new Module(module_spec)); 311 if (module_sp.get() && module_sp->GetObjectFile()) { 312 // Get the current target executable 313 ModuleSP exe_module_sp(target.GetExecutableModule()); 314 315 // Make sure you don't already have the right module loaded 316 // and they will be uniqued 317 if (exe_module_sp.get() != module_sp.get()) 318 target.SetExecutableModule(module_sp, eLoadDependentsNo); 319 } 320 } 321 } 322 } else if (m_comm.RemoteIsDarwinKernel()) { 323 m_dyld_plugin_name = 324 DynamicLoaderDarwinKernel::GetPluginNameStatic(); 325 if (kernel_load_addr != LLDB_INVALID_ADDRESS) { 326 m_kernel_load_addr = kernel_load_addr; 327 } 328 } 329 330 // Set the thread ID 331 UpdateThreadListIfNeeded(); 332 SetID(1); 333 GetThreadList(); 334 SetPrivateState(eStateStopped); 335 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream()); 336 if (async_strm_sp) { 337 const char *cstr; 338 if ((cstr = m_comm.GetKernelVersion()) != NULL) { 339 async_strm_sp->Printf("Version: %s\n", cstr); 340 async_strm_sp->Flush(); 341 } 342 // if ((cstr = m_comm.GetImagePath ()) != NULL) 343 // { 344 // async_strm_sp->Printf ("Image Path: 345 // %s\n", cstr); 346 // async_strm_sp->Flush(); 347 // } 348 } 349 } else { 350 error.SetErrorString("KDP_REATTACH failed"); 351 } 352 } else { 353 error.SetErrorString("KDP_REATTACH failed"); 354 } 355 } else { 356 error.SetErrorString("invalid reply port from UDP connection"); 357 } 358 } else { 359 if (error.Success()) 360 error.SetErrorStringWithFormat("failed to connect to '%s'", 361 remote_url.str().c_str()); 362 } 363 if (error.Fail()) 364 m_comm.Disconnect(); 365 366 return error; 367 } 368 369 //---------------------------------------------------------------------- 370 // Process Control 371 //---------------------------------------------------------------------- 372 Status ProcessKDP::DoLaunch(Module *exe_module, 373 ProcessLaunchInfo &launch_info) { 374 Status error; 375 error.SetErrorString("launching not supported in kdp-remote plug-in"); 376 return error; 377 } 378 379 Status 380 ProcessKDP::DoAttachToProcessWithID(lldb::pid_t attach_pid, 381 const ProcessAttachInfo &attach_info) { 382 Status error; 383 error.SetErrorString( 384 "attach to process by ID is not supported in kdp remote debugging"); 385 return error; 386 } 387 388 Status 389 ProcessKDP::DoAttachToProcessWithName(const char *process_name, 390 const ProcessAttachInfo &attach_info) { 391 Status error; 392 error.SetErrorString( 393 "attach to process by name is not supported in kdp remote debugging"); 394 return error; 395 } 396 397 void ProcessKDP::DidAttach(ArchSpec &process_arch) { 398 Process::DidAttach(process_arch); 399 400 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 401 if (log) 402 log->Printf("ProcessKDP::DidAttach()"); 403 if (GetID() != LLDB_INVALID_PROCESS_ID) { 404 GetHostArchitecture(process_arch); 405 } 406 } 407 408 addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; } 409 410 lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() { 411 if (m_dyld_ap.get() == NULL) 412 m_dyld_ap.reset(DynamicLoader::FindPlugin( 413 this, 414 m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString())); 415 return m_dyld_ap.get(); 416 } 417 418 Status ProcessKDP::WillResume() { return Status(); } 419 420 Status ProcessKDP::DoResume() { 421 Status error; 422 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 423 // Only start the async thread if we try to do any process control 424 if (!m_async_thread.IsJoinable()) 425 StartAsyncThread(); 426 427 bool resume = false; 428 429 // With KDP there is only one thread we can tell what to do 430 ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid)); 431 432 if (kernel_thread_sp) { 433 const StateType thread_resume_state = 434 kernel_thread_sp->GetTemporaryResumeState(); 435 436 if (log) 437 log->Printf("ProcessKDP::DoResume() thread_resume_state = %s", 438 StateAsCString(thread_resume_state)); 439 switch (thread_resume_state) { 440 case eStateSuspended: 441 // Nothing to do here when a thread will stay suspended we just leave the 442 // CPU mask bit set to zero for the thread 443 if (log) 444 log->Printf("ProcessKDP::DoResume() = suspended???"); 445 break; 446 447 case eStateStepping: { 448 lldb::RegisterContextSP reg_ctx_sp( 449 kernel_thread_sp->GetRegisterContext()); 450 451 if (reg_ctx_sp) { 452 if (log) 453 log->Printf( 454 "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);"); 455 reg_ctx_sp->HardwareSingleStep(true); 456 resume = true; 457 } else { 458 error.SetErrorStringWithFormat( 459 "KDP thread 0x%llx has no register context", 460 kernel_thread_sp->GetID()); 461 } 462 } break; 463 464 case eStateRunning: { 465 lldb::RegisterContextSP reg_ctx_sp( 466 kernel_thread_sp->GetRegisterContext()); 467 468 if (reg_ctx_sp) { 469 if (log) 470 log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep " 471 "(false);"); 472 reg_ctx_sp->HardwareSingleStep(false); 473 resume = true; 474 } else { 475 error.SetErrorStringWithFormat( 476 "KDP thread 0x%llx has no register context", 477 kernel_thread_sp->GetID()); 478 } 479 } break; 480 481 default: 482 // The only valid thread resume states are listed above 483 llvm_unreachable("invalid thread resume state"); 484 } 485 } 486 487 if (resume) { 488 if (log) 489 log->Printf("ProcessKDP::DoResume () sending resume"); 490 491 if (m_comm.SendRequestResume()) { 492 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue); 493 SetPrivateState(eStateRunning); 494 } else 495 error.SetErrorString("KDP resume failed"); 496 } else { 497 error.SetErrorString("kernel thread is suspended"); 498 } 499 500 return error; 501 } 502 503 lldb::ThreadSP ProcessKDP::GetKernelThread() { 504 // KDP only tells us about one thread/core. Any other threads will usually 505 // be the ones that are read from memory by the OS plug-ins. 506 507 ThreadSP thread_sp(m_kernel_thread_wp.lock()); 508 if (!thread_sp) { 509 thread_sp.reset(new ThreadKDP(*this, g_kernel_tid)); 510 m_kernel_thread_wp = thread_sp; 511 } 512 return thread_sp; 513 } 514 515 bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list, 516 ThreadList &new_thread_list) { 517 // locker will keep a mutex locked until it goes out of scope 518 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD)); 519 LLDB_LOGV(log, "pid = {0}", GetID()); 520 521 // Even though there is a CPU mask, it doesn't mean we can see each CPU 522 // individually, there is really only one. Lets call this thread 1. 523 ThreadSP thread_sp( 524 old_thread_list.FindThreadByProtocolID(g_kernel_tid, false)); 525 if (!thread_sp) 526 thread_sp = GetKernelThread(); 527 new_thread_list.AddThread(thread_sp); 528 529 return new_thread_list.GetSize(false) > 0; 530 } 531 532 void ProcessKDP::RefreshStateAfterStop() { 533 // Let all threads recover from stopping and do any clean up based on the 534 // previous thread state (if any). 535 m_thread_list.RefreshStateAfterStop(); 536 } 537 538 Status ProcessKDP::DoHalt(bool &caused_stop) { 539 Status error; 540 541 if (m_comm.IsRunning()) { 542 if (m_destroy_in_process) { 543 // If we are attempting to destroy, we need to not return an error to Halt 544 // or DoDestroy won't get called. We are also currently running, so send 545 // a process stopped event 546 SetPrivateState(eStateStopped); 547 } else { 548 error.SetErrorString("KDP cannot interrupt a running kernel"); 549 } 550 } 551 return error; 552 } 553 554 Status ProcessKDP::DoDetach(bool keep_stopped) { 555 Status error; 556 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 557 if (log) 558 log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped); 559 560 if (m_comm.IsRunning()) { 561 // We are running and we can't interrupt a running kernel, so we need to 562 // just close the connection to the kernel and hope for the best 563 } else { 564 // If we are going to keep the target stopped, then don't send the 565 // disconnect message. 566 if (!keep_stopped && m_comm.IsConnected()) { 567 const bool success = m_comm.SendRequestDisconnect(); 568 if (log) { 569 if (success) 570 log->PutCString( 571 "ProcessKDP::DoDetach() detach packet sent successfully"); 572 else 573 log->PutCString( 574 "ProcessKDP::DoDetach() connection channel shutdown failed"); 575 } 576 m_comm.Disconnect(); 577 } 578 } 579 StopAsyncThread(); 580 m_comm.Clear(); 581 582 SetPrivateState(eStateDetached); 583 ResumePrivateStateThread(); 584 585 // KillDebugserverProcess (); 586 return error; 587 } 588 589 Status ProcessKDP::DoDestroy() { 590 // For KDP there really is no difference between destroy and detach 591 bool keep_stopped = false; 592 return DoDetach(keep_stopped); 593 } 594 595 //------------------------------------------------------------------ 596 // Process Queries 597 //------------------------------------------------------------------ 598 599 bool ProcessKDP::IsAlive() { 600 return m_comm.IsConnected() && Process::IsAlive(); 601 } 602 603 //------------------------------------------------------------------ 604 // Process Memory 605 //------------------------------------------------------------------ 606 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size, 607 Status &error) { 608 uint8_t *data_buffer = (uint8_t *)buf; 609 if (m_comm.IsConnected()) { 610 const size_t max_read_size = 512; 611 size_t total_bytes_read = 0; 612 613 // Read the requested amount of memory in 512 byte chunks 614 while (total_bytes_read < size) { 615 size_t bytes_to_read_this_request = size - total_bytes_read; 616 if (bytes_to_read_this_request > max_read_size) { 617 bytes_to_read_this_request = max_read_size; 618 } 619 size_t bytes_read = m_comm.SendRequestReadMemory( 620 addr + total_bytes_read, data_buffer + total_bytes_read, 621 bytes_to_read_this_request, error); 622 total_bytes_read += bytes_read; 623 if (error.Fail() || bytes_read == 0) { 624 return total_bytes_read; 625 } 626 } 627 628 return total_bytes_read; 629 } 630 error.SetErrorString("not connected"); 631 return 0; 632 } 633 634 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size, 635 Status &error) { 636 if (m_comm.IsConnected()) 637 return m_comm.SendRequestWriteMemory(addr, buf, size, error); 638 error.SetErrorString("not connected"); 639 return 0; 640 } 641 642 lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions, 643 Status &error) { 644 error.SetErrorString( 645 "memory allocation not supported in kdp remote debugging"); 646 return LLDB_INVALID_ADDRESS; 647 } 648 649 Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) { 650 Status error; 651 error.SetErrorString( 652 "memory deallocation not supported in kdp remote debugging"); 653 return error; 654 } 655 656 Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) { 657 if (m_comm.LocalBreakpointsAreSupported()) { 658 Status error; 659 if (!bp_site->IsEnabled()) { 660 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) { 661 bp_site->SetEnabled(true); 662 bp_site->SetType(BreakpointSite::eExternal); 663 } else { 664 error.SetErrorString("KDP set breakpoint failed"); 665 } 666 } 667 return error; 668 } 669 return EnableSoftwareBreakpoint(bp_site); 670 } 671 672 Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) { 673 if (m_comm.LocalBreakpointsAreSupported()) { 674 Status error; 675 if (bp_site->IsEnabled()) { 676 BreakpointSite::Type bp_type = bp_site->GetType(); 677 if (bp_type == BreakpointSite::eExternal) { 678 if (m_destroy_in_process && m_comm.IsRunning()) { 679 // We are trying to destroy our connection and we are running 680 bp_site->SetEnabled(false); 681 } else { 682 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress())) 683 bp_site->SetEnabled(false); 684 else 685 error.SetErrorString("KDP remove breakpoint failed"); 686 } 687 } else { 688 error = DisableSoftwareBreakpoint(bp_site); 689 } 690 } 691 return error; 692 } 693 return DisableSoftwareBreakpoint(bp_site); 694 } 695 696 Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) { 697 Status error; 698 error.SetErrorString( 699 "watchpoints are not supported in kdp remote debugging"); 700 return error; 701 } 702 703 Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) { 704 Status error; 705 error.SetErrorString( 706 "watchpoints are not supported in kdp remote debugging"); 707 return error; 708 } 709 710 void ProcessKDP::Clear() { m_thread_list.Clear(); } 711 712 Status ProcessKDP::DoSignal(int signo) { 713 Status error; 714 error.SetErrorString( 715 "sending signals is not supported in kdp remote debugging"); 716 return error; 717 } 718 719 void ProcessKDP::Initialize() { 720 static llvm::once_flag g_once_flag; 721 722 llvm::call_once(g_once_flag, []() { 723 PluginManager::RegisterPlugin(GetPluginNameStatic(), 724 GetPluginDescriptionStatic(), CreateInstance, 725 DebuggerInitialize); 726 727 ProcessKDPLog::Initialize(); 728 }); 729 } 730 731 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) { 732 if (!PluginManager::GetSettingForProcessPlugin( 733 debugger, PluginProperties::GetSettingName())) { 734 const bool is_global_setting = true; 735 PluginManager::CreateSettingForProcessPlugin( 736 debugger, GetGlobalPluginProperties()->GetValueProperties(), 737 ConstString("Properties for the kdp-remote process plug-in."), 738 is_global_setting); 739 } 740 } 741 742 bool ProcessKDP::StartAsyncThread() { 743 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 744 745 if (log) 746 log->Printf("ProcessKDP::StartAsyncThread ()"); 747 748 if (m_async_thread.IsJoinable()) 749 return true; 750 751 m_async_thread = ThreadLauncher::LaunchThread( 752 "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL); 753 return m_async_thread.IsJoinable(); 754 } 755 756 void ProcessKDP::StopAsyncThread() { 757 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 758 759 if (log) 760 log->Printf("ProcessKDP::StopAsyncThread ()"); 761 762 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 763 764 // Stop the stdio thread 765 if (m_async_thread.IsJoinable()) 766 m_async_thread.Join(nullptr); 767 } 768 769 void *ProcessKDP::AsyncThread(void *arg) { 770 ProcessKDP *process = (ProcessKDP *)arg; 771 772 const lldb::pid_t pid = process->GetID(); 773 774 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 775 if (log) 776 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 777 ") thread starting...", 778 arg, pid); 779 780 ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread")); 781 EventSP event_sp; 782 const uint32_t desired_event_mask = 783 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; 784 785 if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster, 786 desired_event_mask) == 787 desired_event_mask) { 788 bool done = false; 789 while (!done) { 790 if (log) 791 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64 792 ") listener.WaitForEvent (NULL, event_sp)...", 793 pid); 794 if (listener_sp->GetEvent(event_sp, llvm::None)) { 795 uint32_t event_type = event_sp->GetType(); 796 if (log) 797 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64 798 ") Got an event of type: %d...", 799 pid, event_type); 800 801 // When we are running, poll for 1 second to try and get an exception 802 // to indicate the process has stopped. If we don't get one, check to 803 // make sure no one asked us to exit 804 bool is_running = false; 805 DataExtractor exc_reply_packet; 806 do { 807 switch (event_type) { 808 case eBroadcastBitAsyncContinue: { 809 is_running = true; 810 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds( 811 exc_reply_packet, 1 * USEC_PER_SEC)) { 812 ThreadSP thread_sp(process->GetKernelThread()); 813 if (thread_sp) { 814 lldb::RegisterContextSP reg_ctx_sp( 815 thread_sp->GetRegisterContext()); 816 if (reg_ctx_sp) 817 reg_ctx_sp->InvalidateAllRegisters(); 818 static_cast<ThreadKDP *>(thread_sp.get()) 819 ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet); 820 } 821 822 // TODO: parse the stop reply packet 823 is_running = false; 824 process->SetPrivateState(eStateStopped); 825 } else { 826 // Check to see if we are supposed to exit. There is no way to 827 // interrupt a running kernel, so all we can do is wait for an 828 // exception or detach... 829 if (listener_sp->GetEvent(event_sp, 830 std::chrono::microseconds(0))) { 831 // We got an event, go through the loop again 832 event_type = event_sp->GetType(); 833 } 834 } 835 } break; 836 837 case eBroadcastBitAsyncThreadShouldExit: 838 if (log) 839 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64 840 ") got eBroadcastBitAsyncThreadShouldExit...", 841 pid); 842 done = true; 843 is_running = false; 844 break; 845 846 default: 847 if (log) 848 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64 849 ") got unknown event 0x%8.8x", 850 pid, event_type); 851 done = true; 852 is_running = false; 853 break; 854 } 855 } while (is_running); 856 } else { 857 if (log) 858 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64 859 ") listener.WaitForEvent (NULL, event_sp) => false", 860 pid); 861 done = true; 862 } 863 } 864 } 865 866 if (log) 867 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 868 ") thread exiting...", 869 arg, pid); 870 871 process->m_async_thread.Reset(); 872 return NULL; 873 } 874 875 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed { 876 private: 877 OptionGroupOptions m_option_group; 878 OptionGroupUInt64 m_command_byte; 879 OptionGroupString m_packet_data; 880 881 virtual Options *GetOptions() { return &m_option_group; } 882 883 public: 884 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) 885 : CommandObjectParsed(interpreter, "process plugin packet send", 886 "Send a custom packet through the KDP protocol by " 887 "specifying the command byte and the packet " 888 "payload data. A packet will be sent with a " 889 "correct header and payload, and the raw result " 890 "bytes will be displayed as a string value. ", 891 NULL), 892 m_option_group(), 893 m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone, 894 "Specify the command byte to use when sending the KDP " 895 "request packet.", 896 0), 897 m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone, 898 "Specify packet payload bytes as a hex ASCII string with " 899 "no spaces or hex prefixes.", 900 NULL) { 901 m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 902 m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 903 m_option_group.Finalize(); 904 } 905 906 ~CommandObjectProcessKDPPacketSend() {} 907 908 bool DoExecute(Args &command, CommandReturnObject &result) { 909 const size_t argc = command.GetArgumentCount(); 910 if (argc == 0) { 911 if (!m_command_byte.GetOptionValue().OptionWasSet()) { 912 result.AppendError( 913 "the --command option must be set to a valid command byte"); 914 result.SetStatus(eReturnStatusFailed); 915 } else { 916 const uint64_t command_byte = 917 m_command_byte.GetOptionValue().GetUInt64Value(0); 918 if (command_byte > 0 && command_byte <= UINT8_MAX) { 919 ProcessKDP *process = 920 (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr(); 921 if (process) { 922 const StateType state = process->GetState(); 923 924 if (StateIsStoppedState(state, true)) { 925 std::vector<uint8_t> payload_bytes; 926 const char *ascii_hex_bytes_cstr = 927 m_packet_data.GetOptionValue().GetCurrentValue(); 928 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) { 929 StringExtractor extractor(ascii_hex_bytes_cstr); 930 const size_t ascii_hex_bytes_cstr_len = 931 extractor.GetStringRef().size(); 932 if (ascii_hex_bytes_cstr_len & 1) { 933 result.AppendErrorWithFormat("payload data must contain an " 934 "even number of ASCII hex " 935 "characters: '%s'", 936 ascii_hex_bytes_cstr); 937 result.SetStatus(eReturnStatusFailed); 938 return false; 939 } 940 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2); 941 if (extractor.GetHexBytes(payload_bytes, '\xdd') != 942 payload_bytes.size()) { 943 result.AppendErrorWithFormat("payload data must only contain " 944 "ASCII hex characters (no " 945 "spaces or hex prefixes): '%s'", 946 ascii_hex_bytes_cstr); 947 result.SetStatus(eReturnStatusFailed); 948 return false; 949 } 950 } 951 Status error; 952 DataExtractor reply; 953 process->GetCommunication().SendRawRequest( 954 command_byte, 955 payload_bytes.empty() ? NULL : payload_bytes.data(), 956 payload_bytes.size(), reply, error); 957 958 if (error.Success()) { 959 // Copy the binary bytes into a hex ASCII string for the result 960 StreamString packet; 961 packet.PutBytesAsRawHex8( 962 reply.GetDataStart(), reply.GetByteSize(), 963 endian::InlHostByteOrder(), endian::InlHostByteOrder()); 964 result.AppendMessage(packet.GetString()); 965 result.SetStatus(eReturnStatusSuccessFinishResult); 966 return true; 967 } else { 968 const char *error_cstr = error.AsCString(); 969 if (error_cstr && error_cstr[0]) 970 result.AppendError(error_cstr); 971 else 972 result.AppendErrorWithFormat("unknown error 0x%8.8x", 973 error.GetError()); 974 result.SetStatus(eReturnStatusFailed); 975 return false; 976 } 977 } else { 978 result.AppendErrorWithFormat("process must be stopped in order " 979 "to send KDP packets, state is %s", 980 StateAsCString(state)); 981 result.SetStatus(eReturnStatusFailed); 982 } 983 } else { 984 result.AppendError("invalid process"); 985 result.SetStatus(eReturnStatusFailed); 986 } 987 } else { 988 result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64 989 ", valid values are 1 - 255", 990 command_byte); 991 result.SetStatus(eReturnStatusFailed); 992 } 993 } 994 } else { 995 result.AppendErrorWithFormat("'%s' takes no arguments, only options.", 996 m_cmd_name.c_str()); 997 result.SetStatus(eReturnStatusFailed); 998 } 999 return false; 1000 } 1001 }; 1002 1003 class CommandObjectProcessKDPPacket : public CommandObjectMultiword { 1004 private: 1005 public: 1006 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) 1007 : CommandObjectMultiword(interpreter, "process plugin packet", 1008 "Commands that deal with KDP remote packets.", 1009 NULL) { 1010 LoadSubCommand( 1011 "send", 1012 CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter))); 1013 } 1014 1015 ~CommandObjectProcessKDPPacket() {} 1016 }; 1017 1018 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword { 1019 public: 1020 CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter) 1021 : CommandObjectMultiword( 1022 interpreter, "process plugin", 1023 "Commands for operating on a ProcessKDP process.", 1024 "process plugin <subcommand> [<subcommand-options>]") { 1025 LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket( 1026 interpreter))); 1027 } 1028 1029 ~CommandObjectMultiwordProcessKDP() {} 1030 }; 1031 1032 CommandObject *ProcessKDP::GetPluginCommandObject() { 1033 if (!m_command_sp) 1034 m_command_sp.reset(new CommandObjectMultiwordProcessKDP( 1035 GetTarget().GetDebugger().GetCommandInterpreter())); 1036 return m_command_sp.get(); 1037 } 1038