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