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