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(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, const char *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 == NULL || remote_url[0] == '\0') {
233     error.SetErrorStringWithFormat("invalid connection URL '%s'", remote_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'", remote_url);
364   }
365   if (error.Fail())
366     m_comm.Disconnect();
367 
368   return error;
369 }
370 
371 //----------------------------------------------------------------------
372 // Process Control
373 //----------------------------------------------------------------------
374 Error ProcessKDP::DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
375   Error error;
376   error.SetErrorString("launching not supported in kdp-remote plug-in");
377   return error;
378 }
379 
380 Error ProcessKDP::DoAttachToProcessWithID(
381     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
382   Error error;
383   error.SetErrorString(
384       "attach to process by ID is not suppported in kdp remote debugging");
385   return error;
386 }
387 
388 Error ProcessKDP::DoAttachToProcessWithName(
389     const char *process_name, const ProcessAttachInfo &attach_info) {
390   Error error;
391   error.SetErrorString(
392       "attach to process by name is not suppported in kdp remote debugging");
393   return error;
394 }
395 
396 void ProcessKDP::DidAttach(ArchSpec &process_arch) {
397   Process::DidAttach(process_arch);
398 
399   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
400   if (log)
401     log->Printf("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_ap.get() == NULL)
411     m_dyld_ap.reset(DynamicLoader::FindPlugin(
412         this,
413         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
414   return m_dyld_ap.get();
415 }
416 
417 Error ProcessKDP::WillResume() { return Error(); }
418 
419 Error ProcessKDP::DoResume() {
420   Error 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     if (log)
436       log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
437                   StateAsCString(thread_resume_state));
438     switch (thread_resume_state) {
439     case eStateSuspended:
440       // Nothing to do here when a thread will stay suspended
441       // we just leave the CPU mask bit set to zero for the thread
442       if (log)
443         log->Printf("ProcessKDP::DoResume() = suspended???");
444       break;
445 
446     case eStateStepping: {
447       lldb::RegisterContextSP reg_ctx_sp(
448           kernel_thread_sp->GetRegisterContext());
449 
450       if (reg_ctx_sp) {
451         if (log)
452           log->Printf(
453               "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
454         reg_ctx_sp->HardwareSingleStep(true);
455         resume = true;
456       } else {
457         error.SetErrorStringWithFormat(
458             "KDP thread 0x%llx has no register context",
459             kernel_thread_sp->GetID());
460       }
461     } break;
462 
463     case eStateRunning: {
464       lldb::RegisterContextSP reg_ctx_sp(
465           kernel_thread_sp->GetRegisterContext());
466 
467       if (reg_ctx_sp) {
468         if (log)
469           log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
470                       "(false);");
471         reg_ctx_sp->HardwareSingleStep(false);
472         resume = true;
473       } else {
474         error.SetErrorStringWithFormat(
475             "KDP thread 0x%llx has no register context",
476             kernel_thread_sp->GetID());
477       }
478     } break;
479 
480     default:
481       // The only valid thread resume states are listed above
482       assert(!"invalid thread resume state");
483       break;
484     }
485   }
486 
487   if (resume) {
488     if (log)
489       log->Printf("ProcessKDP::DoResume () sending resume");
490 
491     if (m_comm.SendRequestResume()) {
492       m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
493       SetPrivateState(eStateRunning);
494     } else
495       error.SetErrorString("KDP resume failed");
496   } else {
497     error.SetErrorString("kernel thread is suspended");
498   }
499 
500   return error;
501 }
502 
503 lldb::ThreadSP ProcessKDP::GetKernelThread() {
504   // KDP only tells us about one thread/core. Any other threads will usually
505   // be the ones that are read from memory by the OS plug-ins.
506 
507   ThreadSP thread_sp(m_kernel_thread_wp.lock());
508   if (!thread_sp) {
509     thread_sp.reset(new ThreadKDP(*this, g_kernel_tid));
510     m_kernel_thread_wp = thread_sp;
511   }
512   return thread_sp;
513 }
514 
515 bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
516                                   ThreadList &new_thread_list) {
517   // locker will keep a mutex locked until it goes out of scope
518   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
519   if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
520     log->Printf("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
521 
522   // Even though there is a CPU mask, it doesn't mean we can see each CPU
523   // individually, there is really only one. Lets call this thread 1.
524   ThreadSP thread_sp(
525       old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
526   if (!thread_sp)
527     thread_sp = GetKernelThread();
528   new_thread_list.AddThread(thread_sp);
529 
530   return new_thread_list.GetSize(false) > 0;
531 }
532 
533 void ProcessKDP::RefreshStateAfterStop() {
534   // Let all threads recover from stopping and do any clean up based
535   // on the previous thread state (if any).
536   m_thread_list.RefreshStateAfterStop();
537 }
538 
539 Error ProcessKDP::DoHalt(bool &caused_stop) {
540   Error error;
541 
542   if (m_comm.IsRunning()) {
543     if (m_destroy_in_process) {
544       // If we are attemping to destroy, we need to not return an error to
545       // Halt or DoDestroy won't get called.
546       // We are also currently running, so send a process stopped event
547       SetPrivateState(eStateStopped);
548     } else {
549       error.SetErrorString("KDP cannot interrupt a running kernel");
550     }
551   }
552   return error;
553 }
554 
555 Error ProcessKDP::DoDetach(bool keep_stopped) {
556   Error error;
557   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
558   if (log)
559     log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
560 
561   if (m_comm.IsRunning()) {
562     // We are running and we can't interrupt a running kernel, so we need
563     // to just close the connection to the kernel and hope for the best
564   } else {
565     // If we are going to keep the target stopped, then don't send the
566     // disconnect message.
567     if (!keep_stopped && m_comm.IsConnected()) {
568       const bool success = m_comm.SendRequestDisconnect();
569       if (log) {
570         if (success)
571           log->PutCString(
572               "ProcessKDP::DoDetach() detach packet sent successfully");
573         else
574           log->PutCString(
575               "ProcessKDP::DoDetach() connection channel shutdown failed");
576       }
577       m_comm.Disconnect();
578     }
579   }
580   StopAsyncThread();
581   m_comm.Clear();
582 
583   SetPrivateState(eStateDetached);
584   ResumePrivateStateThread();
585 
586   // KillDebugserverProcess ();
587   return error;
588 }
589 
590 Error ProcessKDP::DoDestroy() {
591   // For KDP there really is no difference between destroy and detach
592   bool keep_stopped = false;
593   return DoDetach(keep_stopped);
594 }
595 
596 //------------------------------------------------------------------
597 // Process Queries
598 //------------------------------------------------------------------
599 
600 bool ProcessKDP::IsAlive() {
601   return m_comm.IsConnected() && Process::IsAlive();
602 }
603 
604 //------------------------------------------------------------------
605 // Process Memory
606 //------------------------------------------------------------------
607 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
608                                 Error &error) {
609   uint8_t *data_buffer = (uint8_t *)buf;
610   if (m_comm.IsConnected()) {
611     const size_t max_read_size = 512;
612     size_t total_bytes_read = 0;
613 
614     // Read the requested amount of memory in 512 byte chunks
615     while (total_bytes_read < size) {
616       size_t bytes_to_read_this_request = size - total_bytes_read;
617       if (bytes_to_read_this_request > max_read_size) {
618         bytes_to_read_this_request = max_read_size;
619       }
620       size_t bytes_read = m_comm.SendRequestReadMemory(
621           addr + total_bytes_read, data_buffer + total_bytes_read,
622           bytes_to_read_this_request, error);
623       total_bytes_read += bytes_read;
624       if (error.Fail() || bytes_read == 0) {
625         return total_bytes_read;
626       }
627     }
628 
629     return total_bytes_read;
630   }
631   error.SetErrorString("not connected");
632   return 0;
633 }
634 
635 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
636                                  Error &error) {
637   if (m_comm.IsConnected())
638     return m_comm.SendRequestWriteMemory(addr, buf, size, error);
639   error.SetErrorString("not connected");
640   return 0;
641 }
642 
643 lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
644                                           Error &error) {
645   error.SetErrorString(
646       "memory allocation not suppported in kdp remote debugging");
647   return LLDB_INVALID_ADDRESS;
648 }
649 
650 Error ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
651   Error error;
652   error.SetErrorString(
653       "memory deallocation not suppported in kdp remote debugging");
654   return error;
655 }
656 
657 Error ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
658   if (m_comm.LocalBreakpointsAreSupported()) {
659     Error error;
660     if (!bp_site->IsEnabled()) {
661       if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
662         bp_site->SetEnabled(true);
663         bp_site->SetType(BreakpointSite::eExternal);
664       } else {
665         error.SetErrorString("KDP set breakpoint failed");
666       }
667     }
668     return error;
669   }
670   return EnableSoftwareBreakpoint(bp_site);
671 }
672 
673 Error ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
674   if (m_comm.LocalBreakpointsAreSupported()) {
675     Error error;
676     if (bp_site->IsEnabled()) {
677       BreakpointSite::Type bp_type = bp_site->GetType();
678       if (bp_type == BreakpointSite::eExternal) {
679         if (m_destroy_in_process && m_comm.IsRunning()) {
680           // We are trying to destroy our connection and we are running
681           bp_site->SetEnabled(false);
682         } else {
683           if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
684             bp_site->SetEnabled(false);
685           else
686             error.SetErrorString("KDP remove breakpoint failed");
687         }
688       } else {
689         error = DisableSoftwareBreakpoint(bp_site);
690       }
691     }
692     return error;
693   }
694   return DisableSoftwareBreakpoint(bp_site);
695 }
696 
697 Error ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
698   Error error;
699   error.SetErrorString(
700       "watchpoints are not suppported in kdp remote debugging");
701   return error;
702 }
703 
704 Error ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
705   Error error;
706   error.SetErrorString(
707       "watchpoints are not suppported in kdp remote debugging");
708   return error;
709 }
710 
711 void ProcessKDP::Clear() { m_thread_list.Clear(); }
712 
713 Error ProcessKDP::DoSignal(int signo) {
714   Error error;
715   error.SetErrorString(
716       "sending signals is not suppported in kdp remote debugging");
717   return error;
718 }
719 
720 void ProcessKDP::Initialize() {
721   static std::once_flag g_once_flag;
722 
723   std::call_once(g_once_flag, []() {
724     PluginManager::RegisterPlugin(GetPluginNameStatic(),
725                                   GetPluginDescriptionStatic(), CreateInstance,
726                                   DebuggerInitialize);
727 
728     Log::Callbacks log_callbacks = {ProcessKDPLog::DisableLog,
729                                     ProcessKDPLog::EnableLog,
730                                     ProcessKDPLog::ListLogCategories};
731 
732     Log::RegisterLogChannel(ProcessKDP::GetPluginNameStatic(), log_callbacks);
733   });
734 }
735 
736 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
737   if (!PluginManager::GetSettingForProcessPlugin(
738           debugger, PluginProperties::GetSettingName())) {
739     const bool is_global_setting = true;
740     PluginManager::CreateSettingForProcessPlugin(
741         debugger, GetGlobalPluginProperties()->GetValueProperties(),
742         ConstString("Properties for the kdp-remote process plug-in."),
743         is_global_setting);
744   }
745 }
746 
747 bool ProcessKDP::StartAsyncThread() {
748   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
749 
750   if (log)
751     log->Printf("ProcessKDP::StartAsyncThread ()");
752 
753   if (m_async_thread.IsJoinable())
754     return true;
755 
756   m_async_thread = ThreadLauncher::LaunchThread(
757       "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
758   return m_async_thread.IsJoinable();
759 }
760 
761 void ProcessKDP::StopAsyncThread() {
762   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
763 
764   if (log)
765     log->Printf("ProcessKDP::StopAsyncThread ()");
766 
767   m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
768 
769   // Stop the stdio thread
770   if (m_async_thread.IsJoinable())
771     m_async_thread.Join(nullptr);
772 }
773 
774 void *ProcessKDP::AsyncThread(void *arg) {
775   ProcessKDP *process = (ProcessKDP *)arg;
776 
777   const lldb::pid_t pid = process->GetID();
778 
779   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
780   if (log)
781     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
782                 ") thread starting...",
783                 arg, pid);
784 
785   ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
786   EventSP event_sp;
787   const uint32_t desired_event_mask =
788       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
789 
790   if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
791                                            desired_event_mask) ==
792       desired_event_mask) {
793     bool done = false;
794     while (!done) {
795       if (log)
796         log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
797                     ") listener.WaitForEvent (NULL, event_sp)...",
798                     pid);
799       if (listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp)) {
800         uint32_t event_type = event_sp->GetType();
801         if (log)
802           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
803                       ") Got an event of type: %d...",
804                       pid, event_type);
805 
806         // When we are running, poll for 1 second to try and get an exception
807         // to indicate the process has stopped. If we don't get one, check to
808         // make sure no one asked us to exit
809         bool is_running = false;
810         DataExtractor exc_reply_packet;
811         do {
812           switch (event_type) {
813           case eBroadcastBitAsyncContinue: {
814             is_running = true;
815             if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
816                     exc_reply_packet, 1 * USEC_PER_SEC)) {
817               ThreadSP thread_sp(process->GetKernelThread());
818               if (thread_sp) {
819                 lldb::RegisterContextSP reg_ctx_sp(
820                     thread_sp->GetRegisterContext());
821                 if (reg_ctx_sp)
822                   reg_ctx_sp->InvalidateAllRegisters();
823                 static_cast<ThreadKDP *>(thread_sp.get())
824                     ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
825               }
826 
827               // TODO: parse the stop reply packet
828               is_running = false;
829               process->SetPrivateState(eStateStopped);
830             } else {
831               // Check to see if we are supposed to exit. There is no way to
832               // interrupt a running kernel, so all we can do is wait for an
833               // exception or detach...
834               if (listener_sp->GetNextEvent(event_sp)) {
835                 // We got an event, go through the loop again
836                 event_type = event_sp->GetType();
837               }
838             }
839           } break;
840 
841           case eBroadcastBitAsyncThreadShouldExit:
842             if (log)
843               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
844                           ") got eBroadcastBitAsyncThreadShouldExit...",
845                           pid);
846             done = true;
847             is_running = false;
848             break;
849 
850           default:
851             if (log)
852               log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
853                           ") got unknown event 0x%8.8x",
854                           pid, event_type);
855             done = true;
856             is_running = false;
857             break;
858           }
859         } while (is_running);
860       } else {
861         if (log)
862           log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
863                       ") listener.WaitForEvent (NULL, event_sp) => false",
864                       pid);
865         done = true;
866       }
867     }
868   }
869 
870   if (log)
871     log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
872                 ") thread exiting...",
873                 arg, pid);
874 
875   process->m_async_thread.Reset();
876   return NULL;
877 }
878 
879 class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
880 private:
881   OptionGroupOptions m_option_group;
882   OptionGroupUInt64 m_command_byte;
883   OptionGroupString m_packet_data;
884 
885   virtual Options *GetOptions() { return &m_option_group; }
886 
887 public:
888   CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
889       : CommandObjectParsed(interpreter, "process plugin packet send",
890                             "Send a custom packet through the KDP protocol by "
891                             "specifying the command byte and the packet "
892                             "payload data. A packet will be sent with a "
893                             "correct header and payload, and the raw result "
894                             "bytes will be displayed as a string value. ",
895                             NULL),
896         m_option_group(),
897         m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
898                        "Specify the command byte to use when sending the KDP "
899                        "request packet.",
900                        0),
901         m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
902                       "Specify packet payload bytes as a hex ASCII string with "
903                       "no spaces or hex prefixes.",
904                       NULL) {
905     m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
906     m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
907     m_option_group.Finalize();
908   }
909 
910   ~CommandObjectProcessKDPPacketSend() {}
911 
912   bool DoExecute(Args &command, CommandReturnObject &result) {
913     const size_t argc = command.GetArgumentCount();
914     if (argc == 0) {
915       if (!m_command_byte.GetOptionValue().OptionWasSet()) {
916         result.AppendError(
917             "the --command option must be set to a valid command byte");
918         result.SetStatus(eReturnStatusFailed);
919       } else {
920         const uint64_t command_byte =
921             m_command_byte.GetOptionValue().GetUInt64Value(0);
922         if (command_byte > 0 && command_byte <= UINT8_MAX) {
923           ProcessKDP *process =
924               (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
925           if (process) {
926             const StateType state = process->GetState();
927 
928             if (StateIsStoppedState(state, true)) {
929               std::vector<uint8_t> payload_bytes;
930               const char *ascii_hex_bytes_cstr =
931                   m_packet_data.GetOptionValue().GetCurrentValue();
932               if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
933                 StringExtractor extractor(ascii_hex_bytes_cstr);
934                 const size_t ascii_hex_bytes_cstr_len =
935                     extractor.GetStringRef().size();
936                 if (ascii_hex_bytes_cstr_len & 1) {
937                   result.AppendErrorWithFormat("payload data must contain an "
938                                                "even number of ASCII hex "
939                                                "characters: '%s'",
940                                                ascii_hex_bytes_cstr);
941                   result.SetStatus(eReturnStatusFailed);
942                   return false;
943                 }
944                 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
945                 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
946                     payload_bytes.size()) {
947                   result.AppendErrorWithFormat("payload data must only contain "
948                                                "ASCII hex characters (no "
949                                                "spaces or hex prefixes): '%s'",
950                                                ascii_hex_bytes_cstr);
951                   result.SetStatus(eReturnStatusFailed);
952                   return false;
953                 }
954               }
955               Error error;
956               DataExtractor reply;
957               process->GetCommunication().SendRawRequest(
958                   command_byte,
959                   payload_bytes.empty() ? NULL : payload_bytes.data(),
960                   payload_bytes.size(), reply, error);
961 
962               if (error.Success()) {
963                 // Copy the binary bytes into a hex ASCII string for the result
964                 StreamString packet;
965                 packet.PutBytesAsRawHex8(
966                     reply.GetDataStart(), reply.GetByteSize(),
967                     endian::InlHostByteOrder(), endian::InlHostByteOrder());
968                 result.AppendMessage(packet.GetString().c_str());
969                 result.SetStatus(eReturnStatusSuccessFinishResult);
970                 return true;
971               } else {
972                 const char *error_cstr = error.AsCString();
973                 if (error_cstr && error_cstr[0])
974                   result.AppendError(error_cstr);
975                 else
976                   result.AppendErrorWithFormat("unknown error 0x%8.8x",
977                                                error.GetError());
978                 result.SetStatus(eReturnStatusFailed);
979                 return false;
980               }
981             } else {
982               result.AppendErrorWithFormat("process must be stopped in order "
983                                            "to send KDP packets, state is %s",
984                                            StateAsCString(state));
985               result.SetStatus(eReturnStatusFailed);
986             }
987           } else {
988             result.AppendError("invalid process");
989             result.SetStatus(eReturnStatusFailed);
990           }
991         } else {
992           result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
993                                        ", valid values are 1 - 255",
994                                        command_byte);
995           result.SetStatus(eReturnStatusFailed);
996         }
997       }
998     } else {
999       result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
1000                                    m_cmd_name.c_str());
1001       result.SetStatus(eReturnStatusFailed);
1002     }
1003     return false;
1004   }
1005 };
1006 
1007 class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
1008 private:
1009 public:
1010   CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1011       : CommandObjectMultiword(interpreter, "process plugin packet",
1012                                "Commands that deal with KDP remote packets.",
1013                                NULL) {
1014     LoadSubCommand(
1015         "send",
1016         CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1017   }
1018 
1019   ~CommandObjectProcessKDPPacket() {}
1020 };
1021 
1022 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
1023 public:
1024   CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1025       : CommandObjectMultiword(
1026             interpreter, "process plugin",
1027             "Commands for operating on a ProcessKDP process.",
1028             "process plugin <subcommand> [<subcommand-options>]") {
1029     LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1030                                  interpreter)));
1031   }
1032 
1033   ~CommandObjectMultiwordProcessKDP() {}
1034 };
1035 
1036 CommandObject *ProcessKDP::GetPluginCommandObject() {
1037   if (!m_command_sp)
1038     m_command_sp.reset(new CommandObjectMultiwordProcessKDP(
1039         GetTarget().GetDebugger().GetCommandInterpreter()));
1040   return m_command_sp.get();
1041 }
1042