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