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