ProcessKDP.cpp revision 863aa28adf536c9c008e1590f25da662431d6f13
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 389 if (log) 390 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state)); 391 switch (thread_resume_state) 392 { 393 case eStateSuspended: 394 // Nothing to do here when a thread will stay suspended 395 // we just leave the CPU mask bit set to zero for the thread 396 if (log) 397 log->Printf ("ProcessKDP::DoResume() = suspended???"); 398 break; 399 400 case eStateStepping: 401 { 402 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext()); 403 404 if (reg_ctx_sp) 405 { 406 if (log) 407 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);"); 408 reg_ctx_sp->HardwareSingleStep (true); 409 resume = true; 410 } 411 else 412 { 413 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID()); 414 } 415 } 416 break; 417 418 case eStateRunning: 419 { 420 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext()); 421 422 if (reg_ctx_sp) 423 { 424 if (log) 425 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);"); 426 reg_ctx_sp->HardwareSingleStep (false); 427 resume = true; 428 } 429 else 430 { 431 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID()); 432 } 433 } 434 break; 435 436 default: 437 // The only valid thread resume states are listed above 438 assert (!"invalid thread resume state"); 439 break; 440 } 441 } 442 443 if (resume) 444 { 445 if (log) 446 log->Printf ("ProcessKDP::DoResume () sending resume"); 447 448 if (m_comm.SendRequestResume ()) 449 { 450 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue); 451 SetPrivateState(eStateRunning); 452 } 453 else 454 error.SetErrorString ("KDP resume failed"); 455 } 456 else 457 { 458 error.SetErrorString ("kernel thread is suspended"); 459 } 460 461 return error; 462} 463 464lldb::ThreadSP 465ProcessKDP::GetKernelThread() 466{ 467 // KDP only tells us about one thread/core. Any other threads will usually 468 // be the ones that are read from memory by the OS plug-ins. 469 470 ThreadSP thread_sp (m_kernel_thread_wp.lock()); 471 if (!thread_sp) 472 { 473 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid)); 474 m_kernel_thread_wp = thread_sp; 475 } 476 return thread_sp; 477} 478 479 480 481 482bool 483ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 484{ 485 // locker will keep a mutex locked until it goes out of scope 486 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD)); 487 if (log && log->GetMask().Test(KDP_LOG_VERBOSE)) 488 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID()); 489 490 // Even though there is a CPU mask, it doesn't mean we can see each CPU 491 // indivudually, there is really only one. Lets call this thread 1. 492 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false)); 493 if (!thread_sp) 494 thread_sp = GetKernelThread (); 495 new_thread_list.AddThread(thread_sp); 496 497 return new_thread_list.GetSize(false) > 0; 498} 499 500void 501ProcessKDP::RefreshStateAfterStop () 502{ 503 // Let all threads recover from stopping and do any clean up based 504 // on the previous thread state (if any). 505 m_thread_list.RefreshStateAfterStop(); 506} 507 508Error 509ProcessKDP::DoHalt (bool &caused_stop) 510{ 511 Error error; 512 513 if (m_comm.IsRunning()) 514 { 515 if (m_destroy_in_process) 516 { 517 // If we are attemping to destroy, we need to not return an error to 518 // Halt or DoDestroy won't get called. 519 // We are also currently running, so send a process stopped event 520 SetPrivateState (eStateStopped); 521 } 522 else 523 { 524 error.SetErrorString ("KDP cannot interrupt a running kernel"); 525 } 526 } 527 return error; 528} 529 530Error 531ProcessKDP::DoDetach(bool keep_stopped) 532{ 533 Error error; 534 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 535 if (log) 536 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped); 537 538 if (m_comm.IsRunning()) 539 { 540 // We are running and we can't interrupt a running kernel, so we need 541 // to just close the connection to the kernel and hope for the best 542 } 543 else 544 { 545 DisableAllBreakpointSites (); 546 547 m_thread_list.DiscardThreadPlans(); 548 549 // If we are going to keep the target stopped, then don't send the disconnect message. 550 if (!keep_stopped && m_comm.IsConnected()) 551 { 552 const bool success = m_comm.SendRequestDisconnect(); 553 if (log) 554 { 555 if (success) 556 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully"); 557 else 558 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed"); 559 } 560 m_comm.Disconnect (); 561 } 562 } 563 StopAsyncThread (); 564 m_comm.Clear(); 565 566 SetPrivateState (eStateDetached); 567 ResumePrivateStateThread(); 568 569 //KillDebugserverProcess (); 570 return error; 571} 572 573Error 574ProcessKDP::DoDestroy () 575{ 576 // For KDP there really is no difference between destroy and detach 577 bool keep_stopped = false; 578 return DoDetach(keep_stopped); 579} 580 581//------------------------------------------------------------------ 582// Process Queries 583//------------------------------------------------------------------ 584 585bool 586ProcessKDP::IsAlive () 587{ 588 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 589} 590 591//------------------------------------------------------------------ 592// Process Memory 593//------------------------------------------------------------------ 594size_t 595ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 596{ 597 if (m_comm.IsConnected()) 598 return m_comm.SendRequestReadMemory (addr, buf, size, error); 599 error.SetErrorString ("not connected"); 600 return 0; 601} 602 603size_t 604ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 605{ 606 if (m_comm.IsConnected()) 607 return m_comm.SendRequestWriteMemory (addr, buf, size, error); 608 error.SetErrorString ("not connected"); 609 return 0; 610} 611 612lldb::addr_t 613ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 614{ 615 error.SetErrorString ("memory allocation not suppported in kdp remote debugging"); 616 return LLDB_INVALID_ADDRESS; 617} 618 619Error 620ProcessKDP::DoDeallocateMemory (lldb::addr_t addr) 621{ 622 Error error; 623 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging"); 624 return error; 625} 626 627Error 628ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site) 629{ 630 if (m_comm.LocalBreakpointsAreSupported ()) 631 { 632 Error error; 633 if (!bp_site->IsEnabled()) 634 { 635 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) 636 { 637 bp_site->SetEnabled(true); 638 bp_site->SetType (BreakpointSite::eExternal); 639 } 640 else 641 { 642 error.SetErrorString ("KDP set breakpoint failed"); 643 } 644 } 645 return error; 646 } 647 return EnableSoftwareBreakpoint (bp_site); 648} 649 650Error 651ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site) 652{ 653 if (m_comm.LocalBreakpointsAreSupported ()) 654 { 655 Error error; 656 if (bp_site->IsEnabled()) 657 { 658 BreakpointSite::Type bp_type = bp_site->GetType(); 659 if (bp_type == BreakpointSite::eExternal) 660 { 661 if (m_destroy_in_process && m_comm.IsRunning()) 662 { 663 // We are trying to destroy our connection and we are running 664 bp_site->SetEnabled(false); 665 } 666 else 667 { 668 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress())) 669 bp_site->SetEnabled(false); 670 else 671 error.SetErrorString ("KDP remove breakpoint failed"); 672 } 673 } 674 else 675 { 676 error = DisableSoftwareBreakpoint (bp_site); 677 } 678 } 679 return error; 680 } 681 return DisableSoftwareBreakpoint (bp_site); 682} 683 684Error 685ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify) 686{ 687 Error error; 688 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging"); 689 return error; 690} 691 692Error 693ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify) 694{ 695 Error error; 696 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging"); 697 return error; 698} 699 700void 701ProcessKDP::Clear() 702{ 703 m_thread_list.Clear(); 704} 705 706Error 707ProcessKDP::DoSignal (int signo) 708{ 709 Error error; 710 error.SetErrorString ("sending signals is not suppported in kdp remote debugging"); 711 return error; 712} 713 714void 715ProcessKDP::Initialize() 716{ 717 static bool g_initialized = false; 718 719 if (g_initialized == false) 720 { 721 g_initialized = true; 722 PluginManager::RegisterPlugin (GetPluginNameStatic(), 723 GetPluginDescriptionStatic(), 724 CreateInstance); 725 726 Log::Callbacks log_callbacks = { 727 ProcessKDPLog::DisableLog, 728 ProcessKDPLog::EnableLog, 729 ProcessKDPLog::ListLogCategories 730 }; 731 732 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks); 733 } 734} 735 736bool 737ProcessKDP::StartAsyncThread () 738{ 739 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 740 741 if (log) 742 log->Printf ("ProcessKDP::StartAsyncThread ()"); 743 744 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 745 return true; 746 747 m_async_thread = Host::ThreadCreate ("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL); 748 return IS_VALID_LLDB_HOST_THREAD(m_async_thread); 749} 750 751void 752ProcessKDP::StopAsyncThread () 753{ 754 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS)); 755 756 if (log) 757 log->Printf ("ProcessKDP::StopAsyncThread ()"); 758 759 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 760 761 // Stop the stdio thread 762 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 763 { 764 Host::ThreadJoin (m_async_thread, NULL, NULL); 765 m_async_thread = LLDB_INVALID_HOST_THREAD; 766 } 767} 768 769 770void * 771ProcessKDP::AsyncThread (void *arg) 772{ 773 ProcessKDP *process = (ProcessKDP*) arg; 774 775 const lldb::pid_t pid = process->GetID(); 776 777 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS)); 778 if (log) 779 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid); 780 781 Listener listener ("ProcessKDP::AsyncThread"); 782 EventSP event_sp; 783 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 784 eBroadcastBitAsyncThreadShouldExit; 785 786 787 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 788 { 789 bool done = false; 790 while (!done) 791 { 792 if (log) 793 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", 794 pid); 795 if (listener.WaitForEvent (NULL, event_sp)) 796 { 797 uint32_t event_type = event_sp->GetType(); 798 if (log) 799 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...", 800 pid, 801 event_type); 802 803 // When we are running, poll for 1 second to try and get an exception 804 // to indicate the process has stopped. If we don't get one, check to 805 // make sure no one asked us to exit 806 bool is_running = false; 807 DataExtractor exc_reply_packet; 808 do 809 { 810 switch (event_type) 811 { 812 case eBroadcastBitAsyncContinue: 813 { 814 is_running = true; 815 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC)) 816 { 817 ThreadSP thread_sp (process->GetKernelThread()); 818 if (thread_sp) 819 { 820 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext()); 821 if (reg_ctx_sp) 822 reg_ctx_sp->InvalidateAllRegisters(); 823 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet); 824 } 825 826 // TODO: parse the stop reply packet 827 is_running = false; 828 process->SetPrivateState(eStateStopped); 829 } 830 else 831 { 832 // Check to see if we are supposed to exit. There is no way to 833 // interrupt a running kernel, so all we can do is wait for an 834 // exception or detach... 835 if (listener.GetNextEvent(event_sp)) 836 { 837 // We got an event, go through the loop again 838 event_type = event_sp->GetType(); 839 } 840 } 841 } 842 break; 843 844 case eBroadcastBitAsyncThreadShouldExit: 845 if (log) 846 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", 847 pid); 848 done = true; 849 is_running = false; 850 break; 851 852 default: 853 if (log) 854 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x", 855 pid, 856 event_type); 857 done = true; 858 is_running = false; 859 break; 860 } 861 } while (is_running); 862 } 863 else 864 { 865 if (log) 866 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", 867 pid); 868 done = true; 869 } 870 } 871 } 872 873 if (log) 874 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...", 875 arg, 876 pid); 877 878 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 879 return NULL; 880} 881 882 883class CommandObjectProcessKDPPacketSend : public CommandObjectParsed 884{ 885private: 886 887 OptionGroupOptions m_option_group; 888 OptionGroupUInt64 m_command_byte; 889 OptionGroupString m_packet_data; 890 891 virtual Options * 892 GetOptions () 893 { 894 return &m_option_group; 895 } 896 897 898public: 899 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) : 900 CommandObjectParsed (interpreter, 901 "process plugin packet send", 902 "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. ", 903 NULL), 904 m_option_group (interpreter), 905 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), 906 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) 907 { 908 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 909 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 910 m_option_group.Finalize(); 911 } 912 913 ~CommandObjectProcessKDPPacketSend () 914 { 915 } 916 917 bool 918 DoExecute (Args& command, CommandReturnObject &result) 919 { 920 const size_t argc = command.GetArgumentCount(); 921 if (argc == 0) 922 { 923 if (!m_command_byte.GetOptionValue().OptionWasSet()) 924 { 925 result.AppendError ("the --command option must be set to a valid command byte"); 926 result.SetStatus (eReturnStatusFailed); 927 } 928 else 929 { 930 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0); 931 if (command_byte > 0 && command_byte <= UINT8_MAX) 932 { 933 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr(); 934 if (process) 935 { 936 const StateType state = process->GetState(); 937 938 if (StateIsStoppedState (state, true)) 939 { 940 std::vector<uint8_t> payload_bytes; 941 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue(); 942 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) 943 { 944 StringExtractor extractor(ascii_hex_bytes_cstr); 945 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size(); 946 if (ascii_hex_bytes_cstr_len & 1) 947 { 948 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr); 949 result.SetStatus (eReturnStatusFailed); 950 return false; 951 } 952 payload_bytes.resize(ascii_hex_bytes_cstr_len/2); 953 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size()) 954 { 955 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr); 956 result.SetStatus (eReturnStatusFailed); 957 return false; 958 } 959 } 960 Error error; 961 DataExtractor reply; 962 process->GetCommunication().SendRawRequest (command_byte, 963 payload_bytes.empty() ? NULL : payload_bytes.data(), 964 payload_bytes.size(), 965 reply, 966 error); 967 968 if (error.Success()) 969 { 970 // Copy the binary bytes into a hex ASCII string for the result 971 StreamString packet; 972 packet.PutBytesAsRawHex8(reply.GetDataStart(), 973 reply.GetByteSize(), 974 lldb::endian::InlHostByteOrder(), 975 lldb::endian::InlHostByteOrder()); 976 result.AppendMessage(packet.GetString().c_str()); 977 result.SetStatus (eReturnStatusSuccessFinishResult); 978 return true; 979 } 980 else 981 { 982 const char *error_cstr = error.AsCString(); 983 if (error_cstr && error_cstr[0]) 984 result.AppendError (error_cstr); 985 else 986 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError()); 987 result.SetStatus (eReturnStatusFailed); 988 return false; 989 } 990 } 991 else 992 { 993 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state)); 994 result.SetStatus (eReturnStatusFailed); 995 } 996 } 997 else 998 { 999 result.AppendError ("invalid process"); 1000 result.SetStatus (eReturnStatusFailed); 1001 } 1002 } 1003 else 1004 { 1005 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte); 1006 result.SetStatus (eReturnStatusFailed); 1007 } 1008 } 1009 } 1010 else 1011 { 1012 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str()); 1013 result.SetStatus (eReturnStatusFailed); 1014 } 1015 return false; 1016 } 1017}; 1018 1019class CommandObjectProcessKDPPacket : public CommandObjectMultiword 1020{ 1021private: 1022 1023public: 1024 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) : 1025 CommandObjectMultiword (interpreter, 1026 "process plugin packet", 1027 "Commands that deal with KDP remote packets.", 1028 NULL) 1029 { 1030 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter))); 1031 } 1032 1033 ~CommandObjectProcessKDPPacket () 1034 { 1035 } 1036}; 1037 1038class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword 1039{ 1040public: 1041 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) : 1042 CommandObjectMultiword (interpreter, 1043 "process plugin", 1044 "A set of commands for operating on a ProcessKDP process.", 1045 "process plugin <subcommand> [<subcommand-options>]") 1046 { 1047 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter))); 1048 } 1049 1050 ~CommandObjectMultiwordProcessKDP () 1051 { 1052 } 1053}; 1054 1055CommandObject * 1056ProcessKDP::GetPluginCommandObject() 1057{ 1058 if (!m_command_sp) 1059 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter())); 1060 return m_command_sp.get(); 1061} 1062 1063