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