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