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