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