xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
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 (m_comm.LocalBreakpointsAreSupported()) {
648     Status error;
649     if (!bp_site->IsEnabled()) {
650       if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
651         bp_site->SetEnabled(true);
652         bp_site->SetType(BreakpointSite::eExternal);
653       } else {
654         error.SetErrorString("KDP set breakpoint failed");
655       }
656     }
657     return error;
658   }
659   return EnableSoftwareBreakpoint(bp_site);
660 }
661 
662 Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
663   if (m_comm.LocalBreakpointsAreSupported()) {
664     Status error;
665     if (bp_site->IsEnabled()) {
666       BreakpointSite::Type bp_type = bp_site->GetType();
667       if (bp_type == BreakpointSite::eExternal) {
668         if (m_destroy_in_process && m_comm.IsRunning()) {
669           // We are trying to destroy our connection and we are running
670           bp_site->SetEnabled(false);
671         } else {
672           if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
673             bp_site->SetEnabled(false);
674           else
675             error.SetErrorString("KDP remove breakpoint failed");
676         }
677       } else {
678         error = DisableSoftwareBreakpoint(bp_site);
679       }
680     }
681     return error;
682   }
683   return DisableSoftwareBreakpoint(bp_site);
684 }
685 
686 Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
687   Status error;
688   error.SetErrorString(
689       "watchpoints are not supported in kdp remote debugging");
690   return error;
691 }
692 
693 Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
694   Status error;
695   error.SetErrorString(
696       "watchpoints are not supported in kdp remote debugging");
697   return error;
698 }
699 
700 void ProcessKDP::Clear() { m_thread_list.Clear(); }
701 
702 Status ProcessKDP::DoSignal(int signo) {
703   Status error;
704   error.SetErrorString(
705       "sending signals is not supported in kdp remote debugging");
706   return error;
707 }
708 
709 void ProcessKDP::Initialize() {
710   static llvm::once_flag g_once_flag;
711 
712   llvm::call_once(g_once_flag, []() {
713     PluginManager::RegisterPlugin(GetPluginNameStatic(),
714                                   GetPluginDescriptionStatic(), CreateInstance,
715                                   DebuggerInitialize);
716 
717     ProcessKDPLog::Initialize();
718   });
719 }
720 
721 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
722   if (!PluginManager::GetSettingForProcessPlugin(
723           debugger, PluginProperties::GetSettingName())) {
724     const bool is_global_setting = true;
725     PluginManager::CreateSettingForProcessPlugin(
726         debugger, GetGlobalPluginProperties()->GetValueProperties(),
727         ConstString("Properties for the kdp-remote process plug-in."),
728         is_global_setting);
729   }
730 }
731 
732 bool ProcessKDP::StartAsyncThread() {
733   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
734 
735   LLDB_LOGF(log, "ProcessKDP::StartAsyncThread ()");
736 
737   if (m_async_thread.IsJoinable())
738     return true;
739 
740   llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
741       "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this);
742   if (!async_thread) {
743     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
744              "failed to launch host thread: {}",
745              llvm::toString(async_thread.takeError()));
746     return false;
747   }
748   m_async_thread = *async_thread;
749   return m_async_thread.IsJoinable();
750 }
751 
752 void ProcessKDP::StopAsyncThread() {
753   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
754 
755   LLDB_LOGF(log, "ProcessKDP::StopAsyncThread ()");
756 
757   m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
758 
759   // Stop the stdio thread
760   if (m_async_thread.IsJoinable())
761     m_async_thread.Join(nullptr);
762 }
763 
764 void *ProcessKDP::AsyncThread(void *arg) {
765   ProcessKDP *process = (ProcessKDP *)arg;
766 
767   const lldb::pid_t pid = process->GetID();
768 
769   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
770   LLDB_LOGF(log,
771             "ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
772             ") thread starting...",
773             arg, pid);
774 
775   ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
776   EventSP event_sp;
777   const uint32_t desired_event_mask =
778       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
779 
780   if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
781                                            desired_event_mask) ==
782       desired_event_mask) {
783     bool done = false;
784     while (!done) {
785       LLDB_LOGF(log,
786                 "ProcessKDP::AsyncThread (pid = %" PRIu64
787                 ") listener.WaitForEvent (NULL, event_sp)...",
788                 pid);
789       if (listener_sp->GetEvent(event_sp, llvm::None)) {
790         uint32_t event_type = event_sp->GetType();
791         LLDB_LOGF(log,
792                   "ProcessKDP::AsyncThread (pid = %" PRIu64
793                   ") Got an event of type: %d...",
794                   pid, event_type);
795 
796         // When we are running, poll for 1 second to try and get an exception
797         // to indicate the process has stopped. If we don't get one, check to
798         // make sure no one asked us to exit
799         bool is_running = false;
800         DataExtractor exc_reply_packet;
801         do {
802           switch (event_type) {
803           case eBroadcastBitAsyncContinue: {
804             is_running = true;
805             if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
806                     exc_reply_packet, 1 * USEC_PER_SEC)) {
807               ThreadSP thread_sp(process->GetKernelThread());
808               if (thread_sp) {
809                 lldb::RegisterContextSP reg_ctx_sp(
810                     thread_sp->GetRegisterContext());
811                 if (reg_ctx_sp)
812                   reg_ctx_sp->InvalidateAllRegisters();
813                 static_cast<ThreadKDP *>(thread_sp.get())
814                     ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
815               }
816 
817               // TODO: parse the stop reply packet
818               is_running = false;
819               process->SetPrivateState(eStateStopped);
820             } else {
821               // Check to see if we are supposed to exit. There is no way to
822               // interrupt a running kernel, so all we can do is wait for an
823               // exception or detach...
824               if (listener_sp->GetEvent(event_sp,
825                                         std::chrono::microseconds(0))) {
826                 // We got an event, go through the loop again
827                 event_type = event_sp->GetType();
828               }
829             }
830           } break;
831 
832           case eBroadcastBitAsyncThreadShouldExit:
833             LLDB_LOGF(log,
834                       "ProcessKDP::AsyncThread (pid = %" PRIu64
835                       ") got eBroadcastBitAsyncThreadShouldExit...",
836                       pid);
837             done = true;
838             is_running = false;
839             break;
840 
841           default:
842             LLDB_LOGF(log,
843                       "ProcessKDP::AsyncThread (pid = %" PRIu64
844                       ") got unknown event 0x%8.8x",
845                       pid, event_type);
846             done = true;
847             is_running = false;
848             break;
849           }
850         } while (is_running);
851       } else {
852         LLDB_LOGF(log,
853                   "ProcessKDP::AsyncThread (pid = %" PRIu64
854                   ") listener.WaitForEvent (NULL, event_sp) => false",
855                   pid);
856         done = true;
857       }
858     }
859   }
860 
861   LLDB_LOGF(log,
862             "ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
863             ") thread exiting...",
864             arg, pid);
865 
866   process->m_async_thread.Reset();
867   return NULL;
868 }
869 
870 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
871 private:
872   OptionGroupOptions m_option_group;
873   OptionGroupUInt64 m_command_byte;
874   OptionGroupString m_packet_data;
875 
876   virtual Options *GetOptions() { return &m_option_group; }
877 
878 public:
879   CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
880       : CommandObjectParsed(interpreter, "process plugin packet send",
881                             "Send a custom packet through the KDP protocol by "
882                             "specifying the command byte and the packet "
883                             "payload data. A packet will be sent with a "
884                             "correct header and payload, and the raw result "
885                             "bytes will be displayed as a string value. ",
886                             NULL),
887         m_option_group(),
888         m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
889                        "Specify the command byte to use when sending the KDP "
890                        "request packet.",
891                        0),
892         m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
893                       "Specify packet payload bytes as a hex ASCII string with "
894                       "no spaces or hex prefixes.",
895                       NULL) {
896     m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
897     m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
898     m_option_group.Finalize();
899   }
900 
901   ~CommandObjectProcessKDPPacketSend() {}
902 
903   bool DoExecute(Args &command, CommandReturnObject &result) {
904     const size_t argc = command.GetArgumentCount();
905     if (argc == 0) {
906       if (!m_command_byte.GetOptionValue().OptionWasSet()) {
907         result.AppendError(
908             "the --command option must be set to a valid command byte");
909         result.SetStatus(eReturnStatusFailed);
910       } else {
911         const uint64_t command_byte =
912             m_command_byte.GetOptionValue().GetUInt64Value(0);
913         if (command_byte > 0 && command_byte <= UINT8_MAX) {
914           ProcessKDP *process =
915               (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
916           if (process) {
917             const StateType state = process->GetState();
918 
919             if (StateIsStoppedState(state, true)) {
920               std::vector<uint8_t> payload_bytes;
921               const char *ascii_hex_bytes_cstr =
922                   m_packet_data.GetOptionValue().GetCurrentValue();
923               if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
924                 StringExtractor extractor(ascii_hex_bytes_cstr);
925                 const size_t ascii_hex_bytes_cstr_len =
926                     extractor.GetStringRef().size();
927                 if (ascii_hex_bytes_cstr_len & 1) {
928                   result.AppendErrorWithFormat("payload data must contain an "
929                                                "even number of ASCII hex "
930                                                "characters: '%s'",
931                                                ascii_hex_bytes_cstr);
932                   result.SetStatus(eReturnStatusFailed);
933                   return false;
934                 }
935                 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
936                 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
937                     payload_bytes.size()) {
938                   result.AppendErrorWithFormat("payload data must only contain "
939                                                "ASCII hex characters (no "
940                                                "spaces or hex prefixes): '%s'",
941                                                ascii_hex_bytes_cstr);
942                   result.SetStatus(eReturnStatusFailed);
943                   return false;
944                 }
945               }
946               Status error;
947               DataExtractor reply;
948               process->GetCommunication().SendRawRequest(
949                   command_byte,
950                   payload_bytes.empty() ? NULL : payload_bytes.data(),
951                   payload_bytes.size(), reply, error);
952 
953               if (error.Success()) {
954                 // Copy the binary bytes into a hex ASCII string for the result
955                 StreamString packet;
956                 packet.PutBytesAsRawHex8(
957                     reply.GetDataStart(), reply.GetByteSize(),
958                     endian::InlHostByteOrder(), endian::InlHostByteOrder());
959                 result.AppendMessage(packet.GetString());
960                 result.SetStatus(eReturnStatusSuccessFinishResult);
961                 return true;
962               } else {
963                 const char *error_cstr = error.AsCString();
964                 if (error_cstr && error_cstr[0])
965                   result.AppendError(error_cstr);
966                 else
967                   result.AppendErrorWithFormat("unknown error 0x%8.8x",
968                                                error.GetError());
969                 result.SetStatus(eReturnStatusFailed);
970                 return false;
971               }
972             } else {
973               result.AppendErrorWithFormat("process must be stopped in order "
974                                            "to send KDP packets, state is %s",
975                                            StateAsCString(state));
976               result.SetStatus(eReturnStatusFailed);
977             }
978           } else {
979             result.AppendError("invalid process");
980             result.SetStatus(eReturnStatusFailed);
981           }
982         } else {
983           result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
984                                        ", valid values are 1 - 255",
985                                        command_byte);
986           result.SetStatus(eReturnStatusFailed);
987         }
988       }
989     } else {
990       result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
991                                    m_cmd_name.c_str());
992       result.SetStatus(eReturnStatusFailed);
993     }
994     return false;
995   }
996 };
997 
998 class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
999 private:
1000 public:
1001   CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1002       : CommandObjectMultiword(interpreter, "process plugin packet",
1003                                "Commands that deal with KDP remote packets.",
1004                                NULL) {
1005     LoadSubCommand(
1006         "send",
1007         CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1008   }
1009 
1010   ~CommandObjectProcessKDPPacket() {}
1011 };
1012 
1013 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
1014 public:
1015   CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1016       : CommandObjectMultiword(
1017             interpreter, "process plugin",
1018             "Commands for operating on a ProcessKDP process.",
1019             "process plugin <subcommand> [<subcommand-options>]") {
1020     LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1021                                  interpreter)));
1022   }
1023 
1024   ~CommandObjectMultiwordProcessKDP() {}
1025 };
1026 
1027 CommandObject *ProcessKDP::GetPluginCommandObject() {
1028   if (!m_command_sp)
1029     m_command_sp = std::make_shared<CommandObjectMultiwordProcessKDP>(
1030         GetTarget().GetDebugger().GetCommandInterpreter());
1031   return m_command_sp.get();
1032 }
1033