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