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