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