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