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