1 //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 #include <errno.h>
12 #include <stdlib.h>
13 
14 // C++ Includes
15 #include <mutex>
16 
17 // Other libraries and framework includes
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/ModuleSpec.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/UUID.h"
24 #include "lldb/Host/ConnectionFileDescriptor.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/Symbols.h"
27 #include "lldb/Host/ThreadLauncher.h"
28 #include "lldb/Host/common/TCPSocket.h"
29 #include "lldb/Interpreter/CommandInterpreter.h"
30 #include "lldb/Interpreter/CommandObject.h"
31 #include "lldb/Interpreter/CommandObjectMultiword.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/Interpreter/OptionGroupString.h"
34 #include "lldb/Interpreter/OptionGroupUInt64.h"
35 #include "lldb/Interpreter/OptionValueProperties.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Target/RegisterContext.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Thread.h"
40 #include "lldb/Utility/StringExtractor.h"
41 
42 #define USEC_PER_SEC 1000000
43 
44 // Project includes
45 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
46 #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
47 #include "ProcessKDP.h"
48 #include "ProcessKDPLog.h"
49 #include "ThreadKDP.h"
50 
51 using namespace lldb;
52 using namespace lldb_private;
53 
54 namespace {
55 
56 static PropertyDefinition g_properties[] = {
57     {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, NULL,
58      "Specify the default packet timeout in seconds."},
59     {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
60 
61 enum { ePropertyPacketTimeout };
62 
63 class PluginProperties : public Properties {
64 public:
65   static ConstString GetSettingName() {
66     return ProcessKDP::GetPluginNameStatic();
67   }
68 
69   PluginProperties() : Properties() {
70     m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
71     m_collection_sp->Initialize(g_properties);
72   }
73 
74   virtual ~PluginProperties() {}
75 
76   uint64_t GetPacketTimeout() {
77     const uint32_t idx = ePropertyPacketTimeout;
78     return m_collection_sp->GetPropertyAtIndexAsUInt64(
79         NULL, idx, g_properties[idx].default_uint_value);
80   }
81 };
82 
83 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
84 
85 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
86   static ProcessKDPPropertiesSP g_settings_sp;
87   if (!g_settings_sp)
88     g_settings_sp.reset(new PluginProperties());
89   return g_settings_sp;
90 }
91 
92 } // anonymous namespace end
93 
94 static const lldb::tid_t g_kernel_tid = 1;
95 
96 ConstString ProcessKDP::GetPluginNameStatic() {
97   static ConstString g_name("kdp-remote");
98   return g_name;
99 }
100 
101 const char *ProcessKDP::GetPluginDescriptionStatic() {
102   return "KDP Remote protocol based debugging plug-in for darwin kernel "
103          "debugging.";
104 }
105 
106 void ProcessKDP::Terminate() {
107   PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
108 }
109 
110 lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
111                                            ListenerSP listener_sp,
112                                            const FileSpec *crash_file_path) {
113   lldb::ProcessSP process_sp;
114   if (crash_file_path == NULL)
115     process_sp.reset(new ProcessKDP(target_sp, listener_sp));
116   return process_sp;
117 }
118 
119 bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
120   if (plugin_specified_by_name)
121     return true;
122 
123   // For now we are just making sure the file exists for a given module
124   Module *exe_module = target_sp->GetExecutableModulePointer();
125   if (exe_module) {
126     const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
127     switch (triple_ref.getOS()) {
128     case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
129                                // iOS, but accept darwin just in case
130     case llvm::Triple::MacOSX: // For desktop targets
131     case llvm::Triple::IOS:    // For arm targets
132     case llvm::Triple::TvOS:
133     case llvm::Triple::WatchOS:
134       if (triple_ref.getVendor() == llvm::Triple::Apple) {
135         ObjectFile *exe_objfile = exe_module->GetObjectFile();
136         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
137             exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
138           return true;
139       }
140       break;
141 
142     default:
143       break;
144     }
145   }
146   return false;
147 }
148 
149 //----------------------------------------------------------------------
150 // ProcessKDP constructor
151 //----------------------------------------------------------------------
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 //----------------------------------------------------------------------
169 // Destructor
170 //----------------------------------------------------------------------
171 ProcessKDP::~ProcessKDP() {
172   Clear();
173   // We need to call finalize on the process before destroying ourselves
174   // to make sure all of the broadcaster cleanup goes as planned. If we
175   // destruct this class, then Process::~Process() might have problems
176   // trying to fully destroy the broadcaster.
177   Finalize();
178 }
179 
180 //----------------------------------------------------------------------
181 // PluginInterface
182 //----------------------------------------------------------------------
183 lldb_private::ConstString ProcessKDP::GetPluginName() {
184   return GetPluginNameStatic();
185 }
186 
187 uint32_t ProcessKDP::GetPluginVersion() { return 1; }
188 
189 Error ProcessKDP::WillLaunch(Module *module) {
190   Error error;
191   error.SetErrorString("launching not supported in kdp-remote plug-in");
192   return error;
193 }
194 
195 Error ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) {
196   Error error;
197   error.SetErrorString(
198       "attaching to a by process ID not supported in kdp-remote plug-in");
199   return error;
200 }
201 
202 Error ProcessKDP::WillAttachToProcessWithName(const char *process_name,
203                                               bool wait_for_launch) {
204   Error error;
205   error.SetErrorString(
206       "attaching to a by process name not supported in kdp-remote plug-in");
207   return error;
208 }
209 
210 bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) {
211   uint32_t cpu = m_comm.GetCPUType();
212   if (cpu) {
213     uint32_t sub = m_comm.GetCPUSubtype();
214     arch.SetArchitecture(eArchTypeMachO, cpu, sub);
215     // Leave architecture vendor as unspecified unknown
216     arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
217     arch.GetTriple().setVendorName(llvm::StringRef());
218     return true;
219   }
220   arch.Clear();
221   return false;
222 }
223 
224 Error ProcessKDP::DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
225   Error error;
226 
227   // Don't let any JIT happen when doing KDP as we can't allocate
228   // memory and we don't want to be mucking with threads that might
229   // already be handling exceptions
230   SetCanJIT(false);
231 
232   if (remote_url.empty()) {
233     error.SetErrorStringWithFormat("empty connection URL");
234     return error;
235   }
236 
237   std::unique_ptr<ConnectionFileDescriptor> conn_ap(
238       new ConnectionFileDescriptor());
239   if (conn_ap.get()) {
240     // Only try once for now.
241     // TODO: check if we should be retrying?
242     const uint32_t max_retry_count = 1;
243     for (uint32_t retry_count = 0; retry_count < max_retry_count;
244          ++retry_count) {
245       if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
246         break;
247       usleep(100000);
248     }
249   }
250 
251   if (conn_ap->IsConnected()) {
252     const TCPSocket &socket =
253         static_cast<const TCPSocket &>(*conn_ap->GetReadObject());
254     const uint16_t reply_port = socket.GetLocalPortNumber();
255 
256     if (reply_port != 0) {
257       m_comm.SetConnection(conn_ap.release());
258 
259       if (m_comm.SendRequestReattach(reply_port)) {
260         if (m_comm.SendRequestConnect(reply_port, reply_port,
261                                       "Greetings from LLDB...")) {
262           m_comm.GetVersion();
263 
264           Target &target = GetTarget();
265           ArchSpec kernel_arch;
266           // The host architecture
267           GetHostArchitecture(kernel_arch);
268           ArchSpec target_arch = target.GetArchitecture();
269           // Merge in any unspecified stuff into the target architecture in
270           // case the target arch isn't set at all or incompletely.
271           target_arch.MergeFrom(kernel_arch);
272           target.SetArchitecture(target_arch);
273 
274           /* Get the kernel's UUID and load address via KDP_KERNELVERSION
275            * packet.  */
276           /* An EFI kdp session has neither UUID nor load address. */
277 
278           UUID kernel_uuid = m_comm.GetUUID();
279           addr_t kernel_load_addr = m_comm.GetLoadAddress();
280 
281           if (m_comm.RemoteIsEFI()) {
282             // Select an invalid plugin name for the dynamic loader so one
283             // doesn't get used
284             // since EFI does its own manual loading via python scripting
285             static ConstString g_none_dynamic_loader("none");
286             m_dyld_plugin_name = g_none_dynamic_loader;
287 
288             if (kernel_uuid.IsValid()) {
289               // If EFI passed in a UUID= try to lookup UUID
290               // The slide will not be provided. But the UUID
291               // lookup will be used to launch EFI debug scripts
292               // from the dSYM, that can load all of the symbols.
293               ModuleSpec module_spec;
294               module_spec.GetUUID() = kernel_uuid;
295               module_spec.GetArchitecture() = target.GetArchitecture();
296 
297               // Lookup UUID locally, before attempting dsymForUUID like action
298               module_spec.GetSymbolFileSpec() =
299                   Symbols::LocateExecutableSymbolFile(module_spec);
300               if (module_spec.GetSymbolFileSpec()) {
301                 ModuleSpec executable_module_spec =
302                     Symbols::LocateExecutableObjectFile(module_spec);
303                 if (executable_module_spec.GetFileSpec().Exists()) {
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 (module_spec.GetFileSpec().Exists()) {
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, false);
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 Error ProcessKDP::DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
376   Error error;
377   error.SetErrorString("launching not supported in kdp-remote plug-in");
378   return error;
379 }
380 
381 Error ProcessKDP::DoAttachToProcessWithID(
382     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
383   Error error;
384   error.SetErrorString(
385       "attach to process by ID is not suppported in kdp remote debugging");
386   return error;
387 }
388 
389 Error ProcessKDP::DoAttachToProcessWithName(
390     const char *process_name, const ProcessAttachInfo &attach_info) {
391   Error error;
392   error.SetErrorString(
393       "attach to process by name is not suppported 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   if (log)
402     log->Printf("ProcessKDP::DidAttach()");
403   if (GetID() != LLDB_INVALID_PROCESS_ID) {
404     GetHostArchitecture(process_arch);
405   }
406 }
407 
408 addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
409 
410 lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
411   if (m_dyld_ap.get() == NULL)
412     m_dyld_ap.reset(DynamicLoader::FindPlugin(
413         this,
414         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
415   return m_dyld_ap.get();
416 }
417 
418 Error ProcessKDP::WillResume() { return Error(); }
419 
420 Error ProcessKDP::DoResume() {
421   Error error;
422   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
423   // Only start the async thread if we try to do any process control
424   if (!m_async_thread.IsJoinable())
425     StartAsyncThread();
426 
427   bool resume = false;
428 
429   // With KDP there is only one thread we can tell what to do
430   ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
431 
432   if (kernel_thread_sp) {
433     const StateType thread_resume_state =
434         kernel_thread_sp->GetTemporaryResumeState();
435 
436     if (log)
437       log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
438                   StateAsCString(thread_resume_state));
439     switch (thread_resume_state) {
440     case eStateSuspended:
441       // Nothing to do here when a thread will stay suspended
442       // we just leave the CPU mask bit set to zero for the thread
443       if (log)
444         log->Printf("ProcessKDP::DoResume() = suspended???");
445       break;
446 
447     case eStateStepping: {
448       lldb::RegisterContextSP reg_ctx_sp(
449           kernel_thread_sp->GetRegisterContext());
450 
451       if (reg_ctx_sp) {
452         if (log)
453           log->Printf(
454               "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
455         reg_ctx_sp->HardwareSingleStep(true);
456         resume = true;
457       } else {
458         error.SetErrorStringWithFormat(
459             "KDP thread 0x%llx has no register context",
460             kernel_thread_sp->GetID());
461       }
462     } break;
463 
464     case eStateRunning: {
465       lldb::RegisterContextSP reg_ctx_sp(
466           kernel_thread_sp->GetRegisterContext());
467 
468       if (reg_ctx_sp) {
469         if (log)
470           log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
471                       "(false);");
472         reg_ctx_sp->HardwareSingleStep(false);
473         resume = true;
474       } else {
475         error.SetErrorStringWithFormat(
476             "KDP thread 0x%llx has no register context",
477             kernel_thread_sp->GetID());
478       }
479     } break;
480 
481     default:
482       // The only valid thread resume states are listed above
483       assert(!"invalid thread resume state");
484       break;
485     }
486   }
487 
488   if (resume) {
489     if (log)
490       log->Printf("ProcessKDP::DoResume () sending resume");
491 
492     if (m_comm.SendRequestResume()) {
493       m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
494       SetPrivateState(eStateRunning);
495     } else
496       error.SetErrorString("KDP resume failed");
497   } else {
498     error.SetErrorString("kernel thread is suspended");
499   }
500 
501   return error;
502 }
503 
504 lldb::ThreadSP ProcessKDP::GetKernelThread() {
505   // KDP only tells us about one thread/core. Any other threads will usually
506   // be the ones that are read from memory by the OS plug-ins.
507 
508   ThreadSP thread_sp(m_kernel_thread_wp.lock());
509   if (!thread_sp) {
510     thread_sp.reset(new ThreadKDP(*this, g_kernel_tid));
511     m_kernel_thread_wp = thread_sp;
512   }
513   return thread_sp;
514 }
515 
516 bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
517                                   ThreadList &new_thread_list) {
518   // locker will keep a mutex locked until it goes out of scope
519   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
520   if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
521     log->Printf("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
522 
523   // Even though there is a CPU mask, it doesn't mean we can see each CPU
524   // individually, there is really only one. Lets call this thread 1.
525   ThreadSP thread_sp(
526       old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
527   if (!thread_sp)
528     thread_sp = GetKernelThread();
529   new_thread_list.AddThread(thread_sp);
530 
531   return new_thread_list.GetSize(false) > 0;
532 }
533 
534 void ProcessKDP::RefreshStateAfterStop() {
535   // Let all threads recover from stopping and do any clean up based
536   // on the previous thread state (if any).
537   m_thread_list.RefreshStateAfterStop();
538 }
539 
540 Error ProcessKDP::DoHalt(bool &caused_stop) {
541   Error error;
542 
543   if (m_comm.IsRunning()) {
544     if (m_destroy_in_process) {
545       // If we are attemping to destroy, we need to not return an error to
546       // Halt or DoDestroy won't get called.
547       // We are also currently running, so send a process stopped event
548       SetPrivateState(eStateStopped);
549     } else {
550       error.SetErrorString("KDP cannot interrupt a running kernel");
551     }
552   }
553   return error;
554 }
555 
556 Error ProcessKDP::DoDetach(bool keep_stopped) {
557   Error error;
558   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
559   if (log)
560     log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
561 
562   if (m_comm.IsRunning()) {
563     // We are running and we can't interrupt a running kernel, so we need
564     // to just close the connection to the kernel and hope for the best
565   } else {
566     // If we are going to keep the target stopped, then don't send the
567     // disconnect message.
568     if (!keep_stopped && m_comm.IsConnected()) {
569       const bool success = m_comm.SendRequestDisconnect();
570       if (log) {
571         if (success)
572           log->PutCString(
573               "ProcessKDP::DoDetach() detach packet sent successfully");
574         else
575           log->PutCString(
576               "ProcessKDP::DoDetach() connection channel shutdown failed");
577       }
578       m_comm.Disconnect();
579     }
580   }
581   StopAsyncThread();
582   m_comm.Clear();
583 
584   SetPrivateState(eStateDetached);
585   ResumePrivateStateThread();
586 
587   // KillDebugserverProcess ();
588   return error;
589 }
590 
591 Error ProcessKDP::DoDestroy() {
592   // For KDP there really is no difference between destroy and detach
593   bool keep_stopped = false;
594   return DoDetach(keep_stopped);
595 }
596 
597 //------------------------------------------------------------------
598 // Process Queries
599 //------------------------------------------------------------------
600 
601 bool ProcessKDP::IsAlive() {
602   return m_comm.IsConnected() && Process::IsAlive();
603 }
604 
605 //------------------------------------------------------------------
606 // Process Memory
607 //------------------------------------------------------------------
608 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
609                                 Error &error) {
610   uint8_t *data_buffer = (uint8_t *)buf;
611   if (m_comm.IsConnected()) {
612     const size_t max_read_size = 512;
613     size_t total_bytes_read = 0;
614 
615     // Read the requested amount of memory in 512 byte chunks
616     while (total_bytes_read < size) {
617       size_t bytes_to_read_this_request = size - total_bytes_read;
618       if (bytes_to_read_this_request > max_read_size) {
619         bytes_to_read_this_request = max_read_size;
620       }
621       size_t bytes_read = m_comm.SendRequestReadMemory(
622           addr + total_bytes_read, data_buffer + total_bytes_read,
623           bytes_to_read_this_request, error);
624       total_bytes_read += bytes_read;
625       if (error.Fail() || bytes_read == 0) {
626         return total_bytes_read;
627       }
628     }
629 
630     return total_bytes_read;
631   }
632   error.SetErrorString("not connected");
633   return 0;
634 }
635 
636 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
637                                  Error &error) {
638   if (m_comm.IsConnected())
639     return m_comm.SendRequestWriteMemory(addr, buf, size, error);
640   error.SetErrorString("not connected");
641   return 0;
642 }
643 
644 lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
645                                           Error &error) {
646   error.SetErrorString(
647       "memory allocation not suppported in kdp remote debugging");
648   return LLDB_INVALID_ADDRESS;
649 }
650 
651 Error ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
652   Error error;
653   error.SetErrorString(
654       "memory deallocation not suppported in kdp remote debugging");
655   return error;
656 }
657 
658 Error ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
659   if (m_comm.LocalBreakpointsAreSupported()) {
660     Error error;
661     if (!bp_site->IsEnabled()) {
662       if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
663         bp_site->SetEnabled(true);
664         bp_site->SetType(BreakpointSite::eExternal);
665       } else {
666         error.SetErrorString("KDP set breakpoint failed");
667       }
668     }
669     return error;
670   }
671   return EnableSoftwareBreakpoint(bp_site);
672 }
673 
674 Error ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
675   if (m_comm.LocalBreakpointsAreSupported()) {
676     Error error;
677     if (bp_site->IsEnabled()) {
678       BreakpointSite::Type bp_type = bp_site->GetType();
679       if (bp_type == BreakpointSite::eExternal) {
680         if (m_destroy_in_process && m_comm.IsRunning()) {
681           // We are trying to destroy our connection and we are running
682           bp_site->SetEnabled(false);
683         } else {
684           if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
685             bp_site->SetEnabled(false);
686           else
687             error.SetErrorString("KDP remove breakpoint failed");
688         }
689       } else {
690         error = DisableSoftwareBreakpoint(bp_site);
691       }
692     }
693     return error;
694   }
695   return DisableSoftwareBreakpoint(bp_site);
696 }
697 
698 Error ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
699   Error error;
700   error.SetErrorString(
701       "watchpoints are not suppported in kdp remote debugging");
702   return error;
703 }
704 
705 Error ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
706   Error error;
707   error.SetErrorString(
708       "watchpoints are not suppported in kdp remote debugging");
709   return error;
710 }
711 
712 void ProcessKDP::Clear() { m_thread_list.Clear(); }
713 
714 Error ProcessKDP::DoSignal(int signo) {
715   Error error;
716   error.SetErrorString(
717       "sending signals is not suppported in kdp remote debugging");
718   return error;
719 }
720 
721 void ProcessKDP::Initialize() {
722   static std::once_flag g_once_flag;
723 
724   std::call_once(g_once_flag, []() {
725     PluginManager::RegisterPlugin(GetPluginNameStatic(),
726                                   GetPluginDescriptionStatic(), CreateInstance,
727                                   DebuggerInitialize);
728 
729     Log::Callbacks log_callbacks = {ProcessKDPLog::DisableLog,
730                                     ProcessKDPLog::EnableLog,
731                                     ProcessKDPLog::ListLogCategories};
732 
733     Log::RegisterLogChannel(ProcessKDP::GetPluginNameStatic(), log_callbacks);
734   });
735 }
736 
737 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
738   if (!PluginManager::GetSettingForProcessPlugin(
739           debugger, PluginProperties::GetSettingName())) {
740     const bool is_global_setting = true;
741     PluginManager::CreateSettingForProcessPlugin(
742         debugger, GetGlobalPluginProperties()->GetValueProperties(),
743         ConstString("Properties for the kdp-remote process plug-in."),
744         is_global_setting);
745   }
746 }
747 
748 bool ProcessKDP::StartAsyncThread() {
749   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
750 
751   if (log)
752     log->Printf("ProcessKDP::StartAsyncThread ()");
753 
754   if (m_async_thread.IsJoinable())
755     return true;
756 
757   m_async_thread = ThreadLauncher::LaunchThread(
758       "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
759   return m_async_thread.IsJoinable();
760 }
761 
762 void ProcessKDP::StopAsyncThread() {
763   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
764 
765   if (log)
766     log->Printf("ProcessKDP::StopAsyncThread ()");
767 
768   m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
769 
770   // Stop the stdio thread
771   if (m_async_thread.IsJoinable())
772     m_async_thread.Join(nullptr);
773 }
774 
775 void *ProcessKDP::AsyncThread(void *arg) {
776   ProcessKDP *process = (ProcessKDP *)arg;
777 
778   const lldb::pid_t pid = process->GetID();
779 
780   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
781   if (log)
782     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
783                 ") thread starting...",
784                 arg, pid);
785 
786   ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
787   EventSP event_sp;
788   const uint32_t desired_event_mask =
789       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
790 
791   if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
792                                            desired_event_mask) ==
793       desired_event_mask) {
794     bool done = false;
795     while (!done) {
796       if (log)
797         log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
798                     ") listener.WaitForEvent (NULL, event_sp)...",
799                     pid);
800       if (listener_sp->GetEvent(event_sp, llvm::None)) {
801         uint32_t event_type = event_sp->GetType();
802         if (log)
803           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
804                       ") Got an event of type: %d...",
805                       pid, event_type);
806 
807         // When we are running, poll for 1 second to try and get an exception
808         // to indicate the process has stopped. If we don't get one, check to
809         // make sure no one asked us to exit
810         bool is_running = false;
811         DataExtractor exc_reply_packet;
812         do {
813           switch (event_type) {
814           case eBroadcastBitAsyncContinue: {
815             is_running = true;
816             if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
817                     exc_reply_packet, 1 * USEC_PER_SEC)) {
818               ThreadSP thread_sp(process->GetKernelThread());
819               if (thread_sp) {
820                 lldb::RegisterContextSP reg_ctx_sp(
821                     thread_sp->GetRegisterContext());
822                 if (reg_ctx_sp)
823                   reg_ctx_sp->InvalidateAllRegisters();
824                 static_cast<ThreadKDP *>(thread_sp.get())
825                     ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
826               }
827 
828               // TODO: parse the stop reply packet
829               is_running = false;
830               process->SetPrivateState(eStateStopped);
831             } else {
832               // Check to see if we are supposed to exit. There is no way to
833               // interrupt a running kernel, so all we can do is wait for an
834               // exception or detach...
835               if (listener_sp->GetEvent(event_sp,
836                                         std::chrono::microseconds(0))) {
837                 // We got an event, go through the loop again
838                 event_type = event_sp->GetType();
839               }
840             }
841           } break;
842 
843           case eBroadcastBitAsyncThreadShouldExit:
844             if (log)
845               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
846                           ") got eBroadcastBitAsyncThreadShouldExit...",
847                           pid);
848             done = true;
849             is_running = false;
850             break;
851 
852           default:
853             if (log)
854               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
855                           ") got unknown event 0x%8.8x",
856                           pid, event_type);
857             done = true;
858             is_running = false;
859             break;
860           }
861         } while (is_running);
862       } else {
863         if (log)
864           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
865                       ") listener.WaitForEvent (NULL, event_sp) => false",
866                       pid);
867         done = true;
868       }
869     }
870   }
871 
872   if (log)
873     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
874                 ") thread exiting...",
875                 arg, pid);
876 
877   process->m_async_thread.Reset();
878   return NULL;
879 }
880 
881 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
882 private:
883   OptionGroupOptions m_option_group;
884   OptionGroupUInt64 m_command_byte;
885   OptionGroupString m_packet_data;
886 
887   virtual Options *GetOptions() { return &m_option_group; }
888 
889 public:
890   CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
891       : CommandObjectParsed(interpreter, "process plugin packet send",
892                             "Send a custom packet through the KDP protocol by "
893                             "specifying the command byte and the packet "
894                             "payload data. A packet will be sent with a "
895                             "correct header and payload, and the raw result "
896                             "bytes will be displayed as a string value. ",
897                             NULL),
898         m_option_group(),
899         m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
900                        "Specify the command byte to use when sending the KDP "
901                        "request packet.",
902                        0),
903         m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
904                       "Specify packet payload bytes as a hex ASCII string with "
905                       "no spaces or hex prefixes.",
906                       NULL) {
907     m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
908     m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
909     m_option_group.Finalize();
910   }
911 
912   ~CommandObjectProcessKDPPacketSend() {}
913 
914   bool DoExecute(Args &command, CommandReturnObject &result) {
915     const size_t argc = command.GetArgumentCount();
916     if (argc == 0) {
917       if (!m_command_byte.GetOptionValue().OptionWasSet()) {
918         result.AppendError(
919             "the --command option must be set to a valid command byte");
920         result.SetStatus(eReturnStatusFailed);
921       } else {
922         const uint64_t command_byte =
923             m_command_byte.GetOptionValue().GetUInt64Value(0);
924         if (command_byte > 0 && command_byte <= UINT8_MAX) {
925           ProcessKDP *process =
926               (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
927           if (process) {
928             const StateType state = process->GetState();
929 
930             if (StateIsStoppedState(state, true)) {
931               std::vector<uint8_t> payload_bytes;
932               const char *ascii_hex_bytes_cstr =
933                   m_packet_data.GetOptionValue().GetCurrentValue();
934               if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
935                 StringExtractor extractor(ascii_hex_bytes_cstr);
936                 const size_t ascii_hex_bytes_cstr_len =
937                     extractor.GetStringRef().size();
938                 if (ascii_hex_bytes_cstr_len & 1) {
939                   result.AppendErrorWithFormat("payload data must contain an "
940                                                "even number of ASCII hex "
941                                                "characters: '%s'",
942                                                ascii_hex_bytes_cstr);
943                   result.SetStatus(eReturnStatusFailed);
944                   return false;
945                 }
946                 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
947                 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
948                     payload_bytes.size()) {
949                   result.AppendErrorWithFormat("payload data must only contain "
950                                                "ASCII hex characters (no "
951                                                "spaces or hex prefixes): '%s'",
952                                                ascii_hex_bytes_cstr);
953                   result.SetStatus(eReturnStatusFailed);
954                   return false;
955                 }
956               }
957               Error error;
958               DataExtractor reply;
959               process->GetCommunication().SendRawRequest(
960                   command_byte,
961                   payload_bytes.empty() ? NULL : payload_bytes.data(),
962                   payload_bytes.size(), reply, error);
963 
964               if (error.Success()) {
965                 // Copy the binary bytes into a hex ASCII string for the result
966                 StreamString packet;
967                 packet.PutBytesAsRawHex8(
968                     reply.GetDataStart(), reply.GetByteSize(),
969                     endian::InlHostByteOrder(), endian::InlHostByteOrder());
970                 result.AppendMessage(packet.GetString());
971                 result.SetStatus(eReturnStatusSuccessFinishResult);
972                 return true;
973               } else {
974                 const char *error_cstr = error.AsCString();
975                 if (error_cstr && error_cstr[0])
976                   result.AppendError(error_cstr);
977                 else
978                   result.AppendErrorWithFormat("unknown error 0x%8.8x",
979                                                error.GetError());
980                 result.SetStatus(eReturnStatusFailed);
981                 return false;
982               }
983             } else {
984               result.AppendErrorWithFormat("process must be stopped in order "
985                                            "to send KDP packets, state is %s",
986                                            StateAsCString(state));
987               result.SetStatus(eReturnStatusFailed);
988             }
989           } else {
990             result.AppendError("invalid process");
991             result.SetStatus(eReturnStatusFailed);
992           }
993         } else {
994           result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
995                                        ", valid values are 1 - 255",
996                                        command_byte);
997           result.SetStatus(eReturnStatusFailed);
998         }
999       }
1000     } else {
1001       result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
1002                                    m_cmd_name.c_str());
1003       result.SetStatus(eReturnStatusFailed);
1004     }
1005     return false;
1006   }
1007 };
1008 
1009 class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
1010 private:
1011 public:
1012   CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1013       : CommandObjectMultiword(interpreter, "process plugin packet",
1014                                "Commands that deal with KDP remote packets.",
1015                                NULL) {
1016     LoadSubCommand(
1017         "send",
1018         CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1019   }
1020 
1021   ~CommandObjectProcessKDPPacket() {}
1022 };
1023 
1024 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
1025 public:
1026   CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1027       : CommandObjectMultiword(
1028             interpreter, "process plugin",
1029             "Commands for operating on a ProcessKDP process.",
1030             "process plugin <subcommand> [<subcommand-options>]") {
1031     LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1032                                  interpreter)));
1033   }
1034 
1035   ~CommandObjectMultiwordProcessKDP() {}
1036 };
1037 
1038 CommandObject *ProcessKDP::GetPluginCommandObject() {
1039   if (!m_command_sp)
1040     m_command_sp.reset(new CommandObjectMultiwordProcessKDP(
1041         GetTarget().GetDebugger().GetCommandInterpreter()));
1042   return m_command_sp.get();
1043 }
1044