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