1 //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
17 // Other libraries and framework includes
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleSpec.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/UUID.h"
24 #include "lldb/Host/ConnectionFileDescriptor.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/Symbols.h"
27 #include "lldb/Host/ThreadLauncher.h"
28 #include "lldb/Host/common/TCPSocket.h"
29 #include "lldb/Interpreter/CommandInterpreter.h"
30 #include "lldb/Interpreter/CommandObject.h"
31 #include "lldb/Interpreter/CommandObjectMultiword.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/Interpreter/OptionGroupString.h"
34 #include "lldb/Interpreter/OptionGroupUInt64.h"
35 #include "lldb/Interpreter/OptionValueProperties.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Target/RegisterContext.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Thread.h"
40 #include "lldb/Utility/StringExtractor.h"
42 #define USEC_PER_SEC 1000000
45 #include "ProcessKDP.h"
46 #include "ProcessKDPLog.h"
47 #include "ThreadKDP.h"
48 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
49 #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
52 using namespace lldb_private;
56 static PropertyDefinition
59 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 5, NULL, NULL, "Specify the default packet timeout in seconds." },
60 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
65 ePropertyPacketTimeout
68 class PluginProperties : public Properties
75 return ProcessKDP::GetPluginNameStatic();
81 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
82 m_collection_sp->Initialize(g_properties);
93 const uint32_t idx = ePropertyPacketTimeout;
94 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
98 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
100 static const ProcessKDPPropertiesSP &
101 GetGlobalPluginProperties()
103 static ProcessKDPPropertiesSP g_settings_sp;
105 g_settings_sp.reset (new PluginProperties ());
106 return g_settings_sp;
109 } // anonymous namespace end
111 static const lldb::tid_t g_kernel_tid = 1;
114 ProcessKDP::GetPluginNameStatic()
116 static ConstString g_name("kdp-remote");
121 ProcessKDP::GetPluginDescriptionStatic()
123 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
127 ProcessKDP::Terminate()
129 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
134 ProcessKDP::CreateInstance (TargetSP target_sp,
136 const FileSpec *crash_file_path)
138 lldb::ProcessSP process_sp;
139 if (crash_file_path == NULL)
140 process_sp.reset(new ProcessKDP (target_sp, listener));
145 ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name)
147 if (plugin_specified_by_name)
150 // For now we are just making sure the file exists for a given module
151 Module *exe_module = target_sp->GetExecutableModulePointer();
154 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
155 switch (triple_ref.getOS())
157 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
158 case llvm::Triple::MacOSX: // For desktop targets
159 case llvm::Triple::IOS: // For arm targets
160 case llvm::Triple::TvOS:
161 case llvm::Triple::WatchOS:
162 if (triple_ref.getVendor() == llvm::Triple::Apple)
164 ObjectFile *exe_objfile = exe_module->GetObjectFile();
165 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
166 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
178 //----------------------------------------------------------------------
179 // ProcessKDP constructor
180 //----------------------------------------------------------------------
181 ProcessKDP::ProcessKDP(TargetSP target_sp, Listener &listener) :
182 Process (target_sp, listener),
183 m_comm("lldb.process.kdp-remote.communication"),
184 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
185 m_dyld_plugin_name (),
186 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
190 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
191 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
192 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
193 if (timeout_seconds > 0)
194 m_comm.SetPacketTimeout(timeout_seconds);
197 //----------------------------------------------------------------------
199 //----------------------------------------------------------------------
200 ProcessKDP::~ProcessKDP()
203 // We need to call finalize on the process before destroying ourselves
204 // to make sure all of the broadcaster cleanup goes as planned. If we
205 // destruct this class, then Process::~Process() might have problems
206 // trying to fully destroy the broadcaster.
210 //----------------------------------------------------------------------
212 //----------------------------------------------------------------------
213 lldb_private::ConstString
214 ProcessKDP::GetPluginName()
216 return GetPluginNameStatic();
220 ProcessKDP::GetPluginVersion()
226 ProcessKDP::WillLaunch (Module* module)
229 error.SetErrorString ("launching not supported in kdp-remote plug-in");
234 ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
237 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
242 ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
245 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
250 ProcessKDP::GetHostArchitecture(ArchSpec &arch)
252 uint32_t cpu = m_comm.GetCPUType();
255 uint32_t sub = m_comm.GetCPUSubtype();
256 arch.SetArchitecture(eArchTypeMachO, cpu, sub);
257 // Leave architecture vendor as unspecified unknown
258 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
259 arch.GetTriple().setVendorName(llvm::StringRef());
267 ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
271 // Don't let any JIT happen when doing KDP as we can't allocate
272 // memory and we don't want to be mucking with threads that might
273 // already be handling exceptions
276 if (remote_url == NULL || remote_url[0] == '\0')
278 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
282 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
285 // Only try once for now.
286 // TODO: check if we should be retrying?
287 const uint32_t max_retry_count = 1;
288 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
290 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
296 if (conn_ap->IsConnected())
298 const TCPSocket& socket = static_cast<const TCPSocket&>(*conn_ap->GetReadObject());
299 const uint16_t reply_port = socket.GetLocalPortNumber();
303 m_comm.SetConnection(conn_ap.release());
305 if (m_comm.SendRequestReattach(reply_port))
307 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
311 Target &target = GetTarget();
312 ArchSpec kernel_arch;
313 // The host architecture
314 GetHostArchitecture(kernel_arch);
315 ArchSpec target_arch = target.GetArchitecture();
316 // Merge in any unspecified stuff into the target architecture in
317 // case the target arch isn't set at all or incompletely.
318 target_arch.MergeFrom(kernel_arch);
319 target.SetArchitecture(target_arch);
321 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
322 /* An EFI kdp session has neither UUID nor load address. */
324 UUID kernel_uuid = m_comm.GetUUID ();
325 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
327 if (m_comm.RemoteIsEFI ())
329 // Select an invalid plugin name for the dynamic loader so one doesn't get used
330 // since EFI does its own manual loading via python scripting
331 static ConstString g_none_dynamic_loader("none");
332 m_dyld_plugin_name = g_none_dynamic_loader;
334 if (kernel_uuid.IsValid()) {
335 // If EFI passed in a UUID= try to lookup UUID
336 // The slide will not be provided. But the UUID
337 // lookup will be used to launch EFI debug scripts
338 // from the dSYM, that can load all of the symbols.
339 ModuleSpec module_spec;
340 module_spec.GetUUID() = kernel_uuid;
341 module_spec.GetArchitecture() = target.GetArchitecture();
343 // Lookup UUID locally, before attempting dsymForUUID like action
344 module_spec.GetSymbolFileSpec() = Symbols::LocateExecutableSymbolFile(module_spec);
345 if (module_spec.GetSymbolFileSpec())
347 ModuleSpec executable_module_spec = Symbols::LocateExecutableObjectFile (module_spec);
348 if (executable_module_spec.GetFileSpec().Exists())
350 module_spec.GetFileSpec() = executable_module_spec.GetFileSpec();
353 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec())
354 Symbols::DownloadObjectAndSymbolFile (module_spec, true);
356 if (module_spec.GetFileSpec().Exists())
358 ModuleSP module_sp(new Module (module_spec));
359 if (module_sp.get() && module_sp->GetObjectFile())
361 // Get the current target executable
362 ModuleSP exe_module_sp (target.GetExecutableModule ());
364 // Make sure you don't already have the right module loaded and they will be uniqued
365 if (exe_module_sp.get() != module_sp.get())
366 target.SetExecutableModule (module_sp, false);
371 else if (m_comm.RemoteIsDarwinKernel ())
373 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
374 if (kernel_load_addr != LLDB_INVALID_ADDRESS)
376 m_kernel_load_addr = kernel_load_addr;
381 UpdateThreadListIfNeeded ();
384 SetPrivateState (eStateStopped);
385 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
389 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
391 async_strm_sp->Printf ("Version: %s\n", cstr);
392 async_strm_sp->Flush();
394 // if ((cstr = m_comm.GetImagePath ()) != NULL)
396 // async_strm_sp->Printf ("Image Path: %s\n", cstr);
397 // async_strm_sp->Flush();
403 error.SetErrorString("KDP_REATTACH failed");
408 error.SetErrorString("KDP_REATTACH failed");
413 error.SetErrorString("invalid reply port from UDP connection");
419 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
427 //----------------------------------------------------------------------
429 //----------------------------------------------------------------------
431 ProcessKDP::DoLaunch (Module *exe_module,
432 ProcessLaunchInfo &launch_info)
435 error.SetErrorString ("launching not supported in kdp-remote plug-in");
440 ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
443 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
448 ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
451 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
457 ProcessKDP::DidAttach (ArchSpec &process_arch)
459 Process::DidAttach(process_arch);
461 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
463 log->Printf ("ProcessKDP::DidAttach()");
464 if (GetID() != LLDB_INVALID_PROCESS_ID)
466 GetHostArchitecture(process_arch);
471 ProcessKDP::GetImageInfoAddress()
473 return m_kernel_load_addr;
476 lldb_private::DynamicLoader *
477 ProcessKDP::GetDynamicLoader ()
479 if (m_dyld_ap.get() == NULL)
480 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
481 return m_dyld_ap.get();
485 ProcessKDP::WillResume ()
491 ProcessKDP::DoResume ()
494 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
495 // Only start the async thread if we try to do any process control
496 if (!m_async_thread.IsJoinable())
501 // With KDP there is only one thread we can tell what to do
502 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid));
504 if (kernel_thread_sp)
506 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
509 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state));
510 switch (thread_resume_state)
512 case eStateSuspended:
513 // Nothing to do here when a thread will stay suspended
514 // we just leave the CPU mask bit set to zero for the thread
516 log->Printf ("ProcessKDP::DoResume() = suspended???");
521 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
526 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
527 reg_ctx_sp->HardwareSingleStep (true);
532 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
539 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
544 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);");
545 reg_ctx_sp->HardwareSingleStep (false);
550 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
556 // The only valid thread resume states are listed above
557 assert (!"invalid thread resume state");
565 log->Printf ("ProcessKDP::DoResume () sending resume");
567 if (m_comm.SendRequestResume ())
569 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
570 SetPrivateState(eStateRunning);
573 error.SetErrorString ("KDP resume failed");
577 error.SetErrorString ("kernel thread is suspended");
584 ProcessKDP::GetKernelThread()
586 // KDP only tells us about one thread/core. Any other threads will usually
587 // be the ones that are read from memory by the OS plug-ins.
589 ThreadSP thread_sp (m_kernel_thread_wp.lock());
592 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid));
593 m_kernel_thread_wp = thread_sp;
602 ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
604 // locker will keep a mutex locked until it goes out of scope
605 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
606 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
607 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
609 // Even though there is a CPU mask, it doesn't mean we can see each CPU
610 // individually, there is really only one. Lets call this thread 1.
611 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
613 thread_sp = GetKernelThread ();
614 new_thread_list.AddThread(thread_sp);
616 return new_thread_list.GetSize(false) > 0;
620 ProcessKDP::RefreshStateAfterStop ()
622 // Let all threads recover from stopping and do any clean up based
623 // on the previous thread state (if any).
624 m_thread_list.RefreshStateAfterStop();
628 ProcessKDP::DoHalt (bool &caused_stop)
632 if (m_comm.IsRunning())
634 if (m_destroy_in_process)
636 // If we are attemping to destroy, we need to not return an error to
637 // Halt or DoDestroy won't get called.
638 // We are also currently running, so send a process stopped event
639 SetPrivateState (eStateStopped);
643 error.SetErrorString ("KDP cannot interrupt a running kernel");
650 ProcessKDP::DoDetach(bool keep_stopped)
653 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
655 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
657 if (m_comm.IsRunning())
659 // We are running and we can't interrupt a running kernel, so we need
660 // to just close the connection to the kernel and hope for the best
664 // If we are going to keep the target stopped, then don't send the disconnect message.
665 if (!keep_stopped && m_comm.IsConnected())
667 const bool success = m_comm.SendRequestDisconnect();
671 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
673 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed");
675 m_comm.Disconnect ();
681 SetPrivateState (eStateDetached);
682 ResumePrivateStateThread();
684 //KillDebugserverProcess ();
689 ProcessKDP::DoDestroy ()
691 // For KDP there really is no difference between destroy and detach
692 bool keep_stopped = false;
693 return DoDetach(keep_stopped);
696 //------------------------------------------------------------------
698 //------------------------------------------------------------------
701 ProcessKDP::IsAlive ()
703 return m_comm.IsConnected() && Process::IsAlive();
706 //------------------------------------------------------------------
708 //------------------------------------------------------------------
710 ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
712 uint8_t *data_buffer = (uint8_t *) buf;
713 if (m_comm.IsConnected())
715 const size_t max_read_size = 512;
716 size_t total_bytes_read = 0;
718 // Read the requested amount of memory in 512 byte chunks
719 while (total_bytes_read < size)
721 size_t bytes_to_read_this_request = size - total_bytes_read;
722 if (bytes_to_read_this_request > max_read_size)
724 bytes_to_read_this_request = max_read_size;
726 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read,
727 data_buffer + total_bytes_read,
728 bytes_to_read_this_request, error);
729 total_bytes_read += bytes_read;
730 if (error.Fail() || bytes_read == 0)
732 return total_bytes_read;
736 return total_bytes_read;
738 error.SetErrorString ("not connected");
743 ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
745 if (m_comm.IsConnected())
746 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
747 error.SetErrorString ("not connected");
752 ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
754 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
755 return LLDB_INVALID_ADDRESS;
759 ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
762 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
767 ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site)
769 if (m_comm.LocalBreakpointsAreSupported ())
772 if (!bp_site->IsEnabled())
774 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
776 bp_site->SetEnabled(true);
777 bp_site->SetType (BreakpointSite::eExternal);
781 error.SetErrorString ("KDP set breakpoint failed");
786 return EnableSoftwareBreakpoint (bp_site);
790 ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site)
792 if (m_comm.LocalBreakpointsAreSupported ())
795 if (bp_site->IsEnabled())
797 BreakpointSite::Type bp_type = bp_site->GetType();
798 if (bp_type == BreakpointSite::eExternal)
800 if (m_destroy_in_process && m_comm.IsRunning())
802 // We are trying to destroy our connection and we are running
803 bp_site->SetEnabled(false);
807 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
808 bp_site->SetEnabled(false);
810 error.SetErrorString ("KDP remove breakpoint failed");
815 error = DisableSoftwareBreakpoint (bp_site);
820 return DisableSoftwareBreakpoint (bp_site);
824 ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
827 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
832 ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
835 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
842 m_thread_list.Clear();
846 ProcessKDP::DoSignal (int signo)
849 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
854 ProcessKDP::Initialize()
856 static std::once_flag g_once_flag;
858 std::call_once(g_once_flag, []()
860 PluginManager::RegisterPlugin (GetPluginNameStatic(),
861 GetPluginDescriptionStatic(),
865 Log::Callbacks log_callbacks = {
866 ProcessKDPLog::DisableLog,
867 ProcessKDPLog::EnableLog,
868 ProcessKDPLog::ListLogCategories
871 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
876 ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger)
878 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
880 const bool is_global_setting = true;
881 PluginManager::CreateSettingForProcessPlugin (debugger,
882 GetGlobalPluginProperties()->GetValueProperties(),
883 ConstString ("Properties for the kdp-remote process plug-in."),
889 ProcessKDP::StartAsyncThread ()
891 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
894 log->Printf ("ProcessKDP::StartAsyncThread ()");
896 if (m_async_thread.IsJoinable())
899 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
900 return m_async_thread.IsJoinable();
904 ProcessKDP::StopAsyncThread ()
906 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
909 log->Printf ("ProcessKDP::StopAsyncThread ()");
911 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
913 // Stop the stdio thread
914 if (m_async_thread.IsJoinable())
915 m_async_thread.Join(nullptr);
920 ProcessKDP::AsyncThread (void *arg)
922 ProcessKDP *process = (ProcessKDP*) arg;
924 const lldb::pid_t pid = process->GetID();
926 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
928 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
930 Listener listener ("ProcessKDP::AsyncThread");
932 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
933 eBroadcastBitAsyncThreadShouldExit;
936 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
942 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
944 if (listener.WaitForEvent (NULL, event_sp))
946 uint32_t event_type = event_sp->GetType();
948 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
952 // When we are running, poll for 1 second to try and get an exception
953 // to indicate the process has stopped. If we don't get one, check to
954 // make sure no one asked us to exit
955 bool is_running = false;
956 DataExtractor exc_reply_packet;
961 case eBroadcastBitAsyncContinue:
964 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
966 ThreadSP thread_sp (process->GetKernelThread());
969 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
971 reg_ctx_sp->InvalidateAllRegisters();
972 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
975 // TODO: parse the stop reply packet
977 process->SetPrivateState(eStateStopped);
981 // Check to see if we are supposed to exit. There is no way to
982 // interrupt a running kernel, so all we can do is wait for an
983 // exception or detach...
984 if (listener.GetNextEvent(event_sp))
986 // We got an event, go through the loop again
987 event_type = event_sp->GetType();
993 case eBroadcastBitAsyncThreadShouldExit:
995 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
1003 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
1010 } while (is_running);
1015 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
1023 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
1027 process->m_async_thread.Reset();
1032 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
1036 OptionGroupOptions m_option_group;
1037 OptionGroupUInt64 m_command_byte;
1038 OptionGroupString m_packet_data;
1043 return &m_option_group;
1048 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
1049 CommandObjectParsed (interpreter,
1050 "process plugin packet send",
1051 "Send a custom packet through the KDP protocol by specifying the command byte and the packet payload data. A packet will be sent with a correct header and payload, and the raw result bytes will be displayed as a string value. ",
1053 m_option_group (interpreter),
1054 m_command_byte(LLDB_OPT_SET_1, true , "command", 'c', 0, eArgTypeNone, "Specify the command byte to use when sending the KDP request packet.", 0),
1055 m_packet_data (LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone, "Specify packet payload bytes as a hex ASCII string with no spaces or hex prefixes.", NULL)
1057 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1058 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1059 m_option_group.Finalize();
1062 ~CommandObjectProcessKDPPacketSend ()
1067 DoExecute (Args& command, CommandReturnObject &result)
1069 const size_t argc = command.GetArgumentCount();
1072 if (!m_command_byte.GetOptionValue().OptionWasSet())
1074 result.AppendError ("the --command option must be set to a valid command byte");
1075 result.SetStatus (eReturnStatusFailed);
1079 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
1080 if (command_byte > 0 && command_byte <= UINT8_MAX)
1082 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
1085 const StateType state = process->GetState();
1087 if (StateIsStoppedState (state, true))
1089 std::vector<uint8_t> payload_bytes;
1090 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
1091 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
1093 StringExtractor extractor(ascii_hex_bytes_cstr);
1094 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
1095 if (ascii_hex_bytes_cstr_len & 1)
1097 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
1098 result.SetStatus (eReturnStatusFailed);
1101 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
1102 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
1104 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
1105 result.SetStatus (eReturnStatusFailed);
1110 DataExtractor reply;
1111 process->GetCommunication().SendRawRequest (command_byte,
1112 payload_bytes.empty() ? NULL : payload_bytes.data(),
1113 payload_bytes.size(),
1117 if (error.Success())
1119 // Copy the binary bytes into a hex ASCII string for the result
1120 StreamString packet;
1121 packet.PutBytesAsRawHex8(reply.GetDataStart(),
1122 reply.GetByteSize(),
1123 endian::InlHostByteOrder(),
1124 endian::InlHostByteOrder());
1125 result.AppendMessage(packet.GetString().c_str());
1126 result.SetStatus (eReturnStatusSuccessFinishResult);
1131 const char *error_cstr = error.AsCString();
1132 if (error_cstr && error_cstr[0])
1133 result.AppendError (error_cstr);
1135 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
1136 result.SetStatus (eReturnStatusFailed);
1142 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
1143 result.SetStatus (eReturnStatusFailed);
1148 result.AppendError ("invalid process");
1149 result.SetStatus (eReturnStatusFailed);
1154 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
1155 result.SetStatus (eReturnStatusFailed);
1161 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
1162 result.SetStatus (eReturnStatusFailed);
1168 class CommandObjectProcessKDPPacket : public CommandObjectMultiword
1173 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
1174 CommandObjectMultiword (interpreter,
1175 "process plugin packet",
1176 "Commands that deal with KDP remote packets.",
1179 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
1182 ~CommandObjectProcessKDPPacket ()
1187 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1190 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1191 CommandObjectMultiword (interpreter,
1193 "A set of commands for operating on a ProcessKDP process.",
1194 "process plugin <subcommand> [<subcommand-options>]")
1196 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1199 ~CommandObjectMultiwordProcessKDP ()
1205 ProcessKDP::GetPluginCommandObject()
1208 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1209 return m_command_sp.get();