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