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 module_spec.GetFileSpec() = Symbols::LocateExecutableObjectFile (module_spec); 325 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec()) 326 Symbols::DownloadObjectAndSymbolFile (module_spec, true); 327 328 if (module_spec.GetFileSpec().Exists()) 329 { 330 ModuleSP module_sp(new Module (module_spec.GetFileSpec(), target.GetArchitecture())); 331 if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec)) 332 { 333 // Get the current target executable 334 ModuleSP exe_module_sp (target.GetExecutableModule ()); 335 336 // Make sure you don't already have the right module loaded and they will be uniqued 337 if (exe_module_sp.get() != module_sp.get()) 338 target.SetExecutableModule (module_sp, false); 339 } 340 } 341 } 342 } 343 else if (m_comm.RemoteIsDarwinKernel ()) 344 { 345 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic(); 346 if (kernel_load_addr != LLDB_INVALID_ADDRESS) 347 { 348 m_kernel_load_addr = kernel_load_addr; 349 } 350 } 351 352 // Set the thread ID 353 UpdateThreadListIfNeeded (); 354 SetID (1); 355 GetThreadList (); 356 SetPrivateState (eStateStopped); 357 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream()); 358 if (async_strm_sp) 359 { 360 const char *cstr; 361 if ((cstr = m_comm.GetKernelVersion ()) != NULL) 362 { 363 async_strm_sp->Printf ("Version: %s\n", cstr); 364 async_strm_sp->Flush(); 365 } 366 // if ((cstr = m_comm.GetImagePath ()) != NULL) 367 // { 368 // async_strm_sp->Printf ("Image Path: %s\n", cstr); 369 // async_strm_sp->Flush(); 370 // } 371 } 372 } 373 else 374 { 375 error.SetErrorString("KDP_REATTACH failed"); 376 } 377 } 378 else 379 { 380 error.SetErrorString("KDP_REATTACH failed"); 381 } 382 } 383 else 384 { 385 error.SetErrorString("invalid reply port from UDP connection"); 386 } 387 } 388 else 389 { 390 if (error.Success()) 391 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url); 392 } 393 if (error.Fail()) 394 m_comm.Disconnect(); 395 396 return error; 397 } 398 399 //---------------------------------------------------------------------- 400 // Process Control 401 //---------------------------------------------------------------------- 402 Error 403 ProcessKDP::DoLaunch (Module *exe_module, 404 ProcessLaunchInfo &launch_info) 405 { 406 Error error; 407 error.SetErrorString ("launching not supported in kdp-remote plug-in"); 408 return error; 409 } 410 411 Error 412 ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) 413 { 414 Error error; 415 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging"); 416 return error; 417 } 418 419 Error 420 ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info) 421 { 422 Error error; 423 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging"); 424 return error; 425 } 426 427 428 void 429 ProcessKDP::DidAttach (ArchSpec &process_arch) 430 { 431 Process::DidAttach(process_arch); 432 433 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS)); 434 if (log) 435 log->Printf ("ProcessKDP::DidAttach()"); 436 if (GetID() != LLDB_INVALID_PROCESS_ID) 437 { 438 uint32_t cpu = m_comm.GetCPUType(); 439 if (cpu) 440 { 441 uint32_t sub = m_comm.GetCPUSubtype(); 442 process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 443 } 444 } 445 } 446 447 addr_t 448 ProcessKDP::GetImageInfoAddress() 449 { 450 return m_kernel_load_addr; 451 } 452 453 lldb_private::DynamicLoader * 454 ProcessKDP::GetDynamicLoader () 455 { 456 if (m_dyld_ap.get() == NULL) 457 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString())); 458 return m_dyld_ap.get(); 459 } 460 461 Error 462 ProcessKDP::WillResume () 463 { 464 return Error(); 465 } 466 467 Error 468 ProcessKDP::DoResume () 469 { 470 Error error; 471 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS)); 472 // Only start the async thread if we try to do any process control 473 if (!m_async_thread.IsJoinable()) 474 StartAsyncThread(); 475 476 bool resume = false; 477 478 // With KDP there is only one thread we can tell what to do 479 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid)); 480 481 if (kernel_thread_sp) 482 { 483 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState(); 484 485 if (log) 486 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state)); 487 switch (thread_resume_state) 488 { 489 case eStateSuspended: 490 // Nothing to do here when a thread will stay suspended 491 // we just leave the CPU mask bit set to zero for the thread 492 if (log) 493 log->Printf ("ProcessKDP::DoResume() = suspended???"); 494 break; 495 496 case eStateStepping: 497 { 498 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext()); 499 500 if (reg_ctx_sp) 501 { 502 if (log) 503 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);"); 504 reg_ctx_sp->HardwareSingleStep (true); 505 resume = true; 506 } 507 else 508 { 509 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID()); 510 } 511 } 512 break; 513 514 case eStateRunning: 515 { 516 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext()); 517 518 if (reg_ctx_sp) 519 { 520 if (log) 521 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);"); 522 reg_ctx_sp->HardwareSingleStep (false); 523 resume = true; 524 } 525 else 526 { 527 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID()); 528 } 529 } 530 break; 531 532 default: 533 // The only valid thread resume states are listed above 534 assert (!"invalid thread resume state"); 535 break; 536 } 537 } 538 539 if (resume) 540 { 541 if (log) 542 log->Printf ("ProcessKDP::DoResume () sending resume"); 543 544 if (m_comm.SendRequestResume ()) 545 { 546 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue); 547 SetPrivateState(eStateRunning); 548 } 549 else 550 error.SetErrorString ("KDP resume failed"); 551 } 552 else 553 { 554 error.SetErrorString ("kernel thread is suspended"); 555 } 556 557 return error; 558 } 559 560 lldb::ThreadSP 561 ProcessKDP::GetKernelThread() 562 { 563 // KDP only tells us about one thread/core. Any other threads will usually 564 // be the ones that are read from memory by the OS plug-ins. 565 566 ThreadSP thread_sp (m_kernel_thread_wp.lock()); 567 if (!thread_sp) 568 { 569 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid)); 570 m_kernel_thread_wp = thread_sp; 571 } 572 return thread_sp; 573 } 574 575 576 577 578 bool 579 ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 580 { 581 // locker will keep a mutex locked until it goes out of scope 582 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD)); 583 if (log && log->GetMask().Test(KDP_LOG_VERBOSE)) 584 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID()); 585 586 // Even though there is a CPU mask, it doesn't mean we can see each CPU 587 // individually, there is really only one. Lets call this thread 1. 588 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false)); 589 if (!thread_sp) 590 thread_sp = GetKernelThread (); 591 new_thread_list.AddThread(thread_sp); 592 593 return new_thread_list.GetSize(false) > 0; 594 } 595 596 void 597 ProcessKDP::RefreshStateAfterStop () 598 { 599 // Let all threads recover from stopping and do any clean up based 600 // on the previous thread state (if any). 601 m_thread_list.RefreshStateAfterStop(); 602 } 603 604 Error 605 ProcessKDP::DoHalt (bool &caused_stop) 606 { 607 Error error; 608 609 if (m_comm.IsRunning()) 610 { 611 if (m_destroy_in_process) 612 { 613 // If we are attemping to destroy, we need to not return an error to 614 // Halt or DoDestroy won't get called. 615 // We are also currently running, so send a process stopped event 616 SetPrivateState (eStateStopped); 617 } 618 else 619 { 620 error.SetErrorString ("KDP cannot interrupt a running kernel"); 621 } 622 } 623 return error; 624 } 625 626 Error 627 ProcessKDP::DoDetach(bool keep_stopped) 628 { 629 Error error; 630 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 631 if (log) 632 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped); 633 634 if (m_comm.IsRunning()) 635 { 636 // We are running and we can't interrupt a running kernel, so we need 637 // to just close the connection to the kernel and hope for the best 638 } 639 else 640 { 641 // If we are going to keep the target stopped, then don't send the disconnect message. 642 if (!keep_stopped && m_comm.IsConnected()) 643 { 644 const bool success = m_comm.SendRequestDisconnect(); 645 if (log) 646 { 647 if (success) 648 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully"); 649 else 650 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed"); 651 } 652 m_comm.Disconnect (); 653 } 654 } 655 StopAsyncThread (); 656 m_comm.Clear(); 657 658 SetPrivateState (eStateDetached); 659 ResumePrivateStateThread(); 660 661 //KillDebugserverProcess (); 662 return error; 663 } 664 665 Error 666 ProcessKDP::DoDestroy () 667 { 668 // For KDP there really is no difference between destroy and detach 669 bool keep_stopped = false; 670 return DoDetach(keep_stopped); 671 } 672 673 //------------------------------------------------------------------ 674 // Process Queries 675 //------------------------------------------------------------------ 676 677 bool 678 ProcessKDP::IsAlive () 679 { 680 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 681 } 682 683 //------------------------------------------------------------------ 684 // Process Memory 685 //------------------------------------------------------------------ 686 size_t 687 ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 688 { 689 uint8_t *data_buffer = (uint8_t *) buf; 690 if (m_comm.IsConnected()) 691 { 692 const size_t max_read_size = 512; 693 size_t total_bytes_read = 0; 694 695 // Read the requested amount of memory in 512 byte chunks 696 while (total_bytes_read < size) 697 { 698 size_t bytes_to_read_this_request = size - total_bytes_read; 699 if (bytes_to_read_this_request > max_read_size) 700 { 701 bytes_to_read_this_request = max_read_size; 702 } 703 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read, 704 data_buffer + total_bytes_read, 705 bytes_to_read_this_request, error); 706 total_bytes_read += bytes_read; 707 if (error.Fail() || bytes_read == 0) 708 { 709 return total_bytes_read; 710 } 711 } 712 713 return total_bytes_read; 714 } 715 error.SetErrorString ("not connected"); 716 return 0; 717 } 718 719 size_t 720 ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 721 { 722 if (m_comm.IsConnected()) 723 return m_comm.SendRequestWriteMemory (addr, buf, size, error); 724 error.SetErrorString ("not connected"); 725 return 0; 726 } 727 728 lldb::addr_t 729 ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 730 { 731 error.SetErrorString ("memory allocation not suppported in kdp remote debugging"); 732 return LLDB_INVALID_ADDRESS; 733 } 734 735 Error 736 ProcessKDP::DoDeallocateMemory (lldb::addr_t addr) 737 { 738 Error error; 739 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging"); 740 return error; 741 } 742 743 Error 744 ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site) 745 { 746 if (m_comm.LocalBreakpointsAreSupported ()) 747 { 748 Error error; 749 if (!bp_site->IsEnabled()) 750 { 751 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) 752 { 753 bp_site->SetEnabled(true); 754 bp_site->SetType (BreakpointSite::eExternal); 755 } 756 else 757 { 758 error.SetErrorString ("KDP set breakpoint failed"); 759 } 760 } 761 return error; 762 } 763 return EnableSoftwareBreakpoint (bp_site); 764 } 765 766 Error 767 ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site) 768 { 769 if (m_comm.LocalBreakpointsAreSupported ()) 770 { 771 Error error; 772 if (bp_site->IsEnabled()) 773 { 774 BreakpointSite::Type bp_type = bp_site->GetType(); 775 if (bp_type == BreakpointSite::eExternal) 776 { 777 if (m_destroy_in_process && m_comm.IsRunning()) 778 { 779 // We are trying to destroy our connection and we are running 780 bp_site->SetEnabled(false); 781 } 782 else 783 { 784 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress())) 785 bp_site->SetEnabled(false); 786 else 787 error.SetErrorString ("KDP remove breakpoint failed"); 788 } 789 } 790 else 791 { 792 error = DisableSoftwareBreakpoint (bp_site); 793 } 794 } 795 return error; 796 } 797 return DisableSoftwareBreakpoint (bp_site); 798 } 799 800 Error 801 ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify) 802 { 803 Error error; 804 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging"); 805 return error; 806 } 807 808 Error 809 ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify) 810 { 811 Error error; 812 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging"); 813 return error; 814 } 815 816 void 817 ProcessKDP::Clear() 818 { 819 m_thread_list.Clear(); 820 } 821 822 Error 823 ProcessKDP::DoSignal (int signo) 824 { 825 Error error; 826 error.SetErrorString ("sending signals is not suppported in kdp remote debugging"); 827 return error; 828 } 829 830 void 831 ProcessKDP::Initialize() 832 { 833 static std::once_flag g_once_flag; 834 835 std::call_once(g_once_flag, []() 836 { 837 PluginManager::RegisterPlugin (GetPluginNameStatic(), 838 GetPluginDescriptionStatic(), 839 CreateInstance, 840 DebuggerInitialize); 841 842 Log::Callbacks log_callbacks = { 843 ProcessKDPLog::DisableLog, 844 ProcessKDPLog::EnableLog, 845 ProcessKDPLog::ListLogCategories 846 }; 847 848 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks); 849 }); 850 } 851 852 void 853 ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger) 854 { 855 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName())) 856 { 857 const bool is_global_setting = true; 858 PluginManager::CreateSettingForProcessPlugin (debugger, 859 GetGlobalPluginProperties()->GetValueProperties(), 860 ConstString ("Properties for the kdp-remote process plug-in."), 861 is_global_setting); 862 } 863 } 864 865 bool 866 ProcessKDP::StartAsyncThread () 867 { 868 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 869 870 if (log) 871 log->Printf ("ProcessKDP::StartAsyncThread ()"); 872 873 if (m_async_thread.IsJoinable()) 874 return true; 875 876 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL); 877 return m_async_thread.IsJoinable(); 878 } 879 880 void 881 ProcessKDP::StopAsyncThread () 882 { 883 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 884 885 if (log) 886 log->Printf ("ProcessKDP::StopAsyncThread ()"); 887 888 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 889 890 // Stop the stdio thread 891 if (m_async_thread.IsJoinable()) 892 m_async_thread.Join(nullptr); 893 } 894 895 896 void * 897 ProcessKDP::AsyncThread (void *arg) 898 { 899 ProcessKDP *process = (ProcessKDP*) arg; 900 901 const lldb::pid_t pid = process->GetID(); 902 903 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS)); 904 if (log) 905 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid); 906 907 Listener listener ("ProcessKDP::AsyncThread"); 908 EventSP event_sp; 909 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 910 eBroadcastBitAsyncThreadShouldExit; 911 912 913 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 914 { 915 bool done = false; 916 while (!done) 917 { 918 if (log) 919 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", 920 pid); 921 if (listener.WaitForEvent (NULL, event_sp)) 922 { 923 uint32_t event_type = event_sp->GetType(); 924 if (log) 925 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...", 926 pid, 927 event_type); 928 929 // When we are running, poll for 1 second to try and get an exception 930 // to indicate the process has stopped. If we don't get one, check to 931 // make sure no one asked us to exit 932 bool is_running = false; 933 DataExtractor exc_reply_packet; 934 do 935 { 936 switch (event_type) 937 { 938 case eBroadcastBitAsyncContinue: 939 { 940 is_running = true; 941 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC)) 942 { 943 ThreadSP thread_sp (process->GetKernelThread()); 944 if (thread_sp) 945 { 946 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext()); 947 if (reg_ctx_sp) 948 reg_ctx_sp->InvalidateAllRegisters(); 949 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet); 950 } 951 952 // TODO: parse the stop reply packet 953 is_running = false; 954 process->SetPrivateState(eStateStopped); 955 } 956 else 957 { 958 // Check to see if we are supposed to exit. There is no way to 959 // interrupt a running kernel, so all we can do is wait for an 960 // exception or detach... 961 if (listener.GetNextEvent(event_sp)) 962 { 963 // We got an event, go through the loop again 964 event_type = event_sp->GetType(); 965 } 966 } 967 } 968 break; 969 970 case eBroadcastBitAsyncThreadShouldExit: 971 if (log) 972 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", 973 pid); 974 done = true; 975 is_running = false; 976 break; 977 978 default: 979 if (log) 980 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x", 981 pid, 982 event_type); 983 done = true; 984 is_running = false; 985 break; 986 } 987 } while (is_running); 988 } 989 else 990 { 991 if (log) 992 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", 993 pid); 994 done = true; 995 } 996 } 997 } 998 999 if (log) 1000 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...", 1001 arg, 1002 pid); 1003 1004 process->m_async_thread.Reset(); 1005 return NULL; 1006 } 1007 1008 1009 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed 1010 { 1011 private: 1012 1013 OptionGroupOptions m_option_group; 1014 OptionGroupUInt64 m_command_byte; 1015 OptionGroupString m_packet_data; 1016 1017 virtual Options * 1018 GetOptions () 1019 { 1020 return &m_option_group; 1021 } 1022 1023 1024 public: 1025 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) : 1026 CommandObjectParsed (interpreter, 1027 "process plugin packet send", 1028 "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. ", 1029 NULL), 1030 m_option_group (interpreter), 1031 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), 1032 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) 1033 { 1034 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 1035 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 1036 m_option_group.Finalize(); 1037 } 1038 1039 ~CommandObjectProcessKDPPacketSend () 1040 { 1041 } 1042 1043 bool 1044 DoExecute (Args& command, CommandReturnObject &result) 1045 { 1046 const size_t argc = command.GetArgumentCount(); 1047 if (argc == 0) 1048 { 1049 if (!m_command_byte.GetOptionValue().OptionWasSet()) 1050 { 1051 result.AppendError ("the --command option must be set to a valid command byte"); 1052 result.SetStatus (eReturnStatusFailed); 1053 } 1054 else 1055 { 1056 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0); 1057 if (command_byte > 0 && command_byte <= UINT8_MAX) 1058 { 1059 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr(); 1060 if (process) 1061 { 1062 const StateType state = process->GetState(); 1063 1064 if (StateIsStoppedState (state, true)) 1065 { 1066 std::vector<uint8_t> payload_bytes; 1067 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue(); 1068 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) 1069 { 1070 StringExtractor extractor(ascii_hex_bytes_cstr); 1071 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size(); 1072 if (ascii_hex_bytes_cstr_len & 1) 1073 { 1074 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr); 1075 result.SetStatus (eReturnStatusFailed); 1076 return false; 1077 } 1078 payload_bytes.resize(ascii_hex_bytes_cstr_len/2); 1079 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size()) 1080 { 1081 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr); 1082 result.SetStatus (eReturnStatusFailed); 1083 return false; 1084 } 1085 } 1086 Error error; 1087 DataExtractor reply; 1088 process->GetCommunication().SendRawRequest (command_byte, 1089 payload_bytes.empty() ? NULL : payload_bytes.data(), 1090 payload_bytes.size(), 1091 reply, 1092 error); 1093 1094 if (error.Success()) 1095 { 1096 // Copy the binary bytes into a hex ASCII string for the result 1097 StreamString packet; 1098 packet.PutBytesAsRawHex8(reply.GetDataStart(), 1099 reply.GetByteSize(), 1100 lldb::endian::InlHostByteOrder(), 1101 lldb::endian::InlHostByteOrder()); 1102 result.AppendMessage(packet.GetString().c_str()); 1103 result.SetStatus (eReturnStatusSuccessFinishResult); 1104 return true; 1105 } 1106 else 1107 { 1108 const char *error_cstr = error.AsCString(); 1109 if (error_cstr && error_cstr[0]) 1110 result.AppendError (error_cstr); 1111 else 1112 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError()); 1113 result.SetStatus (eReturnStatusFailed); 1114 return false; 1115 } 1116 } 1117 else 1118 { 1119 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state)); 1120 result.SetStatus (eReturnStatusFailed); 1121 } 1122 } 1123 else 1124 { 1125 result.AppendError ("invalid process"); 1126 result.SetStatus (eReturnStatusFailed); 1127 } 1128 } 1129 else 1130 { 1131 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte); 1132 result.SetStatus (eReturnStatusFailed); 1133 } 1134 } 1135 } 1136 else 1137 { 1138 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str()); 1139 result.SetStatus (eReturnStatusFailed); 1140 } 1141 return false; 1142 } 1143 }; 1144 1145 class CommandObjectProcessKDPPacket : public CommandObjectMultiword 1146 { 1147 private: 1148 1149 public: 1150 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) : 1151 CommandObjectMultiword (interpreter, 1152 "process plugin packet", 1153 "Commands that deal with KDP remote packets.", 1154 NULL) 1155 { 1156 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter))); 1157 } 1158 1159 ~CommandObjectProcessKDPPacket () 1160 { 1161 } 1162 }; 1163 1164 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword 1165 { 1166 public: 1167 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) : 1168 CommandObjectMultiword (interpreter, 1169 "process plugin", 1170 "A set of commands for operating on a ProcessKDP process.", 1171 "process plugin <subcommand> [<subcommand-options>]") 1172 { 1173 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter))); 1174 } 1175 1176 ~CommandObjectMultiwordProcessKDP () 1177 { 1178 } 1179 }; 1180 1181 CommandObject * 1182 ProcessKDP::GetPluginCommandObject() 1183 { 1184 if (!m_command_sp) 1185 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter())); 1186 return m_command_sp.get(); 1187 } 1188 1189