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