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