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