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