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