1 //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
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 <errno.h>
10 #include <stdlib.h>
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/State.h"
36 #include "lldb/Utility/StringExtractor.h"
37 #include "lldb/Utility/UUID.h"
38 
39 #include "llvm/Support/Threading.h"
40 
41 #define USEC_PER_SEC 1000000
42 
43 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
44 #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
45 #include "ProcessKDP.h"
46 #include "ProcessKDPLog.h"
47 #include "ThreadKDP.h"
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 namespace {
53 
54 static constexpr PropertyDefinition g_properties[] = {
55     {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, {},
56      "Specify the default packet timeout in seconds."}};
57 
58 enum { ePropertyPacketTimeout };
59 
60 class PluginProperties : public Properties {
61 public:
62   static ConstString GetSettingName() {
63     return ProcessKDP::GetPluginNameStatic();
64   }
65 
66   PluginProperties() : Properties() {
67     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
68     m_collection_sp->Initialize(g_properties);
69   }
70 
71   virtual ~PluginProperties() {}
72 
73   uint64_t GetPacketTimeout() {
74     const uint32_t idx = ePropertyPacketTimeout;
75     return m_collection_sp->GetPropertyAtIndexAsUInt64(
76         NULL, idx, g_properties[idx].default_uint_value);
77   }
78 };
79 
80 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
81 
82 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
83   static ProcessKDPPropertiesSP g_settings_sp;
84   if (!g_settings_sp)
85     g_settings_sp = std::make_shared<PluginProperties>();
86   return g_settings_sp;
87 }
88 
89 } // anonymous namespace end
90 
91 static const lldb::tid_t g_kernel_tid = 1;
92 
93 ConstString ProcessKDP::GetPluginNameStatic() {
94   static ConstString g_name("kdp-remote");
95   return g_name;
96 }
97 
98 const char *ProcessKDP::GetPluginDescriptionStatic() {
99   return "KDP Remote protocol based debugging plug-in for darwin kernel "
100          "debugging.";
101 }
102 
103 void ProcessKDP::Terminate() {
104   PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
105 }
106 
107 lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
108                                            ListenerSP listener_sp,
109                                            const FileSpec *crash_file_path) {
110   lldb::ProcessSP process_sp;
111   if (crash_file_path == NULL)
112     process_sp = std::make_shared<ProcessKDP>(target_sp, listener_sp);
113   return process_sp;
114 }
115 
116 bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
117   if (plugin_specified_by_name)
118     return true;
119 
120   // For now we are just making sure the file exists for a given module
121   Module *exe_module = target_sp->GetExecutableModulePointer();
122   if (exe_module) {
123     const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
124     switch (triple_ref.getOS()) {
125     case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
126                                // iOS, but accept darwin just in case
127     case llvm::Triple::MacOSX: // For desktop targets
128     case llvm::Triple::IOS:    // For arm targets
129     case llvm::Triple::TvOS:
130     case llvm::Triple::WatchOS:
131       if (triple_ref.getVendor() == llvm::Triple::Apple) {
132         ObjectFile *exe_objfile = exe_module->GetObjectFile();
133         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
134             exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
135           return true;
136       }
137       break;
138 
139     default:
140       break;
141     }
142   }
143   return false;
144 }
145 
146 // ProcessKDP constructor
147 ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
148     : Process(target_sp, listener_sp),
149       m_comm("lldb.process.kdp-remote.communication"),
150       m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
151       m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
152       m_command_sp(), m_kernel_thread_wp() {
153   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
154                                    "async thread should exit");
155   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
156                                    "async thread continue");
157   const uint64_t timeout_seconds =
158       GetGlobalPluginProperties()->GetPacketTimeout();
159   if (timeout_seconds > 0)
160     m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
161 }
162 
163 // Destructor
164 ProcessKDP::~ProcessKDP() {
165   Clear();
166   // We need to call finalize on the process before destroying ourselves to
167   // make sure all of the broadcaster cleanup goes as planned. If we destruct
168   // this class, then Process::~Process() might have problems trying to fully
169   // destroy the broadcaster.
170   Finalize();
171 }
172 
173 // PluginInterface
174 lldb_private::ConstString ProcessKDP::GetPluginName() {
175   return GetPluginNameStatic();
176 }
177 
178 uint32_t ProcessKDP::GetPluginVersion() { return 1; }
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(Stream *strm, 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(conn_up.release());
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   if (log)
397     log->Printf("ProcessKDP::DidAttach()");
398   if (GetID() != LLDB_INVALID_PROCESS_ID) {
399     GetHostArchitecture(process_arch);
400   }
401 }
402 
403 addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
404 
405 lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
406   if (m_dyld_up.get() == NULL)
407     m_dyld_up.reset(DynamicLoader::FindPlugin(
408         this,
409         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
410   return m_dyld_up.get();
411 }
412 
413 Status ProcessKDP::WillResume() { return Status(); }
414 
415 Status ProcessKDP::DoResume() {
416   Status error;
417   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
418   // Only start the async thread if we try to do any process control
419   if (!m_async_thread.IsJoinable())
420     StartAsyncThread();
421 
422   bool resume = false;
423 
424   // With KDP there is only one thread we can tell what to do
425   ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
426 
427   if (kernel_thread_sp) {
428     const StateType thread_resume_state =
429         kernel_thread_sp->GetTemporaryResumeState();
430 
431     if (log)
432       log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
433                   StateAsCString(thread_resume_state));
434     switch (thread_resume_state) {
435     case eStateSuspended:
436       // Nothing to do here when a thread will stay suspended we just leave the
437       // CPU mask bit set to zero for the thread
438       if (log)
439         log->Printf("ProcessKDP::DoResume() = suspended???");
440       break;
441 
442     case eStateStepping: {
443       lldb::RegisterContextSP reg_ctx_sp(
444           kernel_thread_sp->GetRegisterContext());
445 
446       if (reg_ctx_sp) {
447         if (log)
448           log->Printf(
449               "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
450         reg_ctx_sp->HardwareSingleStep(true);
451         resume = true;
452       } else {
453         error.SetErrorStringWithFormat(
454             "KDP thread 0x%llx has no register context",
455             kernel_thread_sp->GetID());
456       }
457     } break;
458 
459     case eStateRunning: {
460       lldb::RegisterContextSP reg_ctx_sp(
461           kernel_thread_sp->GetRegisterContext());
462 
463       if (reg_ctx_sp) {
464         if (log)
465           log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
466                       "(false);");
467         reg_ctx_sp->HardwareSingleStep(false);
468         resume = true;
469       } else {
470         error.SetErrorStringWithFormat(
471             "KDP thread 0x%llx has no register context",
472             kernel_thread_sp->GetID());
473       }
474     } break;
475 
476     default:
477       // The only valid thread resume states are listed above
478       llvm_unreachable("invalid thread resume state");
479     }
480   }
481 
482   if (resume) {
483     if (log)
484       log->Printf("ProcessKDP::DoResume () sending resume");
485 
486     if (m_comm.SendRequestResume()) {
487       m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
488       SetPrivateState(eStateRunning);
489     } else
490       error.SetErrorString("KDP resume failed");
491   } else {
492     error.SetErrorString("kernel thread is suspended");
493   }
494 
495   return error;
496 }
497 
498 lldb::ThreadSP ProcessKDP::GetKernelThread() {
499   // KDP only tells us about one thread/core. Any other threads will usually
500   // be the ones that are read from memory by the OS plug-ins.
501 
502   ThreadSP thread_sp(m_kernel_thread_wp.lock());
503   if (!thread_sp) {
504     thread_sp = std::make_shared<ThreadKDP>(*this, g_kernel_tid);
505     m_kernel_thread_wp = thread_sp;
506   }
507   return thread_sp;
508 }
509 
510 bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
511                                   ThreadList &new_thread_list) {
512   // locker will keep a mutex locked until it goes out of scope
513   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
514   LLDB_LOGV(log, "pid = {0}", GetID());
515 
516   // Even though there is a CPU mask, it doesn't mean we can see each CPU
517   // individually, there is really only one. Lets call this thread 1.
518   ThreadSP thread_sp(
519       old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
520   if (!thread_sp)
521     thread_sp = GetKernelThread();
522   new_thread_list.AddThread(thread_sp);
523 
524   return new_thread_list.GetSize(false) > 0;
525 }
526 
527 void ProcessKDP::RefreshStateAfterStop() {
528   // Let all threads recover from stopping and do any clean up based on the
529   // previous thread state (if any).
530   m_thread_list.RefreshStateAfterStop();
531 }
532 
533 Status ProcessKDP::DoHalt(bool &caused_stop) {
534   Status error;
535 
536   if (m_comm.IsRunning()) {
537     if (m_destroy_in_process) {
538       // If we are attempting to destroy, we need to not return an error to Halt
539       // or DoDestroy won't get called. We are also currently running, so send
540       // a process stopped event
541       SetPrivateState(eStateStopped);
542     } else {
543       error.SetErrorString("KDP cannot interrupt a running kernel");
544     }
545   }
546   return error;
547 }
548 
549 Status ProcessKDP::DoDetach(bool keep_stopped) {
550   Status error;
551   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
552   if (log)
553     log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
554 
555   if (m_comm.IsRunning()) {
556     // We are running and we can't interrupt a running kernel, so we need to
557     // just close the connection to the kernel and hope for the best
558   } else {
559     // If we are going to keep the target stopped, then don't send the
560     // disconnect message.
561     if (!keep_stopped && m_comm.IsConnected()) {
562       const bool success = m_comm.SendRequestDisconnect();
563       if (log) {
564         if (success)
565           log->PutCString(
566               "ProcessKDP::DoDetach() detach packet sent successfully");
567         else
568           log->PutCString(
569               "ProcessKDP::DoDetach() connection channel shutdown failed");
570       }
571       m_comm.Disconnect();
572     }
573   }
574   StopAsyncThread();
575   m_comm.Clear();
576 
577   SetPrivateState(eStateDetached);
578   ResumePrivateStateThread();
579 
580   // KillDebugserverProcess ();
581   return error;
582 }
583 
584 Status ProcessKDP::DoDestroy() {
585   // For KDP there really is no difference between destroy and detach
586   bool keep_stopped = false;
587   return DoDetach(keep_stopped);
588 }
589 
590 // Process Queries
591 
592 bool ProcessKDP::IsAlive() {
593   return m_comm.IsConnected() && Process::IsAlive();
594 }
595 
596 // Process Memory
597 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
598                                 Status &error) {
599   uint8_t *data_buffer = (uint8_t *)buf;
600   if (m_comm.IsConnected()) {
601     const size_t max_read_size = 512;
602     size_t total_bytes_read = 0;
603 
604     // Read the requested amount of memory in 512 byte chunks
605     while (total_bytes_read < size) {
606       size_t bytes_to_read_this_request = size - total_bytes_read;
607       if (bytes_to_read_this_request > max_read_size) {
608         bytes_to_read_this_request = max_read_size;
609       }
610       size_t bytes_read = m_comm.SendRequestReadMemory(
611           addr + total_bytes_read, data_buffer + total_bytes_read,
612           bytes_to_read_this_request, error);
613       total_bytes_read += bytes_read;
614       if (error.Fail() || bytes_read == 0) {
615         return total_bytes_read;
616       }
617     }
618 
619     return total_bytes_read;
620   }
621   error.SetErrorString("not connected");
622   return 0;
623 }
624 
625 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
626                                  Status &error) {
627   if (m_comm.IsConnected())
628     return m_comm.SendRequestWriteMemory(addr, buf, size, error);
629   error.SetErrorString("not connected");
630   return 0;
631 }
632 
633 lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
634                                           Status &error) {
635   error.SetErrorString(
636       "memory allocation not supported in kdp remote debugging");
637   return LLDB_INVALID_ADDRESS;
638 }
639 
640 Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
641   Status error;
642   error.SetErrorString(
643       "memory deallocation not supported in kdp remote debugging");
644   return error;
645 }
646 
647 Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
648   if (m_comm.LocalBreakpointsAreSupported()) {
649     Status error;
650     if (!bp_site->IsEnabled()) {
651       if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
652         bp_site->SetEnabled(true);
653         bp_site->SetType(BreakpointSite::eExternal);
654       } else {
655         error.SetErrorString("KDP set breakpoint failed");
656       }
657     }
658     return error;
659   }
660   return EnableSoftwareBreakpoint(bp_site);
661 }
662 
663 Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
664   if (m_comm.LocalBreakpointsAreSupported()) {
665     Status error;
666     if (bp_site->IsEnabled()) {
667       BreakpointSite::Type bp_type = bp_site->GetType();
668       if (bp_type == BreakpointSite::eExternal) {
669         if (m_destroy_in_process && m_comm.IsRunning()) {
670           // We are trying to destroy our connection and we are running
671           bp_site->SetEnabled(false);
672         } else {
673           if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
674             bp_site->SetEnabled(false);
675           else
676             error.SetErrorString("KDP remove breakpoint failed");
677         }
678       } else {
679         error = DisableSoftwareBreakpoint(bp_site);
680       }
681     }
682     return error;
683   }
684   return DisableSoftwareBreakpoint(bp_site);
685 }
686 
687 Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
688   Status error;
689   error.SetErrorString(
690       "watchpoints are not supported in kdp remote debugging");
691   return error;
692 }
693 
694 Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
695   Status error;
696   error.SetErrorString(
697       "watchpoints are not supported in kdp remote debugging");
698   return error;
699 }
700 
701 void ProcessKDP::Clear() { m_thread_list.Clear(); }
702 
703 Status ProcessKDP::DoSignal(int signo) {
704   Status error;
705   error.SetErrorString(
706       "sending signals is not supported in kdp remote debugging");
707   return error;
708 }
709 
710 void ProcessKDP::Initialize() {
711   static llvm::once_flag g_once_flag;
712 
713   llvm::call_once(g_once_flag, []() {
714     PluginManager::RegisterPlugin(GetPluginNameStatic(),
715                                   GetPluginDescriptionStatic(), CreateInstance,
716                                   DebuggerInitialize);
717 
718     ProcessKDPLog::Initialize();
719   });
720 }
721 
722 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
723   if (!PluginManager::GetSettingForProcessPlugin(
724           debugger, PluginProperties::GetSettingName())) {
725     const bool is_global_setting = true;
726     PluginManager::CreateSettingForProcessPlugin(
727         debugger, GetGlobalPluginProperties()->GetValueProperties(),
728         ConstString("Properties for the kdp-remote process plug-in."),
729         is_global_setting);
730   }
731 }
732 
733 bool ProcessKDP::StartAsyncThread() {
734   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
735 
736   if (log)
737     log->Printf("ProcessKDP::StartAsyncThread ()");
738 
739   if (m_async_thread.IsJoinable())
740     return true;
741 
742   m_async_thread = ThreadLauncher::LaunchThread(
743       "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
744   return m_async_thread.IsJoinable();
745 }
746 
747 void ProcessKDP::StopAsyncThread() {
748   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
749 
750   if (log)
751     log->Printf("ProcessKDP::StopAsyncThread ()");
752 
753   m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
754 
755   // Stop the stdio thread
756   if (m_async_thread.IsJoinable())
757     m_async_thread.Join(nullptr);
758 }
759 
760 void *ProcessKDP::AsyncThread(void *arg) {
761   ProcessKDP *process = (ProcessKDP *)arg;
762 
763   const lldb::pid_t pid = process->GetID();
764 
765   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
766   if (log)
767     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
768                 ") thread starting...",
769                 arg, pid);
770 
771   ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
772   EventSP event_sp;
773   const uint32_t desired_event_mask =
774       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
775 
776   if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
777                                            desired_event_mask) ==
778       desired_event_mask) {
779     bool done = false;
780     while (!done) {
781       if (log)
782         log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
783                     ") listener.WaitForEvent (NULL, event_sp)...",
784                     pid);
785       if (listener_sp->GetEvent(event_sp, llvm::None)) {
786         uint32_t event_type = event_sp->GetType();
787         if (log)
788           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
789                       ") Got an event of type: %d...",
790                       pid, event_type);
791 
792         // When we are running, poll for 1 second to try and get an exception
793         // to indicate the process has stopped. If we don't get one, check to
794         // make sure no one asked us to exit
795         bool is_running = false;
796         DataExtractor exc_reply_packet;
797         do {
798           switch (event_type) {
799           case eBroadcastBitAsyncContinue: {
800             is_running = true;
801             if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
802                     exc_reply_packet, 1 * USEC_PER_SEC)) {
803               ThreadSP thread_sp(process->GetKernelThread());
804               if (thread_sp) {
805                 lldb::RegisterContextSP reg_ctx_sp(
806                     thread_sp->GetRegisterContext());
807                 if (reg_ctx_sp)
808                   reg_ctx_sp->InvalidateAllRegisters();
809                 static_cast<ThreadKDP *>(thread_sp.get())
810                     ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
811               }
812 
813               // TODO: parse the stop reply packet
814               is_running = false;
815               process->SetPrivateState(eStateStopped);
816             } else {
817               // Check to see if we are supposed to exit. There is no way to
818               // interrupt a running kernel, so all we can do is wait for an
819               // exception or detach...
820               if (listener_sp->GetEvent(event_sp,
821                                         std::chrono::microseconds(0))) {
822                 // We got an event, go through the loop again
823                 event_type = event_sp->GetType();
824               }
825             }
826           } break;
827 
828           case eBroadcastBitAsyncThreadShouldExit:
829             if (log)
830               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
831                           ") got eBroadcastBitAsyncThreadShouldExit...",
832                           pid);
833             done = true;
834             is_running = false;
835             break;
836 
837           default:
838             if (log)
839               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
840                           ") got unknown event 0x%8.8x",
841                           pid, event_type);
842             done = true;
843             is_running = false;
844             break;
845           }
846         } while (is_running);
847       } else {
848         if (log)
849           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
850                       ") listener.WaitForEvent (NULL, event_sp) => false",
851                       pid);
852         done = true;
853       }
854     }
855   }
856 
857   if (log)
858     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
859                 ") thread exiting...",
860                 arg, pid);
861 
862   process->m_async_thread.Reset();
863   return NULL;
864 }
865 
866 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
867 private:
868   OptionGroupOptions m_option_group;
869   OptionGroupUInt64 m_command_byte;
870   OptionGroupString m_packet_data;
871 
872   virtual Options *GetOptions() { return &m_option_group; }
873 
874 public:
875   CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
876       : CommandObjectParsed(interpreter, "process plugin packet send",
877                             "Send a custom packet through the KDP protocol by "
878                             "specifying the command byte and the packet "
879                             "payload data. A packet will be sent with a "
880                             "correct header and payload, and the raw result "
881                             "bytes will be displayed as a string value. ",
882                             NULL),
883         m_option_group(),
884         m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
885                        "Specify the command byte to use when sending the KDP "
886                        "request packet.",
887                        0),
888         m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
889                       "Specify packet payload bytes as a hex ASCII string with "
890                       "no spaces or hex prefixes.",
891                       NULL) {
892     m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
893     m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
894     m_option_group.Finalize();
895   }
896 
897   ~CommandObjectProcessKDPPacketSend() {}
898 
899   bool DoExecute(Args &command, CommandReturnObject &result) {
900     const size_t argc = command.GetArgumentCount();
901     if (argc == 0) {
902       if (!m_command_byte.GetOptionValue().OptionWasSet()) {
903         result.AppendError(
904             "the --command option must be set to a valid command byte");
905         result.SetStatus(eReturnStatusFailed);
906       } else {
907         const uint64_t command_byte =
908             m_command_byte.GetOptionValue().GetUInt64Value(0);
909         if (command_byte > 0 && command_byte <= UINT8_MAX) {
910           ProcessKDP *process =
911               (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
912           if (process) {
913             const StateType state = process->GetState();
914 
915             if (StateIsStoppedState(state, true)) {
916               std::vector<uint8_t> payload_bytes;
917               const char *ascii_hex_bytes_cstr =
918                   m_packet_data.GetOptionValue().GetCurrentValue();
919               if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
920                 StringExtractor extractor(ascii_hex_bytes_cstr);
921                 const size_t ascii_hex_bytes_cstr_len =
922                     extractor.GetStringRef().size();
923                 if (ascii_hex_bytes_cstr_len & 1) {
924                   result.AppendErrorWithFormat("payload data must contain an "
925                                                "even number of ASCII hex "
926                                                "characters: '%s'",
927                                                ascii_hex_bytes_cstr);
928                   result.SetStatus(eReturnStatusFailed);
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                   result.SetStatus(eReturnStatusFailed);
939                   return false;
940                 }
941               }
942               Status error;
943               DataExtractor reply;
944               process->GetCommunication().SendRawRequest(
945                   command_byte,
946                   payload_bytes.empty() ? NULL : payload_bytes.data(),
947                   payload_bytes.size(), reply, error);
948 
949               if (error.Success()) {
950                 // Copy the binary bytes into a hex ASCII string for the result
951                 StreamString packet;
952                 packet.PutBytesAsRawHex8(
953                     reply.GetDataStart(), reply.GetByteSize(),
954                     endian::InlHostByteOrder(), endian::InlHostByteOrder());
955                 result.AppendMessage(packet.GetString());
956                 result.SetStatus(eReturnStatusSuccessFinishResult);
957                 return true;
958               } else {
959                 const char *error_cstr = error.AsCString();
960                 if (error_cstr && error_cstr[0])
961                   result.AppendError(error_cstr);
962                 else
963                   result.AppendErrorWithFormat("unknown error 0x%8.8x",
964                                                error.GetError());
965                 result.SetStatus(eReturnStatusFailed);
966                 return false;
967               }
968             } else {
969               result.AppendErrorWithFormat("process must be stopped in order "
970                                            "to send KDP packets, state is %s",
971                                            StateAsCString(state));
972               result.SetStatus(eReturnStatusFailed);
973             }
974           } else {
975             result.AppendError("invalid process");
976             result.SetStatus(eReturnStatusFailed);
977           }
978         } else {
979           result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
980                                        ", valid values are 1 - 255",
981                                        command_byte);
982           result.SetStatus(eReturnStatusFailed);
983         }
984       }
985     } else {
986       result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
987                                    m_cmd_name.c_str());
988       result.SetStatus(eReturnStatusFailed);
989     }
990     return false;
991   }
992 };
993 
994 class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
995 private:
996 public:
997   CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
998       : CommandObjectMultiword(interpreter, "process plugin packet",
999                                "Commands that deal with KDP remote packets.",
1000                                NULL) {
1001     LoadSubCommand(
1002         "send",
1003         CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1004   }
1005 
1006   ~CommandObjectProcessKDPPacket() {}
1007 };
1008 
1009 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
1010 public:
1011   CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1012       : CommandObjectMultiword(
1013             interpreter, "process plugin",
1014             "Commands for operating on a ProcessKDP process.",
1015             "process plugin <subcommand> [<subcommand-options>]") {
1016     LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1017                                  interpreter)));
1018   }
1019 
1020   ~CommandObjectMultiwordProcessKDP() {}
1021 };
1022 
1023 CommandObject *ProcessKDP::GetPluginCommandObject() {
1024   if (!m_command_sp)
1025     m_command_sp = std::make_shared<CommandObjectMultiwordProcessKDP>(
1026         GetTarget().GetDebugger().GetCommandInterpreter());
1027   return m_command_sp.get();
1028 }
1029