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