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/Symbol/ObjectFile.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 
30 // Project includes
31 #include "ProcessKDP.h"
32 #include "ProcessKDPLog.h"
33 #include "ThreadKDP.h"
34 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 const char *
40 ProcessKDP::GetPluginNameStatic()
41 {
42     return "kdp-remote";
43 }
44 
45 const char *
46 ProcessKDP::GetPluginDescriptionStatic()
47 {
48     return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
49 }
50 
51 void
52 ProcessKDP::Terminate()
53 {
54     PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
55 }
56 
57 
58 lldb::ProcessSP
59 ProcessKDP::CreateInstance (Target &target,
60                             Listener &listener,
61                             const FileSpec *crash_file_path)
62 {
63     lldb::ProcessSP process_sp;
64     if (crash_file_path == NULL)
65         process_sp.reset(new ProcessKDP (target, listener));
66     return process_sp;
67 }
68 
69 bool
70 ProcessKDP::CanDebug(Target &target, bool plugin_specified_by_name)
71 {
72     if (plugin_specified_by_name)
73         return true;
74 
75     // For now we are just making sure the file exists for a given module
76     Module *exe_module = target.GetExecutableModulePointer();
77     if (exe_module)
78     {
79         const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
80         switch (triple_ref.getOS())
81         {
82             case llvm::Triple::Darwin:  // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
83             case llvm::Triple::MacOSX:  // For desktop targets
84             case llvm::Triple::IOS:     // For arm targets
85                 if (triple_ref.getVendor() == llvm::Triple::Apple)
86                 {
87                     ObjectFile *exe_objfile = exe_module->GetObjectFile();
88                     if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
89                         exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
90                         return true;
91                 }
92                 break;
93 
94             default:
95                 break;
96         }
97     }
98     return false;
99 }
100 
101 //----------------------------------------------------------------------
102 // ProcessKDP constructor
103 //----------------------------------------------------------------------
104 ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
105     Process (target, listener),
106     m_comm("lldb.process.kdp-remote.communication"),
107     m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
108     m_async_thread (LLDB_INVALID_HOST_THREAD),
109     m_destroy_in_process (false),
110     m_dyld_plugin_name (),
111     m_kernel_load_addr (LLDB_INVALID_ADDRESS)
112 {
113     m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit,   "async thread should exit");
114     m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue,           "async thread continue");
115 }
116 
117 //----------------------------------------------------------------------
118 // Destructor
119 //----------------------------------------------------------------------
120 ProcessKDP::~ProcessKDP()
121 {
122     Clear();
123     // We need to call finalize on the process before destroying ourselves
124     // to make sure all of the broadcaster cleanup goes as planned. If we
125     // destruct this class, then Process::~Process() might have problems
126     // trying to fully destroy the broadcaster.
127     Finalize();
128 }
129 
130 //----------------------------------------------------------------------
131 // PluginInterface
132 //----------------------------------------------------------------------
133 const char *
134 ProcessKDP::GetPluginName()
135 {
136     return "Process debugging plug-in that uses the Darwin KDP remote protocol";
137 }
138 
139 const char *
140 ProcessKDP::GetShortPluginName()
141 {
142     return GetPluginNameStatic();
143 }
144 
145 uint32_t
146 ProcessKDP::GetPluginVersion()
147 {
148     return 1;
149 }
150 
151 Error
152 ProcessKDP::WillLaunch (Module* module)
153 {
154     Error error;
155     error.SetErrorString ("launching not supported in kdp-remote plug-in");
156     return error;
157 }
158 
159 Error
160 ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
161 {
162     Error error;
163     error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
164     return error;
165 }
166 
167 Error
168 ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
169 {
170     Error error;
171     error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
172     return error;
173 }
174 
175 Error
176 ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
177 {
178     Error error;
179 
180     // Don't let any JIT happen when doing KDP as we can't allocate
181     // memory and we don't want to be mucking with threads that might
182     // already be handling exceptions
183     SetCanJIT(false);
184 
185     if (remote_url == NULL || remote_url[0] == '\0')
186     {
187         error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
188         return error;
189     }
190 
191     std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
192     if (conn_ap.get())
193     {
194         // Only try once for now.
195         // TODO: check if we should be retrying?
196         const uint32_t max_retry_count = 1;
197         for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
198         {
199             if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
200                 break;
201             usleep (100000);
202         }
203     }
204 
205     if (conn_ap->IsConnected())
206     {
207         const uint16_t reply_port = conn_ap->GetReadPort ();
208 
209         if (reply_port != 0)
210         {
211             m_comm.SetConnection(conn_ap.release());
212 
213             if (m_comm.SendRequestReattach(reply_port))
214             {
215                 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
216                 {
217                     m_comm.GetVersion();
218                     uint32_t cpu = m_comm.GetCPUType();
219                     uint32_t sub = m_comm.GetCPUSubtype();
220                     ArchSpec kernel_arch;
221                     kernel_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
222                     m_target.SetArchitecture(kernel_arch);
223 
224                     /* Get the kernel's UUID and load address via kdp-kernelversion packet.  */
225 
226                     UUID kernel_uuid = m_comm.GetUUID ();
227                     addr_t kernel_load_addr = m_comm.GetLoadAddress ();
228 
229                     if (kernel_load_addr != LLDB_INVALID_ADDRESS)
230                     {
231                         m_kernel_load_addr = kernel_load_addr;
232                         m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
233                     }
234 
235                     // Set the thread ID
236                     UpdateThreadListIfNeeded ();
237                     SetID (1);
238                     GetThreadList ();
239                     SetPrivateState (eStateStopped);
240                     StreamSP async_strm_sp(m_target.GetDebugger().GetAsyncOutputStream());
241                     if (async_strm_sp)
242                     {
243                         const char *cstr;
244                         if ((cstr = m_comm.GetKernelVersion ()) != NULL)
245                         {
246                             async_strm_sp->Printf ("Version: %s\n", cstr);
247                             async_strm_sp->Flush();
248                         }
249 //                      if ((cstr = m_comm.GetImagePath ()) != NULL)
250 //                      {
251 //                          async_strm_sp->Printf ("Image Path: %s\n", cstr);
252 //                          async_strm_sp->Flush();
253 //                      }
254                     }
255                 }
256                 else
257                 {
258                     puts ("KDP_CONNECT failed"); // REMOVE THIS
259                     error.SetErrorString("KDP_REATTACH failed");
260                 }
261             }
262             else
263             {
264                 puts ("KDP_REATTACH failed"); // REMOVE THIS
265                 error.SetErrorString("KDP_REATTACH failed");
266             }
267         }
268         else
269         {
270             error.SetErrorString("invalid reply port from UDP connection");
271         }
272     }
273     else
274     {
275         if (error.Success())
276             error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
277     }
278     if (error.Fail())
279         m_comm.Disconnect();
280 
281     return error;
282 }
283 
284 //----------------------------------------------------------------------
285 // Process Control
286 //----------------------------------------------------------------------
287 Error
288 ProcessKDP::DoLaunch (Module *exe_module,
289                       const ProcessLaunchInfo &launch_info)
290 {
291     Error error;
292     error.SetErrorString ("launching not supported in kdp-remote plug-in");
293     return error;
294 }
295 
296 
297 Error
298 ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid)
299 {
300     Error error;
301     error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
302     return error;
303 }
304 
305 Error
306 ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
307 {
308     Error error;
309     error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
310     return error;
311 }
312 
313 Error
314 ProcessKDP::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
315 {
316     Error error;
317     error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
318     return error;
319 }
320 
321 
322 void
323 ProcessKDP::DidAttach ()
324 {
325     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
326     if (log)
327         log->Printf ("ProcessKDP::DidAttach()");
328     if (GetID() != LLDB_INVALID_PROCESS_ID)
329     {
330         // TODO: figure out the register context that we will use
331     }
332 }
333 
334 addr_t
335 ProcessKDP::GetImageInfoAddress()
336 {
337     return m_kernel_load_addr;
338 }
339 
340 lldb_private::DynamicLoader *
341 ProcessKDP::GetDynamicLoader ()
342 {
343     if (m_dyld_ap.get() == NULL)
344         m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
345     return m_dyld_ap.get();
346 }
347 
348 Error
349 ProcessKDP::WillResume ()
350 {
351     return Error();
352 }
353 
354 Error
355 ProcessKDP::DoResume ()
356 {
357     Error error;
358     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
359     // Only start the async thread if we try to do any process control
360     if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
361         StartAsyncThread ();
362 
363     bool resume = false;
364 
365     // With KDP there is only one thread we can tell what to do
366     ThreadSP kernel_thread_sp (GetKernelThread(m_thread_list, m_thread_list));
367     if (kernel_thread_sp)
368     {
369         const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
370         switch (thread_resume_state)
371         {
372             case eStateSuspended:
373                 // Nothing to do here when a thread will stay suspended
374                 // we just leave the CPU mask bit set to zero for the thread
375                 puts("REMOVE THIS: ProcessKDP::DoResume () -- thread suspended");
376                 break;
377 
378             case eStateStepping:
379                 puts("REMOVE THIS: ProcessKDP::DoResume () -- thread stepping");
380                 kernel_thread_sp->GetRegisterContext()->HardwareSingleStep (true);
381                 resume = true;
382                 break;
383 
384             case eStateRunning:
385                 puts("REMOVE THIS: ProcessKDP::DoResume () -- thread running");
386                 kernel_thread_sp->GetRegisterContext()->HardwareSingleStep (false);
387                 resume = true;
388                 break;
389 
390             default:
391                 // The only valid thread resume states are listed above
392                 assert (!"invalid thread resume state");
393                 break;
394         }
395     }
396 
397     if (resume)
398     {
399         if (log)
400             log->Printf ("ProcessKDP::DoResume () sending resume");
401 
402         if (m_comm.SendRequestResume ())
403         {
404             m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
405             SetPrivateState(eStateRunning);
406         }
407         else
408             error.SetErrorString ("KDP resume failed");
409     }
410     else
411     {
412         error.SetErrorString ("kernel thread is suspended");
413     }
414 
415     return error;
416 }
417 
418 lldb::ThreadSP
419 ProcessKDP::GetKernelThread(ThreadList &old_thread_list, ThreadList &new_thread_list)
420 {
421     // KDP only tells us about one thread/core. Any other threads will usually
422     // be the ones that are read from memory by the OS plug-ins.
423     const lldb::tid_t kernel_tid = 1;
424     ThreadSP thread_sp (old_thread_list.FindThreadByID (kernel_tid, false));
425     if (!thread_sp)
426     {
427         thread_sp.reset(new ThreadKDP (shared_from_this(), kernel_tid));
428         new_thread_list.AddThread(thread_sp);
429     }
430     return thread_sp;
431 }
432 
433 
434 
435 
436 bool
437 ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
438 {
439     // locker will keep a mutex locked until it goes out of scope
440     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
441     if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
442         log->Printf ("ProcessKDP::%s (pid = %llu)", __FUNCTION__, GetID());
443 
444     // Even though there is a CPU mask, it doesn't mean to can see each CPU
445     // indivudually, there is really only one. Lets call this thread 1.
446     GetKernelThread (old_thread_list, new_thread_list);
447 
448     return new_thread_list.GetSize(false) > 0;
449 }
450 
451 void
452 ProcessKDP::RefreshStateAfterStop ()
453 {
454     // Let all threads recover from stopping and do any clean up based
455     // on the previous thread state (if any).
456     m_thread_list.RefreshStateAfterStop();
457 }
458 
459 Error
460 ProcessKDP::DoHalt (bool &caused_stop)
461 {
462     Error error;
463 
464     if (m_comm.IsRunning())
465     {
466         if (m_destroy_in_process)
467         {
468             // If we are attemping to destroy, we need to not return an error to
469             // Halt or DoDestroy won't get called.
470             // We are also currently running, so send a process stopped event
471             SetPrivateState (eStateStopped);
472         }
473         else
474         {
475             error.SetErrorString ("KDP cannot interrupt a running kernel");
476         }
477     }
478     return error;
479 }
480 
481 Error
482 ProcessKDP::DoDetach()
483 {
484     Error error;
485     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
486     if (log)
487         log->Printf ("ProcessKDP::DoDetach()");
488 
489     if (m_comm.IsRunning())
490     {
491         // We are running and we can't interrupt a running kernel, so we need
492         // to just close the connection to the kernel and hope for the best
493     }
494     else
495     {
496         DisableAllBreakpointSites ();
497 
498         m_thread_list.DiscardThreadPlans();
499 
500         if (m_comm.IsConnected())
501         {
502 
503             m_comm.SendRequestDisconnect();
504 
505             size_t response_size = m_comm.Disconnect ();
506             if (log)
507             {
508                 if (response_size)
509                     log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
510                 else
511                     log->PutCString ("ProcessKDP::DoDetach() detach packet send failed");
512             }
513         }
514     }
515     StopAsyncThread ();
516     m_comm.Clear();
517 
518     SetPrivateState (eStateDetached);
519     ResumePrivateStateThread();
520 
521     //KillDebugserverProcess ();
522     return error;
523 }
524 
525 Error
526 ProcessKDP::WillDestroy ()
527 {
528     Error error;
529     m_destroy_in_process = true;
530     return error;
531 }
532 
533 Error
534 ProcessKDP::DoDestroy ()
535 {
536     // For KDP there really is no difference between destroy and detach
537     return DoDetach();
538 }
539 
540 //------------------------------------------------------------------
541 // Process Queries
542 //------------------------------------------------------------------
543 
544 bool
545 ProcessKDP::IsAlive ()
546 {
547     return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
548 }
549 
550 //------------------------------------------------------------------
551 // Process Memory
552 //------------------------------------------------------------------
553 size_t
554 ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
555 {
556     if (m_comm.IsConnected())
557         return m_comm.SendRequestReadMemory (addr, buf, size, error);
558     error.SetErrorString ("not connected");
559     return 0;
560 }
561 
562 size_t
563 ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
564 {
565     if (m_comm.IsConnected())
566         return m_comm.SendRequestWriteMemory (addr, buf, size, error);
567     error.SetErrorString ("not connected");
568     return 0;
569 }
570 
571 lldb::addr_t
572 ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
573 {
574     error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
575     return LLDB_INVALID_ADDRESS;
576 }
577 
578 Error
579 ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
580 {
581     Error error;
582     error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
583     return error;
584 }
585 
586 Error
587 ProcessKDP::EnableBreakpoint (BreakpointSite *bp_site)
588 {
589     if (m_comm.LocalBreakpointsAreSupported ())
590     {
591         Error error;
592         if (!bp_site->IsEnabled())
593         {
594             if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
595             {
596                 bp_site->SetEnabled(true);
597                 bp_site->SetType (BreakpointSite::eExternal);
598             }
599             else
600             {
601                 error.SetErrorString ("KDP set breakpoint failed");
602             }
603         }
604         return error;
605     }
606     return EnableSoftwareBreakpoint (bp_site);
607 }
608 
609 Error
610 ProcessKDP::DisableBreakpoint (BreakpointSite *bp_site)
611 {
612     if (m_comm.LocalBreakpointsAreSupported ())
613     {
614         Error error;
615         if (bp_site->IsEnabled())
616         {
617             BreakpointSite::Type bp_type = bp_site->GetType();
618             if (bp_type == BreakpointSite::eExternal)
619             {
620                 if (m_destroy_in_process && m_comm.IsRunning())
621                 {
622                     // We are trying to destroy our connection and we are running
623                     bp_site->SetEnabled(false);
624                 }
625                 else
626                 {
627                     if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
628                         bp_site->SetEnabled(false);
629                     else
630                         error.SetErrorString ("KDP remove breakpoint failed");
631                 }
632             }
633             else
634             {
635                 error = DisableSoftwareBreakpoint (bp_site);
636             }
637         }
638         return error;
639     }
640     return DisableSoftwareBreakpoint (bp_site);
641 }
642 
643 Error
644 ProcessKDP::EnableWatchpoint (Watchpoint *wp)
645 {
646     Error error;
647     error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
648     return error;
649 }
650 
651 Error
652 ProcessKDP::DisableWatchpoint (Watchpoint *wp)
653 {
654     Error error;
655     error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
656     return error;
657 }
658 
659 void
660 ProcessKDP::Clear()
661 {
662     m_thread_list.Clear();
663 }
664 
665 Error
666 ProcessKDP::DoSignal (int signo)
667 {
668     Error error;
669     error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
670     return error;
671 }
672 
673 void
674 ProcessKDP::Initialize()
675 {
676     static bool g_initialized = false;
677 
678     if (g_initialized == false)
679     {
680         g_initialized = true;
681         PluginManager::RegisterPlugin (GetPluginNameStatic(),
682                                        GetPluginDescriptionStatic(),
683                                        CreateInstance);
684 
685         Log::Callbacks log_callbacks = {
686             ProcessKDPLog::DisableLog,
687             ProcessKDPLog::EnableLog,
688             ProcessKDPLog::ListLogCategories
689         };
690 
691         Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
692     }
693 }
694 
695 bool
696 ProcessKDP::StartAsyncThread ()
697 {
698     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
699 
700     if (log)
701         log->Printf ("ProcessKDP::StartAsyncThread ()");
702 
703     if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
704         return true;
705 
706     m_async_thread = Host::ThreadCreate ("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
707     return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
708 }
709 
710 void
711 ProcessKDP::StopAsyncThread ()
712 {
713     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
714 
715     if (log)
716         log->Printf ("ProcessKDP::StopAsyncThread ()");
717 
718     m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
719 
720     // Stop the stdio thread
721     if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
722     {
723         Host::ThreadJoin (m_async_thread, NULL, NULL);
724         m_async_thread = LLDB_INVALID_HOST_THREAD;
725     }
726 }
727 
728 
729 void *
730 ProcessKDP::AsyncThread (void *arg)
731 {
732     ProcessKDP *process = (ProcessKDP*) arg;
733 
734     const lldb::pid_t pid = process->GetID();
735 
736     LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
737     if (log)
738         log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %llu) thread starting...", arg, pid);
739 
740     Listener listener ("ProcessKDP::AsyncThread");
741     EventSP event_sp;
742     const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
743                                         eBroadcastBitAsyncThreadShouldExit;
744 
745 
746     if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
747     {
748         bool done = false;
749         while (!done)
750         {
751             if (log)
752                 log->Printf ("ProcessKDP::AsyncThread (pid = %llu) listener.WaitForEvent (NULL, event_sp)...",
753                              pid);
754             if (listener.WaitForEvent (NULL, event_sp))
755             {
756                 uint32_t event_type = event_sp->GetType();
757                 if (log)
758                     log->Printf ("ProcessKDP::AsyncThread (pid = %llu) Got an event of type: %d...",
759                                  pid,
760                                  event_type);
761 
762                 // When we are running, poll for 1 second to try and get an exception
763                 // to indicate the process has stopped. If we don't get one, check to
764                 // make sure no one asked us to exit
765                 bool is_running = false;
766                 DataExtractor exc_reply_packet;
767                 do
768                 {
769                     switch (event_type)
770                     {
771                     case eBroadcastBitAsyncContinue:
772                         {
773                             is_running = true;
774                             if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
775                             {
776                                 ThreadSP thread_sp (process->GetKernelThread(process->GetThreadList(), process->GetThreadList()));
777                                 thread_sp->GetRegisterContext()->InvalidateAllRegisters();
778                                 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
779 
780                                 // TODO: parse the stop reply packet
781                                 is_running = false;
782                                 process->SetPrivateState(eStateStopped);
783                             }
784                             else
785                             {
786                                 // Check to see if we are supposed to exit. There is no way to
787                                 // interrupt a running kernel, so all we can do is wait for an
788                                 // exception or detach...
789                                 if (listener.GetNextEvent(event_sp))
790                                 {
791                                     // We got an event, go through the loop again
792                                     event_type = event_sp->GetType();
793                                 }
794                             }
795                         }
796                         break;
797 
798                     case eBroadcastBitAsyncThreadShouldExit:
799                         if (log)
800                             log->Printf ("ProcessKDP::AsyncThread (pid = %llu) got eBroadcastBitAsyncThreadShouldExit...",
801                                          pid);
802                         done = true;
803                         is_running = false;
804                         break;
805 
806                     default:
807                         if (log)
808                             log->Printf ("ProcessKDP::AsyncThread (pid = %llu) got unknown event 0x%8.8x",
809                                          pid,
810                                          event_type);
811                         done = true;
812                         is_running = false;
813                         break;
814                     }
815                 } while (is_running);
816             }
817             else
818             {
819                 if (log)
820                     log->Printf ("ProcessKDP::AsyncThread (pid = %llu) listener.WaitForEvent (NULL, event_sp) => false",
821                                  pid);
822                 done = true;
823             }
824         }
825     }
826 
827     if (log)
828         log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %llu) thread exiting...",
829                      arg,
830                      pid);
831 
832     process->m_async_thread = LLDB_INVALID_HOST_THREAD;
833     return NULL;
834 }
835 
836 
837