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