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