1 //===-- ProcessKDP.cpp ----------------------------------------------------===//
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 <cerrno>
10 #include <cstdlib>
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 LLDB_PLUGIN_DEFINE_ADV(ProcessKDP, ProcessMacOSXKernel)
54 
55 namespace {
56 
57 #define LLDB_PROPERTIES_processkdp
58 #include "ProcessKDPProperties.inc"
59 
60 enum {
61 #define LLDB_PROPERTIES_processkdp
62 #include "ProcessKDPPropertiesEnum.inc"
63 };
64 
65 class PluginProperties : public Properties {
66 public:
GetSettingName()67   static ConstString GetSettingName() {
68     return ProcessKDP::GetPluginNameStatic();
69   }
70 
PluginProperties()71   PluginProperties() : Properties() {
72     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
73     m_collection_sp->Initialize(g_processkdp_properties);
74   }
75 
76   virtual ~PluginProperties() = default;
77 
GetPacketTimeout()78   uint64_t GetPacketTimeout() {
79     const uint32_t idx = ePropertyKDPPacketTimeout;
80     return m_collection_sp->GetPropertyAtIndexAsUInt64(
81         NULL, idx, g_processkdp_properties[idx].default_uint_value);
82   }
83 };
84 
85 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
86 
GetGlobalPluginProperties()87 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
88   static ProcessKDPPropertiesSP g_settings_sp;
89   if (!g_settings_sp)
90     g_settings_sp = std::make_shared<PluginProperties>();
91   return g_settings_sp;
92 }
93 
94 } // anonymous namespace end
95 
96 static const lldb::tid_t g_kernel_tid = 1;
97 
GetPluginNameStatic()98 ConstString ProcessKDP::GetPluginNameStatic() {
99   static ConstString g_name("kdp-remote");
100   return g_name;
101 }
102 
GetPluginDescriptionStatic()103 const char *ProcessKDP::GetPluginDescriptionStatic() {
104   return "KDP Remote protocol based debugging plug-in for darwin kernel "
105          "debugging.";
106 }
107 
Terminate()108 void ProcessKDP::Terminate() {
109   PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
110 }
111 
CreateInstance(TargetSP target_sp,ListenerSP listener_sp,const FileSpec * crash_file_path,bool can_connect)112 lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
113                                            ListenerSP listener_sp,
114                                            const FileSpec *crash_file_path,
115                                            bool can_connect) {
116   lldb::ProcessSP process_sp;
117   if (crash_file_path == NULL)
118     process_sp = std::make_shared<ProcessKDP>(target_sp, listener_sp);
119   return process_sp;
120 }
121 
CanDebug(TargetSP target_sp,bool plugin_specified_by_name)122 bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
123   if (plugin_specified_by_name)
124     return true;
125 
126   // For now we are just making sure the file exists for a given module
127   Module *exe_module = target_sp->GetExecutableModulePointer();
128   if (exe_module) {
129     const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
130     switch (triple_ref.getOS()) {
131     case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
132                                // iOS, but accept darwin just in case
133     case llvm::Triple::MacOSX: // For desktop targets
134     case llvm::Triple::IOS:    // For arm targets
135     case llvm::Triple::TvOS:
136     case llvm::Triple::WatchOS:
137       if (triple_ref.getVendor() == llvm::Triple::Apple) {
138         ObjectFile *exe_objfile = exe_module->GetObjectFile();
139         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
140             exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
141           return true;
142       }
143       break;
144 
145     default:
146       break;
147     }
148   }
149   return false;
150 }
151 
152 // ProcessKDP constructor
ProcessKDP(TargetSP target_sp,ListenerSP listener_sp)153 ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
154     : Process(target_sp, listener_sp),
155       m_comm("lldb.process.kdp-remote.communication"),
156       m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
157       m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
158       m_command_sp(), m_kernel_thread_wp() {
159   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
160                                    "async thread should exit");
161   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
162                                    "async thread continue");
163   const uint64_t timeout_seconds =
164       GetGlobalPluginProperties()->GetPacketTimeout();
165   if (timeout_seconds > 0)
166     m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
167 }
168 
169 // Destructor
~ProcessKDP()170 ProcessKDP::~ProcessKDP() {
171   Clear();
172   // We need to call finalize on the process before destroying ourselves to
173   // make sure all of the broadcaster cleanup goes as planned. If we destruct
174   // this class, then Process::~Process() might have problems trying to fully
175   // destroy the broadcaster.
176   Finalize();
177 }
178 
179 // PluginInterface
GetPluginName()180 lldb_private::ConstString ProcessKDP::GetPluginName() {
181   return GetPluginNameStatic();
182 }
183 
GetPluginVersion()184 uint32_t ProcessKDP::GetPluginVersion() { return 1; }
185 
WillLaunch(Module * module)186 Status ProcessKDP::WillLaunch(Module *module) {
187   Status error;
188   error.SetErrorString("launching not supported in kdp-remote plug-in");
189   return error;
190 }
191 
WillAttachToProcessWithID(lldb::pid_t pid)192 Status ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) {
193   Status error;
194   error.SetErrorString(
195       "attaching to a by process ID not supported in kdp-remote plug-in");
196   return error;
197 }
198 
WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)199 Status ProcessKDP::WillAttachToProcessWithName(const char *process_name,
200                                                bool wait_for_launch) {
201   Status error;
202   error.SetErrorString(
203       "attaching to a by process name not supported in kdp-remote plug-in");
204   return error;
205 }
206 
GetHostArchitecture(ArchSpec & arch)207 bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) {
208   uint32_t cpu = m_comm.GetCPUType();
209   if (cpu) {
210     uint32_t sub = m_comm.GetCPUSubtype();
211     arch.SetArchitecture(eArchTypeMachO, cpu, sub);
212     // Leave architecture vendor as unspecified unknown
213     arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
214     arch.GetTriple().setVendorName(llvm::StringRef());
215     return true;
216   }
217   arch.Clear();
218   return false;
219 }
220 
DoConnectRemote(llvm::StringRef remote_url)221 Status ProcessKDP::DoConnectRemote(llvm::StringRef remote_url) {
222   Status error;
223 
224   // Don't let any JIT happen when doing KDP as we can't allocate memory and we
225   // don't want to be mucking with threads that might already be handling
226   // exceptions
227   SetCanJIT(false);
228 
229   if (remote_url.empty()) {
230     error.SetErrorStringWithFormat("empty connection URL");
231     return error;
232   }
233 
234   std::unique_ptr<ConnectionFileDescriptor> conn_up(
235       new ConnectionFileDescriptor());
236   if (conn_up) {
237     // Only try once for now.
238     // TODO: check if we should be retrying?
239     const uint32_t max_retry_count = 1;
240     for (uint32_t retry_count = 0; retry_count < max_retry_count;
241          ++retry_count) {
242       if (conn_up->Connect(remote_url, &error) == eConnectionStatusSuccess)
243         break;
244       usleep(100000);
245     }
246   }
247 
248   if (conn_up->IsConnected()) {
249     const TCPSocket &socket =
250         static_cast<const TCPSocket &>(*conn_up->GetReadObject());
251     const uint16_t reply_port = socket.GetLocalPortNumber();
252 
253     if (reply_port != 0) {
254       m_comm.SetConnection(std::move(conn_up));
255 
256       if (m_comm.SendRequestReattach(reply_port)) {
257         if (m_comm.SendRequestConnect(reply_port, reply_port,
258                                       "Greetings from LLDB...")) {
259           m_comm.GetVersion();
260 
261           Target &target = GetTarget();
262           ArchSpec kernel_arch;
263           // The host architecture
264           GetHostArchitecture(kernel_arch);
265           ArchSpec target_arch = target.GetArchitecture();
266           // Merge in any unspecified stuff into the target architecture in
267           // case the target arch isn't set at all or incompletely.
268           target_arch.MergeFrom(kernel_arch);
269           target.SetArchitecture(target_arch);
270 
271           /* Get the kernel's UUID and load address via KDP_KERNELVERSION
272            * packet.  */
273           /* An EFI kdp session has neither UUID nor load address. */
274 
275           UUID kernel_uuid = m_comm.GetUUID();
276           addr_t kernel_load_addr = m_comm.GetLoadAddress();
277 
278           if (m_comm.RemoteIsEFI()) {
279             // Select an invalid plugin name for the dynamic loader so one
280             // doesn't get used since EFI does its own manual loading via
281             // python scripting
282             static ConstString g_none_dynamic_loader("none");
283             m_dyld_plugin_name = g_none_dynamic_loader;
284 
285             if (kernel_uuid.IsValid()) {
286               // If EFI passed in a UUID= try to lookup UUID The slide will not
287               // be provided. But the UUID lookup will be used to launch EFI
288               // debug scripts from the dSYM, that can load all of the symbols.
289               ModuleSpec module_spec;
290               module_spec.GetUUID() = kernel_uuid;
291               module_spec.GetArchitecture() = target.GetArchitecture();
292 
293               // Lookup UUID locally, before attempting dsymForUUID like action
294               FileSpecList search_paths =
295                   Target::GetDefaultDebugFileSearchPaths();
296               module_spec.GetSymbolFileSpec() =
297                   Symbols::LocateExecutableSymbolFile(module_spec,
298                                                       search_paths);
299               if (module_spec.GetSymbolFileSpec()) {
300                 ModuleSpec executable_module_spec =
301                     Symbols::LocateExecutableObjectFile(module_spec);
302                 if (FileSystem::Instance().Exists(
303                         executable_module_spec.GetFileSpec())) {
304                   module_spec.GetFileSpec() =
305                       executable_module_spec.GetFileSpec();
306                 }
307               }
308               if (!module_spec.GetSymbolFileSpec() ||
309                   !module_spec.GetSymbolFileSpec())
310                 Symbols::DownloadObjectAndSymbolFile(module_spec, true);
311 
312               if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
313                 ModuleSP module_sp(new Module(module_spec));
314                 if (module_sp.get() && module_sp->GetObjectFile()) {
315                   // Get the current target executable
316                   ModuleSP exe_module_sp(target.GetExecutableModule());
317 
318                   // Make sure you don't already have the right module loaded
319                   // and they will be uniqued
320                   if (exe_module_sp.get() != module_sp.get())
321                     target.SetExecutableModule(module_sp, eLoadDependentsNo);
322                 }
323               }
324             }
325           } else if (m_comm.RemoteIsDarwinKernel()) {
326             m_dyld_plugin_name =
327                 DynamicLoaderDarwinKernel::GetPluginNameStatic();
328             if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
329               m_kernel_load_addr = kernel_load_addr;
330             }
331           }
332 
333           // Set the thread ID
334           UpdateThreadListIfNeeded();
335           SetID(1);
336           GetThreadList();
337           SetPrivateState(eStateStopped);
338           StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
339           if (async_strm_sp) {
340             const char *cstr;
341             if ((cstr = m_comm.GetKernelVersion()) != NULL) {
342               async_strm_sp->Printf("Version: %s\n", cstr);
343               async_strm_sp->Flush();
344             }
345             //                      if ((cstr = m_comm.GetImagePath ()) != NULL)
346             //                      {
347             //                          async_strm_sp->Printf ("Image Path:
348             //                          %s\n", cstr);
349             //                          async_strm_sp->Flush();
350             //                      }
351           }
352         } else {
353           error.SetErrorString("KDP_REATTACH failed");
354         }
355       } else {
356         error.SetErrorString("KDP_REATTACH failed");
357       }
358     } else {
359       error.SetErrorString("invalid reply port from UDP connection");
360     }
361   } else {
362     if (error.Success())
363       error.SetErrorStringWithFormat("failed to connect to '%s'",
364                                      remote_url.str().c_str());
365   }
366   if (error.Fail())
367     m_comm.Disconnect();
368 
369   return error;
370 }
371 
372 // Process Control
DoLaunch(Module * exe_module,ProcessLaunchInfo & launch_info)373 Status ProcessKDP::DoLaunch(Module *exe_module,
374                             ProcessLaunchInfo &launch_info) {
375   Status error;
376   error.SetErrorString("launching not supported in kdp-remote plug-in");
377   return error;
378 }
379 
380 Status
DoAttachToProcessWithID(lldb::pid_t attach_pid,const ProcessAttachInfo & attach_info)381 ProcessKDP::DoAttachToProcessWithID(lldb::pid_t attach_pid,
382                                     const ProcessAttachInfo &attach_info) {
383   Status error;
384   error.SetErrorString(
385       "attach to process by ID is not supported in kdp remote debugging");
386   return error;
387 }
388 
389 Status
DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)390 ProcessKDP::DoAttachToProcessWithName(const char *process_name,
391                                       const ProcessAttachInfo &attach_info) {
392   Status error;
393   error.SetErrorString(
394       "attach to process by name is not supported in kdp remote debugging");
395   return error;
396 }
397 
DidAttach(ArchSpec & process_arch)398 void ProcessKDP::DidAttach(ArchSpec &process_arch) {
399   Process::DidAttach(process_arch);
400 
401   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
402   LLDB_LOGF(log, "ProcessKDP::DidAttach()");
403   if (GetID() != LLDB_INVALID_PROCESS_ID) {
404     GetHostArchitecture(process_arch);
405   }
406 }
407 
GetImageInfoAddress()408 addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
409 
GetDynamicLoader()410 lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
411   if (m_dyld_up.get() == NULL)
412     m_dyld_up.reset(DynamicLoader::FindPlugin(
413         this,
414         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
415   return m_dyld_up.get();
416 }
417 
WillResume()418 Status ProcessKDP::WillResume() { return Status(); }
419 
DoResume()420 Status ProcessKDP::DoResume() {
421   Status error;
422   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
423   // Only start the async thread if we try to do any process control
424   if (!m_async_thread.IsJoinable())
425     StartAsyncThread();
426 
427   bool resume = false;
428 
429   // With KDP there is only one thread we can tell what to do
430   ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
431 
432   if (kernel_thread_sp) {
433     const StateType thread_resume_state =
434         kernel_thread_sp->GetTemporaryResumeState();
435 
436     LLDB_LOGF(log, "ProcessKDP::DoResume() thread_resume_state = %s",
437               StateAsCString(thread_resume_state));
438     switch (thread_resume_state) {
439     case eStateSuspended:
440       // Nothing to do here when a thread will stay suspended we just leave the
441       // CPU mask bit set to zero for the thread
442       LLDB_LOGF(log, "ProcessKDP::DoResume() = suspended???");
443       break;
444 
445     case eStateStepping: {
446       lldb::RegisterContextSP reg_ctx_sp(
447           kernel_thread_sp->GetRegisterContext());
448 
449       if (reg_ctx_sp) {
450         LLDB_LOGF(
451             log,
452             "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
453         reg_ctx_sp->HardwareSingleStep(true);
454         resume = true;
455       } else {
456         error.SetErrorStringWithFormat(
457             "KDP thread 0x%llx has no register context",
458             kernel_thread_sp->GetID());
459       }
460     } break;
461 
462     case eStateRunning: {
463       lldb::RegisterContextSP reg_ctx_sp(
464           kernel_thread_sp->GetRegisterContext());
465 
466       if (reg_ctx_sp) {
467         LLDB_LOGF(log, "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
468                        "(false);");
469         reg_ctx_sp->HardwareSingleStep(false);
470         resume = true;
471       } else {
472         error.SetErrorStringWithFormat(
473             "KDP thread 0x%llx has no register context",
474             kernel_thread_sp->GetID());
475       }
476     } break;
477 
478     default:
479       // The only valid thread resume states are listed above
480       llvm_unreachable("invalid thread resume state");
481     }
482   }
483 
484   if (resume) {
485     LLDB_LOGF(log, "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 
GetKernelThread()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 
DoUpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)511 bool ProcessKDP::DoUpdateThreadList(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 
RefreshStateAfterStop()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 
DoHalt(bool & caused_stop)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 
DoDetach(bool keep_stopped)550 Status ProcessKDP::DoDetach(bool keep_stopped) {
551   Status error;
552   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
553   LLDB_LOGF(log, "ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
554 
555   if (m_comm.IsRunning()) {
556     // We are running and we can't interrupt a running kernel, so we need to
557     // just close the connection to the kernel and hope for the best
558   } else {
559     // If we are going to keep the target stopped, then don't send the
560     // disconnect message.
561     if (!keep_stopped && m_comm.IsConnected()) {
562       const bool success = m_comm.SendRequestDisconnect();
563       if (log) {
564         if (success)
565           log->PutCString(
566               "ProcessKDP::DoDetach() detach packet sent successfully");
567         else
568           log->PutCString(
569               "ProcessKDP::DoDetach() connection channel shutdown failed");
570       }
571       m_comm.Disconnect();
572     }
573   }
574   StopAsyncThread();
575   m_comm.Clear();
576 
577   SetPrivateState(eStateDetached);
578   ResumePrivateStateThread();
579 
580   // KillDebugserverProcess ();
581   return error;
582 }
583 
DoDestroy()584 Status ProcessKDP::DoDestroy() {
585   // For KDP there really is no difference between destroy and detach
586   bool keep_stopped = false;
587   return DoDetach(keep_stopped);
588 }
589 
590 // Process Queries
591 
IsAlive()592 bool ProcessKDP::IsAlive() {
593   return m_comm.IsConnected() && Process::IsAlive();
594 }
595 
596 // Process Memory
DoReadMemory(addr_t addr,void * buf,size_t size,Status & error)597 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
598                                 Status &error) {
599   uint8_t *data_buffer = (uint8_t *)buf;
600   if (m_comm.IsConnected()) {
601     const size_t max_read_size = 512;
602     size_t total_bytes_read = 0;
603 
604     // Read the requested amount of memory in 512 byte chunks
605     while (total_bytes_read < size) {
606       size_t bytes_to_read_this_request = size - total_bytes_read;
607       if (bytes_to_read_this_request > max_read_size) {
608         bytes_to_read_this_request = max_read_size;
609       }
610       size_t bytes_read = m_comm.SendRequestReadMemory(
611           addr + total_bytes_read, data_buffer + total_bytes_read,
612           bytes_to_read_this_request, error);
613       total_bytes_read += bytes_read;
614       if (error.Fail() || bytes_read == 0) {
615         return total_bytes_read;
616       }
617     }
618 
619     return total_bytes_read;
620   }
621   error.SetErrorString("not connected");
622   return 0;
623 }
624 
DoWriteMemory(addr_t addr,const void * buf,size_t size,Status & error)625 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
626                                  Status &error) {
627   if (m_comm.IsConnected())
628     return m_comm.SendRequestWriteMemory(addr, buf, size, error);
629   error.SetErrorString("not connected");
630   return 0;
631 }
632 
DoAllocateMemory(size_t size,uint32_t permissions,Status & error)633 lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
634                                           Status &error) {
635   error.SetErrorString(
636       "memory allocation not supported in kdp remote debugging");
637   return LLDB_INVALID_ADDRESS;
638 }
639 
DoDeallocateMemory(lldb::addr_t addr)640 Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
641   Status error;
642   error.SetErrorString(
643       "memory deallocation not supported in kdp remote debugging");
644   return error;
645 }
646 
EnableBreakpointSite(BreakpointSite * bp_site)647 Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
648   if (bp_site->HardwareRequired())
649     return Status("Hardware breakpoints are not supported.");
650 
651   if (m_comm.LocalBreakpointsAreSupported()) {
652     Status error;
653     if (!bp_site->IsEnabled()) {
654       if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
655         bp_site->SetEnabled(true);
656         bp_site->SetType(BreakpointSite::eExternal);
657       } else {
658         error.SetErrorString("KDP set breakpoint failed");
659       }
660     }
661     return error;
662   }
663   return EnableSoftwareBreakpoint(bp_site);
664 }
665 
DisableBreakpointSite(BreakpointSite * bp_site)666 Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
667   if (m_comm.LocalBreakpointsAreSupported()) {
668     Status error;
669     if (bp_site->IsEnabled()) {
670       BreakpointSite::Type bp_type = bp_site->GetType();
671       if (bp_type == BreakpointSite::eExternal) {
672         if (m_destroy_in_process && m_comm.IsRunning()) {
673           // We are trying to destroy our connection and we are running
674           bp_site->SetEnabled(false);
675         } else {
676           if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
677             bp_site->SetEnabled(false);
678           else
679             error.SetErrorString("KDP remove breakpoint failed");
680         }
681       } else {
682         error = DisableSoftwareBreakpoint(bp_site);
683       }
684     }
685     return error;
686   }
687   return DisableSoftwareBreakpoint(bp_site);
688 }
689 
EnableWatchpoint(Watchpoint * wp,bool notify)690 Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
691   Status error;
692   error.SetErrorString(
693       "watchpoints are not supported in kdp remote debugging");
694   return error;
695 }
696 
DisableWatchpoint(Watchpoint * wp,bool notify)697 Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
698   Status error;
699   error.SetErrorString(
700       "watchpoints are not supported in kdp remote debugging");
701   return error;
702 }
703 
Clear()704 void ProcessKDP::Clear() { m_thread_list.Clear(); }
705 
DoSignal(int signo)706 Status ProcessKDP::DoSignal(int signo) {
707   Status error;
708   error.SetErrorString(
709       "sending signals is not supported in kdp remote debugging");
710   return error;
711 }
712 
Initialize()713 void ProcessKDP::Initialize() {
714   static llvm::once_flag g_once_flag;
715 
716   llvm::call_once(g_once_flag, []() {
717     PluginManager::RegisterPlugin(GetPluginNameStatic(),
718                                   GetPluginDescriptionStatic(), CreateInstance,
719                                   DebuggerInitialize);
720 
721     ProcessKDPLog::Initialize();
722   });
723 }
724 
DebuggerInitialize(lldb_private::Debugger & debugger)725 void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
726   if (!PluginManager::GetSettingForProcessPlugin(
727           debugger, PluginProperties::GetSettingName())) {
728     const bool is_global_setting = true;
729     PluginManager::CreateSettingForProcessPlugin(
730         debugger, GetGlobalPluginProperties()->GetValueProperties(),
731         ConstString("Properties for the kdp-remote process plug-in."),
732         is_global_setting);
733   }
734 }
735 
StartAsyncThread()736 bool ProcessKDP::StartAsyncThread() {
737   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
738 
739   LLDB_LOGF(log, "ProcessKDP::StartAsyncThread ()");
740 
741   if (m_async_thread.IsJoinable())
742     return true;
743 
744   llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
745       "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this);
746   if (!async_thread) {
747     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
748              "failed to launch host thread: {}",
749              llvm::toString(async_thread.takeError()));
750     return false;
751   }
752   m_async_thread = *async_thread;
753   return m_async_thread.IsJoinable();
754 }
755 
StopAsyncThread()756 void ProcessKDP::StopAsyncThread() {
757   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
758 
759   LLDB_LOGF(log, "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 
AsyncThread(void * arg)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   LLDB_LOGF(log,
775             "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       LLDB_LOGF(log,
790                 "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         LLDB_LOGF(log,
796                   "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             LLDB_LOGF(log,
838                       "ProcessKDP::AsyncThread (pid = %" PRIu64
839                       ") got eBroadcastBitAsyncThreadShouldExit...",
840                       pid);
841             done = true;
842             is_running = false;
843             break;
844 
845           default:
846             LLDB_LOGF(log,
847                       "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         LLDB_LOGF(log,
857                   "ProcessKDP::AsyncThread (pid = %" PRIu64
858                   ") listener.WaitForEvent (NULL, event_sp) => false",
859                   pid);
860         done = true;
861       }
862     }
863   }
864 
865   LLDB_LOGF(log,
866             "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 
GetOptions()880   Options *GetOptions() override { return &m_option_group; }
881 
882 public:
CommandObjectProcessKDPPacketSend(CommandInterpreter & interpreter)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() = default;
906 
DoExecute(Args & command,CommandReturnObject & result)907   bool DoExecute(Args &command, CommandReturnObject &result) override {
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       } else {
914         const uint64_t command_byte =
915             m_command_byte.GetOptionValue().GetUInt64Value(0);
916         if (command_byte > 0 && command_byte <= UINT8_MAX) {
917           ProcessKDP *process =
918               (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
919           if (process) {
920             const StateType state = process->GetState();
921 
922             if (StateIsStoppedState(state, true)) {
923               std::vector<uint8_t> payload_bytes;
924               const char *ascii_hex_bytes_cstr =
925                   m_packet_data.GetOptionValue().GetCurrentValue();
926               if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
927                 StringExtractor extractor(ascii_hex_bytes_cstr);
928                 const size_t ascii_hex_bytes_cstr_len =
929                     extractor.GetStringRef().size();
930                 if (ascii_hex_bytes_cstr_len & 1) {
931                   result.AppendErrorWithFormat("payload data must contain an "
932                                                "even number of ASCII hex "
933                                                "characters: '%s'",
934                                                ascii_hex_bytes_cstr);
935                   return false;
936                 }
937                 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
938                 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
939                     payload_bytes.size()) {
940                   result.AppendErrorWithFormat("payload data must only contain "
941                                                "ASCII hex characters (no "
942                                                "spaces or hex prefixes): '%s'",
943                                                ascii_hex_bytes_cstr);
944                   return false;
945                 }
946               }
947               Status error;
948               DataExtractor reply;
949               process->GetCommunication().SendRawRequest(
950                   command_byte,
951                   payload_bytes.empty() ? NULL : payload_bytes.data(),
952                   payload_bytes.size(), reply, error);
953 
954               if (error.Success()) {
955                 // Copy the binary bytes into a hex ASCII string for the result
956                 StreamString packet;
957                 packet.PutBytesAsRawHex8(
958                     reply.GetDataStart(), reply.GetByteSize(),
959                     endian::InlHostByteOrder(), endian::InlHostByteOrder());
960                 result.AppendMessage(packet.GetString());
961                 result.SetStatus(eReturnStatusSuccessFinishResult);
962                 return true;
963               } else {
964                 const char *error_cstr = error.AsCString();
965                 if (error_cstr && error_cstr[0])
966                   result.AppendError(error_cstr);
967                 else
968                   result.AppendErrorWithFormat("unknown error 0x%8.8x",
969                                                error.GetError());
970                 return false;
971               }
972             } else {
973               result.AppendErrorWithFormat("process must be stopped in order "
974                                            "to send KDP packets, state is %s",
975                                            StateAsCString(state));
976             }
977           } else {
978             result.AppendError("invalid process");
979           }
980         } else {
981           result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
982                                        ", valid values are 1 - 255",
983                                        command_byte);
984         }
985       }
986     } else {
987       result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
988                                    m_cmd_name.c_str());
989     }
990     return false;
991   }
992 };
993 
994 class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
995 private:
996 public:
CommandObjectProcessKDPPacket(CommandInterpreter & interpreter)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() = default;
1007 };
1008 
1009 class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
1010 public:
CommandObjectMultiwordProcessKDP(CommandInterpreter & interpreter)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() = default;
1021 };
1022 
GetPluginCommandObject()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