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