LLDB  mainline
ProcessKDP.cpp
Go to the documentation of this file.
1 //===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <errno.h>
10 #include <stdlib.h>
11 
12 #include <memory>
13 #include <mutex>
14 
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Host/Host.h"
31 #include "lldb/Symbol/ObjectFile.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Utility/State.h"
37 #include "lldb/Utility/UUID.h"
38 
39 #include "llvm/Support/Threading.h"
40 
41 #define USEC_PER_SEC 1000000
42 
45 #include "ProcessKDP.h"
46 #include "ProcessKDPLog.h"
47 #include "ThreadKDP.h"
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 namespace {
53 
54 static constexpr PropertyDefinition g_properties[] = {
55  {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, {},
56  "Specify the default packet timeout in seconds."}};
57 
58 enum { ePropertyPacketTimeout };
59 
60 class PluginProperties : public Properties {
61 public:
62  static ConstString GetSettingName() {
64  }
65 
66  PluginProperties() : Properties() {
67  m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
68  m_collection_sp->Initialize(g_properties);
69  }
70 
71  virtual ~PluginProperties() {}
72 
73  uint64_t GetPacketTimeout() {
74  const uint32_t idx = ePropertyPacketTimeout;
75  return m_collection_sp->GetPropertyAtIndexAsUInt64(
76  NULL, idx, g_properties[idx].default_uint_value);
77  }
78 };
79 
80 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
81 
82 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
83  static ProcessKDPPropertiesSP g_settings_sp;
84  if (!g_settings_sp)
85  g_settings_sp = std::make_shared<PluginProperties>();
86  return g_settings_sp;
87 }
88 
89 } // anonymous namespace end
90 
91 static const lldb::tid_t g_kernel_tid = 1;
92 
94  static ConstString g_name("kdp-remote");
95  return g_name;
96 }
97 
99  return "KDP Remote protocol based debugging plug-in for darwin kernel "
100  "debugging.";
101 }
102 
104  PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
105 }
106 
107 lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
108  ListenerSP listener_sp,
109  const FileSpec *crash_file_path) {
110  lldb::ProcessSP process_sp;
111  if (crash_file_path == NULL)
112  process_sp = std::make_shared<ProcessKDP>(target_sp, listener_sp);
113  return process_sp;
114 }
115 
116 bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
117  if (plugin_specified_by_name)
118  return true;
119 
120  // For now we are just making sure the file exists for a given module
121  Module *exe_module = target_sp->GetExecutableModulePointer();
122  if (exe_module) {
123  const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
124  switch (triple_ref.getOS()) {
125  case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
126  // iOS, but accept darwin just in case
127  case llvm::Triple::MacOSX: // For desktop targets
128  case llvm::Triple::IOS: // For arm targets
129  case llvm::Triple::TvOS:
130  case llvm::Triple::WatchOS:
131  if (triple_ref.getVendor() == llvm::Triple::Apple) {
132  ObjectFile *exe_objfile = exe_module->GetObjectFile();
133  if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
134  exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
135  return true;
136  }
137  break;
138 
139  default:
140  break;
141  }
142  }
143  return false;
144 }
145 
146 // ProcessKDP constructor
147 ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
148  : Process(target_sp, listener_sp),
149  m_comm("lldb.process.kdp-remote.communication"),
150  m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
151  m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
152  m_command_sp(), m_kernel_thread_wp() {
154  "async thread should exit");
156  "async thread continue");
157  const uint64_t timeout_seconds =
158  GetGlobalPluginProperties()->GetPacketTimeout();
159  if (timeout_seconds > 0)
160  m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
161 }
162 
163 // Destructor
165  Clear();
166  // We need to call finalize on the process before destroying ourselves to
167  // make sure all of the broadcaster cleanup goes as planned. If we destruct
168  // this class, then Process::~Process() might have problems trying to fully
169  // destroy the broadcaster.
170  Finalize();
171 }
172 
173 // PluginInterface
175  return GetPluginNameStatic();
176 }
177 
179 
181  Status error;
182  error.SetErrorString("launching not supported in kdp-remote plug-in");
183  return error;
184 }
185 
187  Status error;
188  error.SetErrorString(
189  "attaching to a by process ID not supported in kdp-remote plug-in");
190  return error;
191 }
192 
194  bool wait_for_launch) {
195  Status error;
196  error.SetErrorString(
197  "attaching to a by process name not supported in kdp-remote plug-in");
198  return error;
199 }
200 
202  uint32_t cpu = m_comm.GetCPUType();
203  if (cpu) {
204  uint32_t sub = m_comm.GetCPUSubtype();
205  arch.SetArchitecture(eArchTypeMachO, cpu, sub);
206  // Leave architecture vendor as unspecified unknown
207  arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
208  arch.GetTriple().setVendorName(llvm::StringRef());
209  return true;
210  }
211  arch.Clear();
212  return false;
213 }
214 
215 Status ProcessKDP::DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
216  Status error;
217 
218  // Don't let any JIT happen when doing KDP as we can't allocate memory and we
219  // don't want to be mucking with threads that might already be handling
220  // exceptions
221  SetCanJIT(false);
222 
223  if (remote_url.empty()) {
224  error.SetErrorStringWithFormat("empty connection URL");
225  return error;
226  }
227 
228  std::unique_ptr<ConnectionFileDescriptor> conn_up(
230  if (conn_up) {
231  // Only try once for now.
232  // TODO: check if we should be retrying?
233  const uint32_t max_retry_count = 1;
234  for (uint32_t retry_count = 0; retry_count < max_retry_count;
235  ++retry_count) {
236  if (conn_up->Connect(remote_url, &error) == eConnectionStatusSuccess)
237  break;
238  usleep(100000);
239  }
240  }
241 
242  if (conn_up->IsConnected()) {
243  const TCPSocket &socket =
244  static_cast<const TCPSocket &>(*conn_up->GetReadObject());
245  const uint16_t reply_port = socket.GetLocalPortNumber();
246 
247  if (reply_port != 0) {
248  m_comm.SetConnection(conn_up.release());
249 
250  if (m_comm.SendRequestReattach(reply_port)) {
251  if (m_comm.SendRequestConnect(reply_port, reply_port,
252  "Greetings from LLDB...")) {
253  m_comm.GetVersion();
254 
255  Target &target = GetTarget();
256  ArchSpec kernel_arch;
257  // The host architecture
258  GetHostArchitecture(kernel_arch);
259  ArchSpec target_arch = target.GetArchitecture();
260  // Merge in any unspecified stuff into the target architecture in
261  // case the target arch isn't set at all or incompletely.
262  target_arch.MergeFrom(kernel_arch);
263  target.SetArchitecture(target_arch);
264 
265  /* Get the kernel's UUID and load address via KDP_KERNELVERSION
266  * packet. */
267  /* An EFI kdp session has neither UUID nor load address. */
268 
269  UUID kernel_uuid = m_comm.GetUUID();
270  addr_t kernel_load_addr = m_comm.GetLoadAddress();
271 
272  if (m_comm.RemoteIsEFI()) {
273  // Select an invalid plugin name for the dynamic loader so one
274  // doesn't get used since EFI does its own manual loading via
275  // python scripting
276  static ConstString g_none_dynamic_loader("none");
277  m_dyld_plugin_name = g_none_dynamic_loader;
278 
279  if (kernel_uuid.IsValid()) {
280  // If EFI passed in a UUID= try to lookup UUID The slide will not
281  // be provided. But the UUID lookup will be used to launch EFI
282  // debug scripts from the dSYM, that can load all of the symbols.
283  ModuleSpec module_spec;
284  module_spec.GetUUID() = kernel_uuid;
285  module_spec.GetArchitecture() = target.GetArchitecture();
286 
287  // Lookup UUID locally, before attempting dsymForUUID like action
288  FileSpecList search_paths =
289  Target::GetDefaultDebugFileSearchPaths();
290  module_spec.GetSymbolFileSpec() =
291  Symbols::LocateExecutableSymbolFile(module_spec,
292  search_paths);
293  if (module_spec.GetSymbolFileSpec()) {
294  ModuleSpec executable_module_spec =
295  Symbols::LocateExecutableObjectFile(module_spec);
296  if (FileSystem::Instance().Exists(
297  executable_module_spec.GetFileSpec())) {
298  module_spec.GetFileSpec() =
299  executable_module_spec.GetFileSpec();
300  }
301  }
302  if (!module_spec.GetSymbolFileSpec() ||
303  !module_spec.GetSymbolFileSpec())
304  Symbols::DownloadObjectAndSymbolFile(module_spec, true);
305 
306  if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
307  ModuleSP module_sp(new Module(module_spec));
308  if (module_sp.get() && module_sp->GetObjectFile()) {
309  // Get the current target executable
310  ModuleSP exe_module_sp(target.GetExecutableModule());
311 
312  // Make sure you don't already have the right module loaded
313  // and they will be uniqued
314  if (exe_module_sp.get() != module_sp.get())
315  target.SetExecutableModule(module_sp, eLoadDependentsNo);
316  }
317  }
318  }
319  } else if (m_comm.RemoteIsDarwinKernel()) {
322  if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
323  m_kernel_load_addr = kernel_load_addr;
324  }
325  }
326 
327  // Set the thread ID
329  SetID(1);
330  GetThreadList();
332  StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
333  if (async_strm_sp) {
334  const char *cstr;
335  if ((cstr = m_comm.GetKernelVersion()) != NULL) {
336  async_strm_sp->Printf("Version: %s\n", cstr);
337  async_strm_sp->Flush();
338  }
339  // if ((cstr = m_comm.GetImagePath ()) != NULL)
340  // {
341  // async_strm_sp->Printf ("Image Path:
342  // %s\n", cstr);
343  // async_strm_sp->Flush();
344  // }
345  }
346  } else {
347  error.SetErrorString("KDP_REATTACH failed");
348  }
349  } else {
350  error.SetErrorString("KDP_REATTACH failed");
351  }
352  } else {
353  error.SetErrorString("invalid reply port from UDP connection");
354  }
355  } else {
356  if (error.Success())
357  error.SetErrorStringWithFormat("failed to connect to '%s'",
358  remote_url.str().c_str());
359  }
360  if (error.Fail())
361  m_comm.Disconnect();
362 
363  return error;
364 }
365 
366 // Process Control
368  ProcessLaunchInfo &launch_info) {
369  Status error;
370  error.SetErrorString("launching not supported in kdp-remote plug-in");
371  return error;
372 }
373 
374 Status
376  const ProcessAttachInfo &attach_info) {
377  Status error;
378  error.SetErrorString(
379  "attach to process by ID is not supported in kdp remote debugging");
380  return error;
381 }
382 
383 Status
384 ProcessKDP::DoAttachToProcessWithName(const char *process_name,
385  const ProcessAttachInfo &attach_info) {
386  Status error;
387  error.SetErrorString(
388  "attach to process by name is not supported in kdp remote debugging");
389  return error;
390 }
391 
392 void ProcessKDP::DidAttach(ArchSpec &process_arch) {
393  Process::DidAttach(process_arch);
394 
396  if (log)
397  log->Printf("ProcessKDP::DidAttach()");
398  if (GetID() != LLDB_INVALID_PROCESS_ID) {
399  GetHostArchitecture(process_arch);
400  }
401 }
402 
404 
406  if (m_dyld_up.get() == NULL)
407  m_dyld_up.reset(DynamicLoader::FindPlugin(
408  this,
410  return m_dyld_up.get();
411 }
412 
414 
416  Status error;
418  // Only start the async thread if we try to do any process control
419  if (!m_async_thread.IsJoinable())
421 
422  bool resume = false;
423 
424  // With KDP there is only one thread we can tell what to do
425  ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
426 
427  if (kernel_thread_sp) {
428  const StateType thread_resume_state =
429  kernel_thread_sp->GetTemporaryResumeState();
430 
431  if (log)
432  log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
433  StateAsCString(thread_resume_state));
434  switch (thread_resume_state) {
435  case eStateSuspended:
436  // Nothing to do here when a thread will stay suspended we just leave the
437  // CPU mask bit set to zero for the thread
438  if (log)
439  log->Printf("ProcessKDP::DoResume() = suspended???");
440  break;
441 
442  case eStateStepping: {
443  lldb::RegisterContextSP reg_ctx_sp(
444  kernel_thread_sp->GetRegisterContext());
445 
446  if (reg_ctx_sp) {
447  if (log)
448  log->Printf(
449  "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
450  reg_ctx_sp->HardwareSingleStep(true);
451  resume = true;
452  } else {
454  "KDP thread 0x%llx has no register context",
455  kernel_thread_sp->GetID());
456  }
457  } break;
458 
459  case eStateRunning: {
460  lldb::RegisterContextSP reg_ctx_sp(
461  kernel_thread_sp->GetRegisterContext());
462 
463  if (reg_ctx_sp) {
464  if (log)
465  log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
466  "(false);");
467  reg_ctx_sp->HardwareSingleStep(false);
468  resume = true;
469  } else {
471  "KDP thread 0x%llx has no register context",
472  kernel_thread_sp->GetID());
473  }
474  } break;
475 
476  default:
477  // The only valid thread resume states are listed above
478  llvm_unreachable("invalid thread resume state");
479  }
480  }
481 
482  if (resume) {
483  if (log)
484  log->Printf("ProcessKDP::DoResume () sending resume");
485 
486  if (m_comm.SendRequestResume()) {
489  } else
490  error.SetErrorString("KDP resume failed");
491  } else {
492  error.SetErrorString("kernel thread is suspended");
493  }
494 
495  return error;
496 }
497 
498 lldb::ThreadSP ProcessKDP::GetKernelThread() {
499  // KDP only tells us about one thread/core. Any other threads will usually
500  // be the ones that are read from memory by the OS plug-ins.
501 
502  ThreadSP thread_sp(m_kernel_thread_wp.lock());
503  if (!thread_sp) {
504  thread_sp = std::make_shared<ThreadKDP>(*this, g_kernel_tid);
505  m_kernel_thread_wp = thread_sp;
506  }
507  return thread_sp;
508 }
509 
511  ThreadList &new_thread_list) {
512  // locker will keep a mutex locked until it goes out of scope
514  LLDB_LOGV(log, "pid = {0}", GetID());
515 
516  // Even though there is a CPU mask, it doesn't mean we can see each CPU
517  // individually, there is really only one. Lets call this thread 1.
518  ThreadSP thread_sp(
519  old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
520  if (!thread_sp)
521  thread_sp = GetKernelThread();
522  new_thread_list.AddThread(thread_sp);
523 
524  return new_thread_list.GetSize(false) > 0;
525 }
526 
528  // Let all threads recover from stopping and do any clean up based on the
529  // previous thread state (if any).
531 }
532 
533 Status ProcessKDP::DoHalt(bool &caused_stop) {
534  Status error;
535 
536  if (m_comm.IsRunning()) {
537  if (m_destroy_in_process) {
538  // If we are attempting to destroy, we need to not return an error to Halt
539  // or DoDestroy won't get called. We are also currently running, so send
540  // a process stopped event
542  } else {
543  error.SetErrorString("KDP cannot interrupt a running kernel");
544  }
545  }
546  return error;
547 }
548 
549 Status ProcessKDP::DoDetach(bool keep_stopped) {
550  Status error;
552  if (log)
553  log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
554 
555  if (m_comm.IsRunning()) {
556  // We are running and we can't interrupt a running kernel, so we need to
557  // just close the connection to the kernel and hope for the best
558  } else {
559  // If we are going to keep the target stopped, then don't send the
560  // disconnect message.
561  if (!keep_stopped && m_comm.IsConnected()) {
562  const bool success = m_comm.SendRequestDisconnect();
563  if (log) {
564  if (success)
565  log->PutCString(
566  "ProcessKDP::DoDetach() detach packet sent successfully");
567  else
568  log->PutCString(
569  "ProcessKDP::DoDetach() connection channel shutdown failed");
570  }
571  m_comm.Disconnect();
572  }
573  }
574  StopAsyncThread();
575  m_comm.Clear();
576 
579 
580  // KillDebugserverProcess ();
581  return error;
582 }
583 
585  // For KDP there really is no difference between destroy and detach
586  bool keep_stopped = false;
587  return DoDetach(keep_stopped);
588 }
589 
590 // Process Queries
591 
593  return m_comm.IsConnected() && Process::IsAlive();
594 }
595 
596 // Process Memory
597 size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
598  Status &error) {
599  uint8_t *data_buffer = (uint8_t *)buf;
600  if (m_comm.IsConnected()) {
601  const size_t max_read_size = 512;
602  size_t total_bytes_read = 0;
603 
604  // Read the requested amount of memory in 512 byte chunks
605  while (total_bytes_read < size) {
606  size_t bytes_to_read_this_request = size - total_bytes_read;
607  if (bytes_to_read_this_request > max_read_size) {
608  bytes_to_read_this_request = max_read_size;
609  }
610  size_t bytes_read = m_comm.SendRequestReadMemory(
611  addr + total_bytes_read, data_buffer + total_bytes_read,
612  bytes_to_read_this_request, error);
613  total_bytes_read += bytes_read;
614  if (error.Fail() || bytes_read == 0) {
615  return total_bytes_read;
616  }
617  }
618 
619  return total_bytes_read;
620  }
621  error.SetErrorString("not connected");
622  return 0;
623 }
624 
625 size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
626  Status &error) {
627  if (m_comm.IsConnected())
628  return m_comm.SendRequestWriteMemory(addr, buf, size, error);
629  error.SetErrorString("not connected");
630  return 0;
631 }
632 
634  Status &error) {
635  error.SetErrorString(
636  "memory allocation not supported in kdp remote debugging");
637  return LLDB_INVALID_ADDRESS;
638 }
639 
641  Status error;
642  error.SetErrorString(
643  "memory deallocation not supported in kdp remote debugging");
644  return error;
645 }
646 
649  Status error;
650  if (!bp_site->IsEnabled()) {
651  if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
652  bp_site->SetEnabled(true);
653  bp_site->SetType(BreakpointSite::eExternal);
654  } else {
655  error.SetErrorString("KDP set breakpoint failed");
656  }
657  }
658  return error;
659  }
660  return EnableSoftwareBreakpoint(bp_site);
661 }
662 
665  Status error;
666  if (bp_site->IsEnabled()) {
667  BreakpointSite::Type bp_type = bp_site->GetType();
668  if (bp_type == BreakpointSite::eExternal) {
670  // We are trying to destroy our connection and we are running
671  bp_site->SetEnabled(false);
672  } else {
673  if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
674  bp_site->SetEnabled(false);
675  else
676  error.SetErrorString("KDP remove breakpoint failed");
677  }
678  } else {
679  error = DisableSoftwareBreakpoint(bp_site);
680  }
681  }
682  return error;
683  }
684  return DisableSoftwareBreakpoint(bp_site);
685 }
686 
688  Status error;
689  error.SetErrorString(
690  "watchpoints are not supported in kdp remote debugging");
691  return error;
692 }
693 
695  Status error;
696  error.SetErrorString(
697  "watchpoints are not supported in kdp remote debugging");
698  return error;
699 }
700 
702 
704  Status error;
705  error.SetErrorString(
706  "sending signals is not supported in kdp remote debugging");
707  return error;
708 }
709 
711  static llvm::once_flag g_once_flag;
712 
713  llvm::call_once(g_once_flag, []() {
714  PluginManager::RegisterPlugin(GetPluginNameStatic(),
717 
718  ProcessKDPLog::Initialize();
719  });
720 }
721 
723  if (!PluginManager::GetSettingForProcessPlugin(
724  debugger, PluginProperties::GetSettingName())) {
725  const bool is_global_setting = true;
726  PluginManager::CreateSettingForProcessPlugin(
727  debugger, GetGlobalPluginProperties()->GetValueProperties(),
728  ConstString("Properties for the kdp-remote process plug-in."),
729  is_global_setting);
730  }
731 }
732 
735 
736  if (log)
737  log->Printf("ProcessKDP::StartAsyncThread ()");
738 
740  return true;
741 
742  m_async_thread = ThreadLauncher::LaunchThread(
743  "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
744  return m_async_thread.IsJoinable();
745 }
746 
749 
750  if (log)
751  log->Printf("ProcessKDP::StopAsyncThread ()");
752 
754 
755  // Stop the stdio thread
757  m_async_thread.Join(nullptr);
758 }
759 
760 void *ProcessKDP::AsyncThread(void *arg) {
761  ProcessKDP *process = (ProcessKDP *)arg;
762 
763  const lldb::pid_t pid = process->GetID();
764 
766  if (log)
767  log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
768  ") thread starting...",
769  arg, pid);
770 
771  ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
772  EventSP event_sp;
773  const uint32_t desired_event_mask =
775 
776  if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
777  desired_event_mask) ==
778  desired_event_mask) {
779  bool done = false;
780  while (!done) {
781  if (log)
782  log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
783  ") listener.WaitForEvent (NULL, event_sp)...",
784  pid);
785  if (listener_sp->GetEvent(event_sp, llvm::None)) {
786  uint32_t event_type = event_sp->GetType();
787  if (log)
788  log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
789  ") Got an event of type: %d...",
790  pid, event_type);
791 
792  // When we are running, poll for 1 second to try and get an exception
793  // to indicate the process has stopped. If we don't get one, check to
794  // make sure no one asked us to exit
795  bool is_running = false;
796  DataExtractor exc_reply_packet;
797  do {
798  switch (event_type) {
800  is_running = true;
802  exc_reply_packet, 1 * USEC_PER_SEC)) {
803  ThreadSP thread_sp(process->GetKernelThread());
804  if (thread_sp) {
805  lldb::RegisterContextSP reg_ctx_sp(
806  thread_sp->GetRegisterContext());
807  if (reg_ctx_sp)
808  reg_ctx_sp->InvalidateAllRegisters();
809  static_cast<ThreadKDP *>(thread_sp.get())
810  ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
811  }
812 
813  // TODO: parse the stop reply packet
814  is_running = false;
815  process->SetPrivateState(eStateStopped);
816  } else {
817  // Check to see if we are supposed to exit. There is no way to
818  // interrupt a running kernel, so all we can do is wait for an
819  // exception or detach...
820  if (listener_sp->GetEvent(event_sp,
821  std::chrono::microseconds(0))) {
822  // We got an event, go through the loop again
823  event_type = event_sp->GetType();
824  }
825  }
826  } break;
827 
829  if (log)
830  log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
831  ") got eBroadcastBitAsyncThreadShouldExit...",
832  pid);
833  done = true;
834  is_running = false;
835  break;
836 
837  default:
838  if (log)
839  log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
840  ") got unknown event 0x%8.8x",
841  pid, event_type);
842  done = true;
843  is_running = false;
844  break;
845  }
846  } while (is_running);
847  } else {
848  if (log)
849  log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
850  ") listener.WaitForEvent (NULL, event_sp) => false",
851  pid);
852  done = true;
853  }
854  }
855  }
856 
857  if (log)
858  log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
859  ") thread exiting...",
860  arg, pid);
861 
862  process->m_async_thread.Reset();
863  return NULL;
864 }
865 
867 private:
868  OptionGroupOptions m_option_group;
869  OptionGroupUInt64 m_command_byte;
870  OptionGroupString m_packet_data;
871 
872  virtual Options *GetOptions() { return &m_option_group; }
873 
874 public:
876  : CommandObjectParsed(interpreter, "process plugin packet send",
877  "Send a custom packet through the KDP protocol by "
878  "specifying the command byte and the packet "
879  "payload data. A packet will be sent with a "
880  "correct header and payload, and the raw result "
881  "bytes will be displayed as a string value. ",
882  NULL),
883  m_option_group(),
884  m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
885  "Specify the command byte to use when sending the KDP "
886  "request packet.",
887  0),
888  m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
889  "Specify packet payload bytes as a hex ASCII string with "
890  "no spaces or hex prefixes.",
891  NULL) {
892  m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
893  m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
894  m_option_group.Finalize();
895  }
896 
898 
899  bool DoExecute(Args &command, CommandReturnObject &result) {
900  const size_t argc = command.GetArgumentCount();
901  if (argc == 0) {
902  if (!m_command_byte.GetOptionValue().OptionWasSet()) {
903  result.AppendError(
904  "the --command option must be set to a valid command byte");
906  } else {
907  const uint64_t command_byte =
908  m_command_byte.GetOptionValue().GetUInt64Value(0);
909  if (command_byte > 0 && command_byte <= UINT8_MAX) {
910  ProcessKDP *process =
911  (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
912  if (process) {
913  const StateType state = process->GetState();
914 
915  if (StateIsStoppedState(state, true)) {
916  std::vector<uint8_t> payload_bytes;
917  const char *ascii_hex_bytes_cstr =
918  m_packet_data.GetOptionValue().GetCurrentValue();
919  if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
920  StringExtractor extractor(ascii_hex_bytes_cstr);
921  const size_t ascii_hex_bytes_cstr_len =
922  extractor.GetStringRef().size();
923  if (ascii_hex_bytes_cstr_len & 1) {
924  result.AppendErrorWithFormat("payload data must contain an "
925  "even number of ASCII hex "
926  "characters: '%s'",
927  ascii_hex_bytes_cstr);
929  return false;
930  }
931  payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
932  if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
933  payload_bytes.size()) {
934  result.AppendErrorWithFormat("payload data must only contain "
935  "ASCII hex characters (no "
936  "spaces or hex prefixes): '%s'",
937  ascii_hex_bytes_cstr);
939  return false;
940  }
941  }
942  Status error;
943  DataExtractor reply;
944  process->GetCommunication().SendRawRequest(
945  command_byte,
946  payload_bytes.empty() ? NULL : payload_bytes.data(),
947  payload_bytes.size(), reply, error);
948 
949  if (error.Success()) {
950  // Copy the binary bytes into a hex ASCII string for the result
951  StreamString packet;
952  packet.PutBytesAsRawHex8(
953  reply.GetDataStart(), reply.GetByteSize(),
955  result.AppendMessage(packet.GetString());
957  return true;
958  } else {
959  const char *error_cstr = error.AsCString();
960  if (error_cstr && error_cstr[0])
961  result.AppendError(error_cstr);
962  else
963  result.AppendErrorWithFormat("unknown error 0x%8.8x",
964  error.GetError());
966  return false;
967  }
968  } else {
969  result.AppendErrorWithFormat("process must be stopped in order "
970  "to send KDP packets, state is %s",
971  StateAsCString(state));
973  }
974  } else {
975  result.AppendError("invalid process");
977  }
978  } else {
979  result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
980  ", valid values are 1 - 255",
981  command_byte);
983  }
984  }
985  } else {
986  result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
987  m_cmd_name.c_str());
989  }
990  return false;
991  }
992 };
993 
995 private:
996 public:
998  : CommandObjectMultiword(interpreter, "process plugin packet",
999  "Commands that deal with KDP remote packets.",
1000  NULL) {
1001  LoadSubCommand(
1002  "send",
1003  CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1004  }
1005 
1007 };
1008 
1010 public:
1013  interpreter, "process plugin",
1014  "Commands for operating on a ProcessKDP process.",
1015  "process plugin <subcommand> [<subcommand-options>]") {
1016  LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1017  interpreter)));
1018  }
1019 
1021 };
1022 
1024  if (!m_command_sp)
1025  m_command_sp = std::make_shared<CommandObjectMultiwordProcessKDP>(
1027  return m_command_sp.get();
1028 }
size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override
Actually do the reading of memory from a process.
Definition: ProcessKDP.cpp:597
A class to manage flag bits.
Definition: Debugger.h:82
Class that manages the actual breakpoint that will be inserted into the running program.
void UpdateThreadListIfNeeded()
Definition: Process.cpp:1230
lldb_private::Status DoLaunch(lldb_private::Module *exe_module, lldb_private::ProcessLaunchInfo &launch_info) override
Launch a new process.
Definition: ProcessKDP.cpp:367
An data extractor class.
Definition: DataExtractor.h:47
A command line argument class.
Definition: Args.h:32
static void DebuggerInitialize(lldb_private::Debugger &debugger)
Definition: ProcessKDP.cpp:722
OptionValueString & GetOptionValue()
static void Terminate()
Definition: ProcessKDP.cpp:103
lldb_private::Status DoDeallocateMemory(lldb::addr_t ptr) override
Actually deallocate memory in the process.
Definition: ProcessKDP.cpp:640
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
Definition: Broadcaster.h:361
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
Definition: ProcessKDP.cpp:875
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1796
const ArchSpec & GetArchitecture() const
Definition: Target.h:941
lldb_private::HostThread m_async_thread
Definition: ProcessKDP.h:175
CommandInterpreter & GetCommandInterpreter()
Definition: Debugger.h:152
bool IsValid() const
Definition: UUID.h:65
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
lldb::ThreadSP FindThreadByProtocolID(lldb::tid_t tid, bool can_update=true)
Definition: ThreadList.cpp:120
lldb_private::Status DoHalt(bool &caused_stop) override
Halts a running process.
Definition: ProcessKDP.cpp:533
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:92
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void SetConnection(Connection *connection)
Sets the connection that it to be used by this class.
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.cpp:254
lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, lldb_private::Status &error) override
Actually allocate memory in the process.
Definition: ProcessKDP.cpp:633
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition: Module.cpp:1251
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
Definition: ProcessKDP.cpp:527
lldb::ThreadSP GetKernelThread()
Definition: ProcessKDP.cpp:498
size_t WaitForPacketWithTimeoutMicroSeconds(lldb_private::DataExtractor &response, uint32_t usec)
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:49
lldb_private::Status DisableWatchpoint(lldb_private::Watchpoint *wp, bool notify=true) override
Definition: ProcessKDP.cpp:694
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
ThreadList & GetThreadList()
Definition: Process.h:2045
void Clear()
Definition: ProcessKDP.cpp:701
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1347
lldb_private::Status DoAttachToProcessWithName(const char *process_name, const lldb_private::ProcessAttachInfo &attach_info) override
Attach to an existing process using a partial process name.
Definition: ProcessKDP.cpp:384
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec *crash_file_path)
Definition: ProcessKDP.cpp:107
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:58
lldb_private::DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
Definition: ProcessKDP.cpp:405
lldb_private::Status DoDetach(bool keep_stopped) override
Detaches from a running or stopped process.
Definition: ProcessKDP.cpp:549
lldb::ThreadWP m_kernel_thread_wp
Definition: ProcessKDP.h:179
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false)
Set the architecture for this target.
Definition: Target.cpp:1498
lldb_private::Status EnableWatchpoint(lldb_private::Watchpoint *wp, bool notify=true) override
Definition: ProcessKDP.cpp:687
static constexpr PropertyDefinition g_properties[]
Definition: Debugger.cpp:198
Process or thread is stopped and can be examined.
bool LocalBreakpointsAreSupported()
static void Initialize()
Definition: ProcessKDP.cpp:710
uint32_t SendRequestReadMemory(lldb::addr_t addr, void *dst, uint32_t dst_size, lldb_private::Status &error)
lldb_private::ConstString m_dyld_plugin_name
Definition: ProcessKDP.h:176
CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
uint32_t SendRequestWriteMemory(lldb::addr_t addr, const void *src, uint32_t src_len, lldb_private::Status &error)
static const char * GetPluginDescriptionStatic()
Definition: ProcessKDP.cpp:98
uint32_t GetPluginVersion() override
Definition: ProcessKDP.cpp:178
bool IsAlive() override
Check if a process is still alive.
Definition: ProcessKDP.cpp:592
std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout)
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:431
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
Definition: Broadcaster.h:283
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition: Module.cpp:1074
uint16_t GetLocalPortNumber() const
Definition: TCPSocket.cpp:71
lldb_private::Status WillAttachToProcessWithID(lldb::pid_t pid) override
Called before attaching to a process.
Definition: ProcessKDP.cpp:186
bool UpdateThreadList(lldb_private::ThreadList &old_thread_list, lldb_private::ThreadList &new_thread_list) override
Definition: ProcessKDP.cpp:510
ProcessKDP(lldb::TargetSP target_sp, lldb::ListenerSP listener)
Definition: ProcessKDP.cpp:147
void Clear()
Clears the object state.
Definition: ArchSpec.cpp:580
int usleep(uint32_t useconds)
lldb_private::Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch) override
Called before attaching to a process.
Definition: ProcessKDP.cpp:193
bool StartAsyncThread()
Definition: ProcessKDP.cpp:733
lldb_private::Status EnableBreakpointSite(lldb_private::BreakpointSite *bp_site) override
Definition: ProcessKDP.cpp:647
bool IsEnabled() const
Tells whether the current breakpoint site is enabled or not.
bool SendRawRequest(uint8_t command_byte, const void *src, uint32_t src_len, lldb_private::DataExtractor &reply, lldb_private::Status &error)
bool IsRunning() const
lldb_private::Status DoSignal(int signal) override
Sends a process a UNIX signal signal.
Definition: ProcessKDP.cpp:703
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
Definition: ProcessKDP.cpp:997
lldb::StreamSP GetAsyncOutputStream()
Definition: Debugger.cpp:1149
lldb_private::Status DoConnectRemote(lldb_private::Stream *strm, llvm::StringRef remote_url) override
Attach to a remote system via a URL.
Definition: ProcessKDP.cpp:215
uint64_t GetUInt64Value(uint64_t fail_value, bool *success_ptr)
Definition: OptionValue.cpp:19
void StopAsyncThread()
Definition: ProcessKDP.cpp:747
CommunicationKDP & GetCommunication()
Definition: ProcessKDP.h:137
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition: State.cpp:89
void SetEnabled(bool enabled)
Sets whether the current breakpoint site is enabled or not.
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
virtual void Finalize()
This object is about to be destroyed, do any necessary cleanup.
Definition: Process.cpp:615
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:109
BreakpointSite::Type GetType() const
Process has been detached and can&#39;t be examined.
static void * AsyncThread(void *arg)
Definition: ProcessKDP.cpp:760
lldb_private::UUID GetUUID()
size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, lldb_private::Status &error) override
Actually do the writing of memory to a process.
Definition: ProcessKDP.cpp:625
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
uint64_t tid_t
Definition: lldb-types.h:86
void AppendMessage(llvm::StringRef in_string)
llvm::StringRef GetString() const
lldb::CommandObjectSP m_command_sp
Definition: ProcessKDP.h:178
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
Definition: ProcessKDP.cpp:116
A plug-in interface definition class for debugging a process.
Definition: Process.h:353
CommunicationKDP m_comm
Broadcaster event bits definitions.
Definition: ProcessKDP.h:173
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition: Target.cpp:1380
bool Success() const
Test for success condition.
Definition: Status.cpp:287
const char * GetCurrentValue() const
Status Join(lldb::thread_result_t *result)
Definition: HostThread.cpp:20
Process or thread is in the process of stepping and can not be examined.
static lldb_private::ConstString GetPluginNameStatic()
lldb_private::CommandObject * GetPluginCommandObject() override
Return a multi-word command object that can be used to expose plug-in specific commands.
FileSpec & GetFileSpec()
Definition: ModuleSpec.h:75
lldb_private::Status DisableBreakpointSite(lldb_private::BreakpointSite *bp_site) override
Definition: ProcessKDP.cpp:663
bool IsConnected() const
Check if the connection is valid.
#define KDP_LOG_THREAD
Definition: ProcessKDPLog.h:15
A plug-in interface definition class for dynamic loaders.
Definition: DynamicLoader.h:64
void ResumePrivateStateThread()
Definition: Process.cpp:3579
void DidAttach(lldb_private::ArchSpec &process_arch) override
Called after attaching a process.
Definition: ProcessKDP.cpp:392
uint64_t GetByteSize() const
Get the number of bytes contained in this object.
OptionValueUInt64 & GetOptionValue()
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
Definition: ProcessKDP.cpp:403
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
lldb_private::Status WillResume() override
Called before resuming to a process.
Definition: ProcessKDP.cpp:413
lldb::addr_t GetLoadAddress()
ArchSpec & GetArchitecture()
Definition: ModuleSpec.h:111
lldb_private::Status DoResume() override
Resumes all of a process&#39;s threads as configured using the Thread run control functions.
Definition: ProcessKDP.cpp:415
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1872
A command line option parsing protocol class.
Definition: Options.h:62
void SetType(BreakpointSite::Type type)
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1194
void void AppendError(llvm::StringRef in_string)
lldb_private::Broadcaster m_async_broadcaster
Definition: ProcessKDP.h:174
uint64_t addr_t
Definition: lldb-types.h:83
const uint8_t * GetDataStart() const
Get the data start pointer.
A uniqued constant string class.
Definition: ConstString.h:38
lldb_private::Status DoAttachToProcessWithID(lldb::pid_t pid, const lldb_private::ProcessAttachInfo &attach_info) override
Attach to an existing process using a process ID.
Definition: ProcessKDP.cpp:375
static lldb_private::ConstString GetPluginNameStatic()
Definition: ProcessKDP.cpp:93
virtual lldb::addr_t GetLoadAddress() const
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:247
FileSpec & GetSymbolFileSpec()
Definition: ModuleSpec.h:99
lldb_private::Status DoDestroy() override
Definition: ProcessKDP.cpp:584
bool SendRequestBreakpoint(bool set, lldb::addr_t addr)
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition: ArchSpec.cpp:859
void PutCString(const char *cstr)
Definition: Log.cpp:109
void SetID(lldb::user_id_t uid)
Set accessor for the user ID.
Definition: UserID.h:55
Definition: SBAddress.h:15
~ProcessKDP() override
Definition: ProcessKDP.cpp:164
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition: Process.h:2657
uint64_t pid_t
Definition: lldb-types.h:85
bool GetHostArchitecture(lldb_private::ArchSpec &arch)
Definition: ProcessKDP.cpp:201
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:110
void AddThread(const lldb::ThreadSP &thread_sp)
virtual lldb::OptionValuePropertiesSP GetValueProperties() const
uint32_t GetSize(bool can_update=true)
Definition: ThreadList.cpp:82
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
std::string & GetStringRef()
lldb::ByteOrder InlHostByteOrder()
Definition: Endian.h:25
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition: Options.cpp:843
#define LLDB_OPT_SET_1
Definition: lldb-defines.h:111
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
#define USEC_PER_SEC
Definition: ProcessKDP.cpp:41
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition: ArchSpec.cpp:892
bool SendRequestConnect(uint16_t reply_port, uint16_t exc_port, const char *greeting)
ValueType GetError() const
Access the error value.
Definition: Status.cpp:174
lldb::addr_t m_kernel_load_addr
Definition: ProcessKDP.h:177
static const lldb::tid_t g_kernel_tid
Definition: ProcessKDP.cpp:91
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition: Target.cpp:1431
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition: Process.cpp:2406
#define KDP_LOG_PROCESS
Definition: ProcessKDPLog.h:14
bool IsEmpty() const
Test for empty string.
Definition: ConstString.h:340
#define LLDB_LOGV(log,...)
Definition: Log.h:216
const char * GetKernelVersion()
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:406
void SetStatus(lldb::ReturnStatus status)
Debugger & GetDebugger()
Definition: Target.h:974
lldb_private::ConstString GetPluginName() override
Definition: ProcessKDP.cpp:174
bool DoExecute(Args &command, CommandReturnObject &result)
Definition: ProcessKDP.cpp:899
void SetPrivateState(lldb::StateType state)
Definition: Process.cpp:1465
lldb::DynamicLoaderUP m_dyld_up
Definition: Process.h:2677
bool SendRequestReattach(uint16_t reply_port)
An error handling class.
Definition: Status.h:44
lldb_private::Status WillLaunch(lldb_private::Module *module) override
Called before launching to a process.
Definition: ProcessKDP.cpp:180
Process or thread is running and can&#39;t be examined.