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