LLDB  mainline
Process.cpp
Go to the documentation of this file.
1 //===-- Process.cpp -------------------------------------------------------===//
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 <atomic>
10 #include <memory>
11 #include <mutex>
12 
13 #include "llvm/ADT/ScopeExit.h"
14 #include "llvm/Support/ScopedPrinter.h"
15 #include "llvm/Support/Threading.h"
16 
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/StreamFile.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/OptionParser.h"
33 #include "lldb/Host/Pipe.h"
34 #include "lldb/Host/Terminal.h"
39 #include "lldb/Symbol/Function.h"
40 #include "lldb/Symbol/Symbol.h"
41 #include "lldb/Target/ABI.h"
45 #include "lldb/Target/JITLoader.h"
47 #include "lldb/Target/Language.h"
52 #include "lldb/Target/Platform.h"
53 #include "lldb/Target/Process.h"
55 #include "lldb/Target/StopInfo.h"
58 #include "lldb/Target/Target.h"
59 #include "lldb/Target/TargetList.h"
60 #include "lldb/Target/Thread.h"
61 #include "lldb/Target/ThreadPlan.h"
66 #include "lldb/Utility/Event.h"
67 #include "lldb/Utility/Log.h"
71 #include "lldb/Utility/State.h"
72 #include "lldb/Utility/Timer.h"
73 
74 using namespace lldb;
75 using namespace lldb_private;
76 using namespace std::chrono;
77 
78 // Comment out line below to disable memory caching, overriding the process
79 // setting target.process.disable-memory-cache
80 #define ENABLE_MEMORY_CACHING
81 
82 #ifdef ENABLE_MEMORY_CACHING
83 #define DISABLE_MEM_CACHE_DEFAULT false
84 #else
85 #define DISABLE_MEM_CACHE_DEFAULT true
86 #endif
87 
89  : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
90 public:
92 
94  bool will_modify,
95  uint32_t idx) const override {
96  // When getting the value for a key from the process options, we will
97  // always try and grab the setting from the current process if there is
98  // one. Else we just use the one from this instance.
99  if (exe_ctx) {
100  Process *process = exe_ctx->GetProcessPtr();
101  if (process) {
102  ProcessOptionValueProperties *instance_properties =
103  static_cast<ProcessOptionValueProperties *>(
104  process->GetValueProperties().get());
105  if (this != instance_properties)
106  return instance_properties->ProtectedGetPropertyAtIndex(idx);
107  }
108  }
109  return ProtectedGetPropertyAtIndex(idx);
110  }
111 };
112 
113 #define LLDB_PROPERTIES_process
114 #include "TargetProperties.inc"
115 
116 enum {
117 #define LLDB_PROPERTIES_process
118 #include "TargetPropertiesEnum.inc"
120 };
121 
122 #define LLDB_PROPERTIES_process_experimental
123 #include "TargetProperties.inc"
124 
125 enum {
126 #define LLDB_PROPERTIES_process_experimental
127 #include "TargetPropertiesEnum.inc"
128 };
129 
131  : public Cloneable<ProcessExperimentalOptionValueProperties,
132  OptionValueProperties> {
133 public:
135  : Cloneable(
136  ConstString(Properties::GetExperimentalSettingsName())) {}
137 };
138 
139 ProcessExperimentalProperties::ProcessExperimentalProperties()
140  : Properties(OptionValuePropertiesSP(
142  m_collection_sp->Initialize(g_process_experimental_properties);
143 }
144 
146  : Properties(),
147  m_process(process) // Can be nullptr for global ProcessProperties
148 {
149  if (process == nullptr) {
150  // Global process properties, set them up one time
152  std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
153  m_collection_sp->Initialize(g_process_properties);
154  m_collection_sp->AppendProperty(
155  ConstString("thread"), ConstString("Settings specific to threads."),
157  } else {
160  m_collection_sp->SetValueChangedCallback(
161  ePropertyPythonOSPluginPath,
162  [this] { m_process->LoadOperatingSystemPlugin(true); });
163  }
164 
166  std::make_unique<ProcessExperimentalProperties>();
167  m_collection_sp->AppendProperty(
169  ConstString("Experimental settings - setting these won't produce "
170  "errors if the setting is not present."),
171  true, m_experimental_properties_up->GetValueProperties());
172 }
173 
175 
177  const uint32_t idx = ePropertyDisableMemCache;
178  return m_collection_sp->GetPropertyAtIndexAsBoolean(
179  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
180 }
181 
183  const uint32_t idx = ePropertyMemCacheLineSize;
184  return m_collection_sp->GetPropertyAtIndexAsUInt64(
185  nullptr, idx, g_process_properties[idx].default_uint_value);
186 }
187 
189  Args args;
190  const uint32_t idx = ePropertyExtraStartCommand;
191  m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
192  return args;
193 }
194 
196  const uint32_t idx = ePropertyExtraStartCommand;
197  m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
198 }
199 
201  const uint32_t idx = ePropertyPythonOSPluginPath;
202  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
203 }
204 
206  const uint32_t idx = ePropertyVirtualAddressableBits;
207  return m_collection_sp->GetPropertyAtIndexAsUInt64(
208  nullptr, idx, g_process_properties[idx].default_uint_value);
209 }
210 
212  const uint32_t idx = ePropertyVirtualAddressableBits;
213  m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, bits);
214 }
216  const uint32_t idx = ePropertyPythonOSPluginPath;
217  m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
218 }
219 
221  const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
222  return m_collection_sp->GetPropertyAtIndexAsBoolean(
223  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
224 }
225 
227  const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
228  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
229 }
230 
232  const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
233  return m_collection_sp->GetPropertyAtIndexAsBoolean(
234  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
235 }
236 
238  const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
239  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
240 }
241 
243  const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
244  return m_collection_sp->GetPropertyAtIndexAsBoolean(
245  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
246 }
247 
249  const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
250  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
251 }
252 
254  const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
255  return m_collection_sp->GetPropertyAtIndexAsBoolean(
256  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
257 }
258 
260  const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
261  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, disable);
262  m_process->Flush();
263 }
264 
266  const uint32_t idx = ePropertyDetachKeepsStopped;
267  return m_collection_sp->GetPropertyAtIndexAsBoolean(
268  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
269 }
270 
272  const uint32_t idx = ePropertyDetachKeepsStopped;
273  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
274 }
275 
277  const uint32_t idx = ePropertyWarningOptimization;
278  return m_collection_sp->GetPropertyAtIndexAsBoolean(
279  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
280 }
281 
283  const uint32_t idx = ePropertyWarningUnsupportedLanguage;
284  return m_collection_sp->GetPropertyAtIndexAsBoolean(
285  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
286 }
287 
289  const uint32_t idx = ePropertyStopOnExec;
290  return m_collection_sp->GetPropertyAtIndexAsBoolean(
291  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
292 }
293 
295  const uint32_t idx = ePropertyUtilityExpressionTimeout;
296  uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
297  nullptr, idx, g_process_properties[idx].default_uint_value);
298  return std::chrono::seconds(value);
299 }
300 
301 std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {
302  const uint32_t idx = ePropertyInterruptTimeout;
303  uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
304  nullptr, idx, g_process_properties[idx].default_uint_value);
305  return std::chrono::seconds(value);
306 }
307 
309  const uint32_t idx = ePropertySteppingRunsAllThreads;
310  return m_collection_sp->GetPropertyAtIndexAsBoolean(
311  nullptr, idx, g_process_properties[idx].default_uint_value != 0);
312 }
313 
315  const bool fail_value = true;
316  const Property *exp_property =
317  m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
318  OptionValueProperties *exp_values =
319  exp_property->GetValue()->GetAsProperties();
320  if (!exp_values)
321  return fail_value;
322 
323  return exp_values->GetPropertyAtIndexAsBoolean(
324  nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
325 }
326 
328  const Property *exp_property =
329  m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
330  OptionValueProperties *exp_values =
331  exp_property->GetValue()->GetAsProperties();
332  if (exp_values)
333  exp_values->SetPropertyAtIndexAsBoolean(
334  nullptr, ePropertyOSPluginReportsAllThreads, does_report);
335 }
336 
337 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
338  llvm::StringRef plugin_name,
339  ListenerSP listener_sp,
340  const FileSpec *crash_file_path,
341  bool can_connect) {
342  static uint32_t g_process_unique_id = 0;
343 
344  ProcessSP process_sp;
345  ProcessCreateInstance create_callback = nullptr;
346  if (!plugin_name.empty()) {
347  ConstString const_plugin_name(plugin_name);
348  create_callback =
350  if (create_callback) {
351  process_sp = create_callback(target_sp, listener_sp, crash_file_path,
352  can_connect);
353  if (process_sp) {
354  if (process_sp->CanDebug(target_sp, true)) {
355  process_sp->m_process_unique_id = ++g_process_unique_id;
356  } else
357  process_sp.reset();
358  }
359  }
360  } else {
361  for (uint32_t idx = 0;
362  (create_callback =
364  ++idx) {
365  process_sp = create_callback(target_sp, listener_sp, crash_file_path,
366  can_connect);
367  if (process_sp) {
368  if (process_sp->CanDebug(target_sp, false)) {
369  process_sp->m_process_unique_id = ++g_process_unique_id;
370  break;
371  } else
372  process_sp.reset();
373  }
374  }
375  }
376  return process_sp;
377 }
378 
380  static ConstString class_name("lldb.process");
381  return class_name;
382 }
383 
384 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
385  : Process(target_sp, listener_sp,
386  UnixSignals::Create(HostInfo::GetArchitecture())) {
387  // This constructor just delegates to the full Process constructor,
388  // defaulting to using the Host's UnixSignals.
389 }
390 
391 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
392  const UnixSignalsSP &unix_signals_sp)
393  : ProcessProperties(this),
394  Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
395  Process::GetStaticBroadcasterClass().AsCString()),
396  m_target_wp(target_sp), m_public_state(eStateUnloaded),
397  m_private_state(eStateUnloaded),
398  m_private_state_broadcaster(nullptr,
399  "lldb.process.internal_state_broadcaster"),
400  m_private_state_control_broadcaster(
401  nullptr, "lldb.process.internal_state_control_broadcaster"),
402  m_private_state_listener_sp(
403  Listener::MakeListener("lldb.process.internal_state_listener")),
404  m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
405  m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
406  m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
407  m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
408  m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
409  m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
410  m_breakpoint_site_list(), m_dynamic_checkers_up(),
411  m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
412  m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
413  m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
414  m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
415  m_memory_cache(*this), m_allocated_memory_cache(*this),
416  m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
417  m_private_run_lock(), m_finalizing(false),
418  m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
419  m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
420  m_can_interpret_function_calls(false), m_warnings_issued(),
421  m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
423 
425  LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
426 
427  if (!m_unix_signals_sp)
428  m_unix_signals_sp = std::make_shared<UnixSignals>();
429 
430  SetEventName(eBroadcastBitStateChanged, "state-changed");
431  SetEventName(eBroadcastBitInterrupt, "interrupt");
432  SetEventName(eBroadcastBitSTDOUT, "stdout-available");
433  SetEventName(eBroadcastBitSTDERR, "stderr-available");
434  SetEventName(eBroadcastBitProfileData, "profile-data-available");
435  SetEventName(eBroadcastBitStructuredData, "structured-data-available");
436 
438  eBroadcastInternalStateControlStop, "control-stop");
440  eBroadcastInternalStateControlPause, "control-pause");
442  eBroadcastInternalStateControlResume, "control-resume");
443 
444  m_listener_sp->StartListeningForEvents(
448 
449  m_private_state_listener_sp->StartListeningForEvents(
452 
453  m_private_state_listener_sp->StartListeningForEvents(
457  // We need something valid here, even if just the default UnixSignalsSP.
458  assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
459 
460  // Allow the platform to override the default cache line size
461  OptionValueSP value_sp =
463  ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
464  ->GetValue();
465  uint32_t platform_cache_line_size =
466  target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
467  if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
468  value_sp->SetUInt64Value(platform_cache_line_size);
469 
471 }
472 
475  LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
477 
478  // ThreadList::Clear() will try to acquire this process's mutex, so
479  // explicitly clear the thread list here to ensure that the mutex is not
480  // destroyed before the thread list.
482 }
483 
485  // NOTE: intentional leak so we don't crash if global destructor chain gets
486  // called as other threads still use the result of this function
487  static ProcessPropertiesSP *g_settings_sp_ptr =
488  new ProcessPropertiesSP(new ProcessProperties(nullptr));
489  return *g_settings_sp_ptr;
490 }
491 
493  if (m_finalizing.exchange(true))
494  return;
495 
496  // Destroy the process. This will call the virtual function DoDestroy under
497  // the hood, giving our derived class a chance to do the ncessary tear down.
498  DestroyImpl(false);
499 
500  // Clear our broadcaster before we proceed with destroying
502 
503  // Do any cleanup needed prior to being destructed... Subclasses that
504  // override this method should call this superclass method as well.
505 
506  // We need to destroy the loader before the derived Process class gets
507  // destroyed since it is very likely that undoing the loader will require
508  // access to the real process.
509  m_dynamic_checkers_up.reset();
510  m_abi_sp.reset();
511  m_os_up.reset();
512  m_system_runtime_up.reset();
513  m_dyld_up.reset();
514  m_jit_loaders_up.reset();
521  std::vector<Notifications> empty_notifications;
522  m_notifications.swap(empty_notifications);
523  m_image_tokens.clear();
526  {
527  std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
528  m_language_runtimes.clear();
529  }
531  m_next_event_action_up.reset();
532  // Clear the last natural stop ID since it has a strong reference to this
533  // process
535  //#ifdef LLDB_CONFIGURATION_DEBUG
536  // StreamFile s(stdout, false);
537  // EventSP event_sp;
538  // while (m_private_state_listener_sp->GetNextEvent(event_sp))
539  // {
540  // event_sp->Dump (&s);
541  // s.EOL();
542  // }
543  //#endif
544  // We have to be very careful here as the m_private_state_listener might
545  // contain events that have ProcessSP values in them which can keep this
546  // process around forever. These events need to be cleared out.
548  m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
550  m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
553 }
554 
556  m_notifications.push_back(callbacks);
557  if (callbacks.initialize != nullptr)
558  callbacks.initialize(callbacks.baton, this);
559 }
560 
562  std::vector<Notifications>::iterator pos, end = m_notifications.end();
563  for (pos = m_notifications.begin(); pos != end; ++pos) {
564  if (pos->baton == callbacks.baton &&
565  pos->initialize == callbacks.initialize &&
566  pos->process_state_changed == callbacks.process_state_changed) {
567  m_notifications.erase(pos);
568  return true;
569  }
570  }
571  return false;
572 }
573 
575  std::vector<Notifications>::iterator notification_pos,
576  notification_end = m_notifications.end();
577  for (notification_pos = m_notifications.begin();
578  notification_pos != notification_end; ++notification_pos) {
579  if (notification_pos->process_state_changed)
580  notification_pos->process_state_changed(notification_pos->baton, this,
581  state);
582  }
583 }
584 
585 // FIXME: We need to do some work on events before the general Listener sees
586 // them.
587 // For instance if we are continuing from a breakpoint, we need to ensure that
588 // we do the little "insert real insn, step & stop" trick. But we can't do
589 // that when the event is delivered by the broadcaster - since that is done on
590 // the thread that is waiting for new events, so if we needed more than one
591 // event for our handling, we would stall. So instead we do it when we fetch
592 // the event off of the queue.
593 //
594 
595 StateType Process::GetNextEvent(EventSP &event_sp) {
596  StateType state = eStateInvalid;
597 
598  if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
599  std::chrono::seconds(0)) &&
600  event_sp)
601  state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
602 
603  return state;
604 }
605 
607  const Timeout<std::micro> &timeout) {
608  // don't sync (potentially context switch) in case where there is no process
609  // IO
611  return;
612 
613  auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
614 
616  if (Result) {
617  LLDB_LOG(
618  log,
619  "waited from m_iohandler_sync to change from {0}. New value is {1}.",
620  iohandler_id, *Result);
621  } else {
622  LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
623  iohandler_id);
624  }
625 }
626 
628  EventSP *event_sp_ptr, bool wait_always,
629  ListenerSP hijack_listener_sp,
630  Stream *stream, bool use_run_lock) {
631  // We can't just wait for a "stopped" event, because the stopped event may
632  // have restarted the target. We have to actually check each event, and in
633  // the case of a stopped event check the restarted flag on the event.
634  if (event_sp_ptr)
635  event_sp_ptr->reset();
636  StateType state = GetState();
637  // If we are exited or detached, we won't ever get back to any other valid
638  // state...
639  if (state == eStateDetached || state == eStateExited)
640  return state;
641 
643  LLDB_LOG(log, "timeout = {0}", timeout);
644 
645  if (!wait_always && StateIsStoppedState(state, true) &&
647  LLDB_LOGF(log,
648  "Process::%s returning without waiting for events; process "
649  "private and public states are already 'stopped'.",
650  __FUNCTION__);
651  // We need to toggle the run lock as this won't get done in
652  // SetPublicState() if the process is hijacked.
653  if (hijack_listener_sp && use_run_lock)
655  return state;
656  }
657 
658  while (state != eStateInvalid) {
659  EventSP event_sp;
660  state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
661  if (event_sp_ptr && event_sp)
662  *event_sp_ptr = event_sp;
663 
664  bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
666  pop_process_io_handler);
667 
668  switch (state) {
669  case eStateCrashed:
670  case eStateDetached:
671  case eStateExited:
672  case eStateUnloaded:
673  // We need to toggle the run lock as this won't get done in
674  // SetPublicState() if the process is hijacked.
675  if (hijack_listener_sp && use_run_lock)
677  return state;
678  case eStateStopped:
680  continue;
681  else {
682  // We need to toggle the run lock as this won't get done in
683  // SetPublicState() if the process is hijacked.
684  if (hijack_listener_sp && use_run_lock)
686  return state;
687  }
688  default:
689  continue;
690  }
691  }
692  return state;
693 }
694 
695 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
696  Stream *stream,
697  bool &pop_process_io_handler) {
698  const bool handle_pop = pop_process_io_handler;
699 
700  pop_process_io_handler = false;
701  ProcessSP process_sp =
703 
704  if (!process_sp)
705  return false;
706 
707  StateType event_state =
709  if (event_state == eStateInvalid)
710  return false;
711 
712  switch (event_state) {
713  case eStateInvalid:
714  case eStateUnloaded:
715  case eStateAttaching:
716  case eStateLaunching:
717  case eStateStepping:
718  case eStateDetached:
719  if (stream)
720  stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
721  StateAsCString(event_state));
722  if (event_state == eStateDetached)
723  pop_process_io_handler = true;
724  break;
725 
726  case eStateConnected:
727  case eStateRunning:
728  // Don't be chatty when we run...
729  break;
730 
731  case eStateExited:
732  if (stream)
733  process_sp->GetStatus(*stream);
734  pop_process_io_handler = true;
735  break;
736 
737  case eStateStopped:
738  case eStateCrashed:
739  case eStateSuspended:
740  // Make sure the program hasn't been auto-restarted:
742  if (stream) {
743  size_t num_reasons =
745  if (num_reasons > 0) {
746  // FIXME: Do we want to report this, or would that just be annoyingly
747  // chatty?
748  if (num_reasons == 1) {
749  const char *reason =
751  event_sp.get(), 0);
752  stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
753  process_sp->GetID(),
754  reason ? reason : "<UNKNOWN REASON>");
755  } else {
756  stream->Printf("Process %" PRIu64
757  " stopped and restarted, reasons:\n",
758  process_sp->GetID());
759 
760  for (size_t i = 0; i < num_reasons; i++) {
761  const char *reason =
763  event_sp.get(), i);
764  stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
765  }
766  }
767  }
768  }
769  } else {
770  StopInfoSP curr_thread_stop_info_sp;
771  // Lock the thread list so it doesn't change on us, this is the scope for
772  // the locker:
773  {
774  ThreadList &thread_list = process_sp->GetThreadList();
775  std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
776 
777  ThreadSP curr_thread(thread_list.GetSelectedThread());
778  ThreadSP thread;
779  StopReason curr_thread_stop_reason = eStopReasonInvalid;
780  if (curr_thread) {
781  curr_thread_stop_reason = curr_thread->GetStopReason();
782  curr_thread_stop_info_sp = curr_thread->GetStopInfo();
783  }
784  if (!curr_thread || !curr_thread->IsValid() ||
785  curr_thread_stop_reason == eStopReasonInvalid ||
786  curr_thread_stop_reason == eStopReasonNone) {
787  // Prefer a thread that has just completed its plan over another
788  // thread as current thread.
789  ThreadSP plan_thread;
790  ThreadSP other_thread;
791 
792  const size_t num_threads = thread_list.GetSize();
793  size_t i;
794  for (i = 0; i < num_threads; ++i) {
795  thread = thread_list.GetThreadAtIndex(i);
796  StopReason thread_stop_reason = thread->GetStopReason();
797  switch (thread_stop_reason) {
798  case eStopReasonInvalid:
799  case eStopReasonNone:
800  break;
801 
802  case eStopReasonSignal: {
803  // Don't select a signal thread if we weren't going to stop at
804  // that signal. We have to have had another reason for stopping
805  // here, and the user doesn't want to see this thread.
806  uint64_t signo = thread->GetStopInfo()->GetValue();
807  if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
808  if (!other_thread)
809  other_thread = thread;
810  }
811  break;
812  }
813  case eStopReasonTrace:
817  case eStopReasonExec:
818  case eStopReasonFork:
819  case eStopReasonVFork:
824  if (!other_thread)
825  other_thread = thread;
826  break;
828  if (!plan_thread)
829  plan_thread = thread;
830  break;
831  }
832  }
833  if (plan_thread)
834  thread_list.SetSelectedThreadByID(plan_thread->GetID());
835  else if (other_thread)
836  thread_list.SetSelectedThreadByID(other_thread->GetID());
837  else {
838  if (curr_thread && curr_thread->IsValid())
839  thread = curr_thread;
840  else
841  thread = thread_list.GetThreadAtIndex(0);
842 
843  if (thread)
844  thread_list.SetSelectedThreadByID(thread->GetID());
845  }
846  }
847  }
848  // Drop the ThreadList mutex by here, since GetThreadStatus below might
849  // have to run code, e.g. for Data formatters, and if we hold the
850  // ThreadList mutex, then the process is going to have a hard time
851  // restarting the process.
852  if (stream) {
853  Debugger &debugger = process_sp->GetTarget().GetDebugger();
854  if (debugger.GetTargetList().GetSelectedTarget().get() ==
855  &process_sp->GetTarget()) {
856  ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
857 
858  if (!thread_sp || !thread_sp->IsValid())
859  return false;
860 
861  const bool only_threads_with_stop_reason = true;
862  const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
863  const uint32_t num_frames = 1;
864  const uint32_t num_frames_with_source = 1;
865  const bool stop_format = true;
866 
867  process_sp->GetStatus(*stream);
868  process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
869  start_frame, num_frames,
870  num_frames_with_source,
871  stop_format);
872  if (curr_thread_stop_info_sp) {
873  lldb::addr_t crashing_address;
874  ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
875  curr_thread_stop_info_sp, &crashing_address);
876  if (valobj_sp) {
878  ValueObject::GetExpressionPathFormat::
879  eGetExpressionPathFormatHonorPointers;
880  stream->PutCString("Likely cause: ");
881  valobj_sp->GetExpressionPath(*stream, format);
882  stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
883  }
884  }
885  } else {
886  uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
887  process_sp->GetTarget().shared_from_this());
888  if (target_idx != UINT32_MAX)
889  stream->Printf("Target %d: (", target_idx);
890  else
891  stream->Printf("Target <unknown index>: (");
892  process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
893  stream->Printf(") stopped.\n");
894  }
895  }
896 
897  // Pop the process IO handler
898  pop_process_io_handler = true;
899  }
900  break;
901  }
902 
903  if (handle_pop && pop_process_io_handler)
904  process_sp->PopProcessIOHandler();
905 
906  return true;
907 }
908 
909 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
910  if (listener_sp) {
911  return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
913  } else
914  return false;
915 }
916 
918 
920  const Timeout<std::micro> &timeout,
921  ListenerSP hijack_listener_sp) {
923  LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
924 
925  ListenerSP listener_sp = hijack_listener_sp;
926  if (!listener_sp)
927  listener_sp = m_listener_sp;
928 
929  StateType state = eStateInvalid;
930  if (listener_sp->GetEventForBroadcasterWithType(
932  timeout)) {
933  if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
934  state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
935  else
936  LLDB_LOG(log, "got no event or was interrupted.");
937  }
938 
939  LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
940  return state;
941 }
942 
945 
946  LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
947 
948  Event *event_ptr;
949  event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
951  if (log) {
952  if (event_ptr) {
953  LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
955  } else {
956  LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
957  }
958  }
959  return event_ptr;
960 }
961 
962 StateType
964  const Timeout<std::micro> &timeout) {
966  LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
967 
968  StateType state = eStateInvalid;
969  if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
972  timeout))
973  if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
974  state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
975 
976  LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
977  state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
978  return state;
979 }
980 
981 bool Process::GetEventsPrivate(EventSP &event_sp,
982  const Timeout<std::micro> &timeout,
983  bool control_only) {
985  LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
986 
987  if (control_only)
988  return m_private_state_listener_sp->GetEventForBroadcaster(
989  &m_private_state_control_broadcaster, event_sp, timeout);
990  else
991  return m_private_state_listener_sp->GetEvent(event_sp, timeout);
992 }
993 
994 bool Process::IsRunning() const {
996 }
997 
999  std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1000 
1002  return m_exit_status;
1003  return -1;
1004 }
1005 
1007  std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1008 
1009  if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1010  return m_exit_string.c_str();
1011  return nullptr;
1012 }
1013 
1014 bool Process::SetExitStatus(int status, const char *cstr) {
1015  // Use a mutex to protect setting the exit status.
1016  std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1017 
1020  LLDB_LOGF(
1021  log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1022  status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
1023 
1024  // We were already in the exited state
1026  LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1027  "state was already set to eStateExited");
1028  return false;
1029  }
1030 
1031  m_exit_status = status;
1032  if (cstr)
1033  m_exit_string = cstr;
1034  else
1035  m_exit_string.clear();
1036 
1037  // Clear the last natural stop ID since it has a strong reference to this
1038  // process
1040 
1042 
1043  // Allow subclasses to do some cleanup
1044  DidExit();
1045 
1046  return true;
1047 }
1048 
1050  switch (m_private_state.GetValue()) {
1051  case eStateConnected:
1052  case eStateAttaching:
1053  case eStateLaunching:
1054  case eStateStopped:
1055  case eStateRunning:
1056  case eStateStepping:
1057  case eStateCrashed:
1058  case eStateSuspended:
1059  return true;
1060  default:
1061  return false;
1062  }
1063 }
1064 
1065 // This static callback can be used to watch for local child processes on the
1066 // current host. The child process exits, the process will be found in the
1067 // global target list (we want to be completely sure that the
1068 // lldb_private::Process doesn't go away before we can deliver the signal.
1070  lldb::pid_t pid, bool exited,
1071  int signo, // Zero for no signal
1072  int exit_status // Exit value of process if signal is zero
1073  ) {
1075  LLDB_LOGF(log,
1076  "Process::SetProcessExitStatus (pid=%" PRIu64
1077  ", exited=%i, signal=%i, exit_status=%i)\n",
1078  pid, exited, signo, exit_status);
1079 
1080  if (exited) {
1081  TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1082  if (target_sp) {
1083  ProcessSP process_sp(target_sp->GetProcessSP());
1084  if (process_sp) {
1085  const char *signal_cstr = nullptr;
1086  if (signo)
1087  signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1088 
1089  process_sp->SetExitStatus(exit_status, signal_cstr);
1090  }
1091  }
1092  return true;
1093  }
1094  return false;
1095 }
1096 
1098  ThreadList &new_thread_list) {
1100  return DoUpdateThreadList(old_thread_list, new_thread_list);
1101 }
1102 
1104  const uint32_t stop_id = GetStopID();
1105  if (m_thread_list.GetSize(false) == 0 ||
1106  stop_id != m_thread_list.GetStopID()) {
1107  bool clear_unused_threads = true;
1108  const StateType state = GetPrivateState();
1109  if (StateIsStoppedState(state, true)) {
1110  std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1111  m_thread_list.SetStopID(stop_id);
1112 
1113  // m_thread_list does have its own mutex, but we need to hold onto the
1114  // mutex between the call to UpdateThreadList(...) and the
1115  // os->UpdateThreadList(...) so it doesn't change on us
1116  ThreadList &old_thread_list = m_thread_list;
1117  ThreadList real_thread_list(this);
1118  ThreadList new_thread_list(this);
1119  // Always update the thread list with the protocol specific thread list,
1120  // but only update if "true" is returned
1121  if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1122  // Don't call into the OperatingSystem to update the thread list if we
1123  // are shutting down, since that may call back into the SBAPI's,
1124  // requiring the API lock which is already held by whoever is shutting
1125  // us down, causing a deadlock.
1127  if (os && !m_destroy_in_process) {
1128  // Clear any old backing threads where memory threads might have been
1129  // backed by actual threads from the lldb_private::Process subclass
1130  size_t num_old_threads = old_thread_list.GetSize(false);
1131  for (size_t i = 0; i < num_old_threads; ++i)
1132  old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1133  // See if the OS plugin reports all threads. If it does, then
1134  // it is safe to clear unseen thread's plans here. Otherwise we
1135  // should preserve them in case they show up again:
1136  clear_unused_threads = GetOSPluginReportsAllThreads();
1137 
1138  // Turn off dynamic types to ensure we don't run any expressions.
1139  // Objective-C can run an expression to determine if a SBValue is a
1140  // dynamic type or not and we need to avoid this. OperatingSystem
1141  // plug-ins can't run expressions that require running code...
1142 
1143  Target &target = GetTarget();
1144  const lldb::DynamicValueType saved_prefer_dynamic =
1145  target.GetPreferDynamicValue();
1146  if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1148 
1149  // Now let the OperatingSystem plug-in update the thread list
1150 
1151  os->UpdateThreadList(
1152  old_thread_list, // Old list full of threads created by OS plug-in
1153  real_thread_list, // The actual thread list full of threads
1154  // created by each lldb_private::Process
1155  // subclass
1156  new_thread_list); // The new thread list that we will show to the
1157  // user that gets filled in
1158 
1159  if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1160  target.SetPreferDynamicValue(saved_prefer_dynamic);
1161  } else {
1162  // No OS plug-in, the new thread list is the same as the real thread
1163  // list.
1164  new_thread_list = real_thread_list;
1165  }
1166 
1167  m_thread_list_real.Update(real_thread_list);
1168  m_thread_list.Update(new_thread_list);
1169  m_thread_list.SetStopID(stop_id);
1170 
1172  // Clear any extended threads that we may have accumulated previously
1175 
1176  m_queue_list.Clear();
1178  }
1179  }
1180  // Now update the plan stack map.
1181  // If we do have an OS plugin, any absent real threads in the
1182  // m_thread_list have already been removed from the ThreadPlanStackMap.
1183  // So any remaining threads are OS Plugin threads, and those we want to
1184  // preserve in case they show up again.
1185  m_thread_plans.Update(m_thread_list, clear_unused_threads);
1186  }
1187  }
1188 }
1189 
1191  return m_thread_plans.Find(tid);
1192 }
1193 
1195  return m_thread_plans.PrunePlansForTID(tid);
1196 }
1197 
1199  m_thread_plans.Update(GetThreadList(), true, false);
1200 }
1201 
1203  lldb::DescriptionLevel desc_level,
1204  bool internal, bool condense_trivial,
1205  bool skip_unreported_plans) {
1207  strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1208 }
1210  bool internal, bool condense_trivial,
1211  bool skip_unreported_plans) {
1212  m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1213  skip_unreported_plans);
1214 }
1215 
1217  if (m_system_runtime_up) {
1218  if (m_queue_list.GetSize() == 0 ||
1220  const StateType state = GetPrivateState();
1221  if (StateIsStoppedState(state, true)) {
1222  m_system_runtime_up->PopulateQueueList(m_queue_list);
1224  }
1225  }
1226  }
1227 }
1228 
1231  if (os)
1232  return os->CreateThread(tid, context);
1233  return ThreadSP();
1234 }
1235 
1237  return AssignIndexIDToThread(thread_id);
1238 }
1239 
1240 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1241  return (m_thread_id_to_index_id_map.find(thread_id) !=
1243 }
1244 
1246  uint32_t result = 0;
1247  std::map<uint64_t, uint32_t>::iterator iterator =
1248  m_thread_id_to_index_id_map.find(thread_id);
1249  if (iterator == m_thread_id_to_index_id_map.end()) {
1250  result = ++m_thread_index_id;
1251  m_thread_id_to_index_id_map[thread_id] = result;
1252  } else {
1253  result = iterator->second;
1254  }
1255 
1256  return result;
1257 }
1258 
1260  return m_public_state.GetValue();
1261 }
1262 
1263 void Process::SetPublicState(StateType new_state, bool restarted) {
1266  LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1267  StateAsCString(new_state), restarted);
1268  const StateType old_state = m_public_state.GetValue();
1269  m_public_state.SetValue(new_state);
1270 
1271  // On the transition from Run to Stopped, we unlock the writer end of the run
1272  // lock. The lock gets locked in Resume, which is the public API to tell the
1273  // program to run.
1275  if (new_state == eStateDetached) {
1276  LLDB_LOGF(log,
1277  "Process::SetPublicState (%s) -- unlocking run lock for detach",
1278  StateAsCString(new_state));
1280  } else {
1281  const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1282  const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1283  if ((old_state_is_stopped != new_state_is_stopped)) {
1284  if (new_state_is_stopped && !restarted) {
1285  LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1286  StateAsCString(new_state));
1288  }
1289  }
1290  }
1291  }
1292 }
1293 
1297  LLDB_LOGF(log, "Process::Resume -- locking run lock");
1299  Status error("Resume request failed - process still running.");
1300  LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1301  return error;
1302  }
1304  if (!error.Success()) {
1305  // Undo running state change
1307  }
1308  return error;
1309 }
1310 
1311 static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1312 
1316  LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
1318  Status error("Resume request failed - process still running.");
1319  LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1320  return error;
1321  }
1322 
1323  ListenerSP listener_sp(
1325  HijackProcessEvents(listener_sp);
1326 
1328  if (error.Success()) {
1329  StateType state = WaitForProcessToStop(llvm::None, nullptr, true,
1330  listener_sp, stream);
1331  const bool must_be_alive =
1332  false; // eStateExited is ok, so this must be false
1333  if (!StateIsStoppedState(state, must_be_alive))
1334  error.SetErrorStringWithFormat(
1335  "process not in stopped state after synchronous resume: %s",
1336  StateAsCString(state));
1337  } else {
1338  // Undo running state change
1340  }
1341 
1342  // Undo the hijacking of process events...
1344 
1345  return error;
1346 }
1347 
1350  const char *hijacking_name = GetHijackingListenerName();
1351  if (hijacking_name &&
1352  strcmp(hijacking_name, g_resume_sync_name))
1353  return true;
1354  }
1355  return false;
1356 }
1357 
1360  const char *hijacking_name = GetHijackingListenerName();
1361  if (hijacking_name &&
1362  strcmp(hijacking_name, g_resume_sync_name) == 0)
1363  return true;
1364  }
1365  return false;
1366 }
1367 
1369 
1371  if (m_finalizing)
1372  return;
1373 
1376  bool state_changed = false;
1377 
1378  LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
1379 
1380  std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1381  std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1382 
1383  const StateType old_state = m_private_state.GetValueNoLock();
1384  state_changed = old_state != new_state;
1385 
1386  const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1387  const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1388  if (old_state_is_stopped != new_state_is_stopped) {
1389  if (new_state_is_stopped)
1391  else
1393  }
1394 
1395  if (state_changed) {
1396  m_private_state.SetValueNoLock(new_state);
1397  EventSP event_sp(
1399  new ProcessEventData(shared_from_this(), new_state)));
1400  if (StateIsStoppedState(new_state, false)) {
1401  // Note, this currently assumes that all threads in the list stop when
1402  // the process stops. In the future we will want to support a debugging
1403  // model where some threads continue to run while others are stopped.
1404  // When that happens we will either need a way for the thread list to
1405  // identify which threads are stopping or create a special thread list
1406  // containing only threads which actually stopped.
1407  //
1408  // The process plugin is responsible for managing the actual behavior of
1409  // the threads and should have stopped any threads that are going to stop
1410  // before we get here.
1412 
1413  m_mod_id.BumpStopID();
1417  LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1418  StateAsCString(new_state), m_mod_id.GetStopID());
1419  }
1420 
1422  } else {
1423  LLDB_LOGF(log,
1424  "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1425  StateAsCString(new_state));
1426  }
1427 }
1428 
1431 }
1432 
1435 }
1436 
1438 
1439 const lldb::ABISP &Process::GetABI() {
1440  if (!m_abi_sp)
1441  m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1442  return m_abi_sp;
1443 }
1444 
1445 std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
1446  std::vector<LanguageRuntime *> language_runtimes;
1447 
1448  if (m_finalizing)
1449  return language_runtimes;
1450 
1451  std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1452  // Before we pass off a copy of the language runtimes, we must make sure that
1453  // our collection is properly populated. It's possible that some of the
1454  // language runtimes were not loaded yet, either because nobody requested it
1455  // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1456  // hadn't been loaded).
1457  for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1458  if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
1459  language_runtimes.emplace_back(runtime);
1460  }
1461 
1462  return language_runtimes;
1463 }
1464 
1466  if (m_finalizing)
1467  return nullptr;
1468 
1469  LanguageRuntime *runtime = nullptr;
1470 
1471  std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1472  LanguageRuntimeCollection::iterator pos;
1473  pos = m_language_runtimes.find(language);
1474  if (pos == m_language_runtimes.end() || !pos->second) {
1475  lldb::LanguageRuntimeSP runtime_sp(
1476  LanguageRuntime::FindPlugin(this, language));
1477 
1478  m_language_runtimes[language] = runtime_sp;
1479  runtime = runtime_sp.get();
1480  } else
1481  runtime = pos->second.get();
1482 
1483  if (runtime)
1484  // It's possible that a language runtime can support multiple LanguageTypes,
1485  // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1486  // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1487  // primary language type and make sure that our runtime supports it.
1488  assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1489 
1490  return runtime;
1491 }
1492 
1494  if (m_finalizing)
1495  return false;
1496 
1497  if (in_value.IsDynamic())
1498  return false;
1499  LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1500 
1501  if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1502  LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1503  return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1504  }
1505 
1506  for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1507  if (runtime->CouldHaveDynamicValue(in_value))
1508  return true;
1509  }
1510 
1511  return false;
1512 }
1513 
1515  m_dynamic_checkers_up.reset(dynamic_checkers);
1516 }
1517 
1519  return m_breakpoint_site_list;
1520 }
1521 
1523  return m_breakpoint_site_list;
1524 }
1525 
1527  m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1528  // bp_site->SetEnabled(true);
1529  DisableBreakpointSite(bp_site);
1530  });
1531 }
1532 
1535 
1536  if (error.Success())
1537  m_breakpoint_site_list.Remove(break_id);
1538 
1539  return error;
1540 }
1541 
1543  Status error;
1544  BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1545  if (bp_site_sp) {
1546  if (bp_site_sp->IsEnabled())
1547  error = DisableBreakpointSite(bp_site_sp.get());
1548  } else {
1549  error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1550  break_id);
1551  }
1552 
1553  return error;
1554 }
1555 
1557  Status error;
1558  BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1559  if (bp_site_sp) {
1560  if (!bp_site_sp->IsEnabled())
1561  error = EnableBreakpointSite(bp_site_sp.get());
1562  } else {
1563  error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1564  break_id);
1565  }
1566  return error;
1567 }
1568 
1570 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1571  bool use_hardware) {
1572  addr_t load_addr = LLDB_INVALID_ADDRESS;
1573 
1574  bool show_error = true;
1575  switch (GetState()) {
1576  case eStateInvalid:
1577  case eStateUnloaded:
1578  case eStateConnected:
1579  case eStateAttaching:
1580  case eStateLaunching:
1581  case eStateDetached:
1582  case eStateExited:
1583  show_error = false;
1584  break;
1585 
1586  case eStateStopped:
1587  case eStateRunning:
1588  case eStateStepping:
1589  case eStateCrashed:
1590  case eStateSuspended:
1591  show_error = IsAlive();
1592  break;
1593  }
1594 
1595  // Reset the IsIndirect flag here, in case the location changes from pointing
1596  // to a indirect symbol to a regular symbol.
1597  owner->SetIsIndirect(false);
1598 
1599  if (owner->ShouldResolveIndirectFunctions()) {
1600  Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1601  if (symbol && symbol->IsIndirect()) {
1602  Status error;
1603  Address symbol_address = symbol->GetAddress();
1604  load_addr = ResolveIndirectFunction(&symbol_address, error);
1605  if (!error.Success() && show_error) {
1607  "warning: failed to resolve indirect function at 0x%" PRIx64
1608  " for breakpoint %i.%i: %s\n",
1609  symbol->GetLoadAddress(&GetTarget()),
1610  owner->GetBreakpoint().GetID(), owner->GetID(),
1611  error.AsCString() ? error.AsCString() : "unknown error");
1612  return LLDB_INVALID_BREAK_ID;
1613  }
1614  Address resolved_address(load_addr);
1615  load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1616  owner->SetIsIndirect(true);
1617  } else
1618  load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1619  } else
1620  load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1621 
1622  if (load_addr != LLDB_INVALID_ADDRESS) {
1623  BreakpointSiteSP bp_site_sp;
1624 
1625  // Look up this breakpoint site. If it exists, then add this new owner,
1626  // otherwise create a new breakpoint site and add it.
1627 
1628  bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1629 
1630  if (bp_site_sp) {
1631  bp_site_sp->AddOwner(owner);
1632  owner->SetBreakpointSite(bp_site_sp);
1633  return bp_site_sp->GetID();
1634  } else {
1635  bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1636  load_addr, use_hardware));
1637  if (bp_site_sp) {
1638  Status error = EnableBreakpointSite(bp_site_sp.get());
1639  if (error.Success()) {
1640  owner->SetBreakpointSite(bp_site_sp);
1641  return m_breakpoint_site_list.Add(bp_site_sp);
1642  } else {
1643  if (show_error || use_hardware) {
1644  // Report error for setting breakpoint...
1646  "warning: failed to set breakpoint site at 0x%" PRIx64
1647  " for breakpoint %i.%i: %s\n",
1648  load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1649  error.AsCString() ? error.AsCString() : "unknown error");
1650  }
1651  }
1652  }
1653  }
1654  }
1655  // We failed to enable the breakpoint
1656  return LLDB_INVALID_BREAK_ID;
1657 }
1658 
1660  lldb::user_id_t owner_loc_id,
1661  BreakpointSiteSP &bp_site_sp) {
1662  uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1663  if (num_owners == 0) {
1664  // Don't try to disable the site if we don't have a live process anymore.
1665  if (IsAlive())
1666  DisableBreakpointSite(bp_site_sp.get());
1667  m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1668  }
1669 }
1670 
1672  uint8_t *buf) const {
1673  size_t bytes_removed = 0;
1674  BreakpointSiteList bp_sites_in_range;
1675 
1676  if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1677  bp_sites_in_range)) {
1678  bp_sites_in_range.ForEach([bp_addr, size,
1679  buf](BreakpointSite *bp_site) -> void {
1680  if (bp_site->GetType() == BreakpointSite::eSoftware) {
1681  addr_t intersect_addr;
1682  size_t intersect_size;
1683  size_t opcode_offset;
1684  if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1685  &intersect_size, &opcode_offset)) {
1686  assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1687  assert(bp_addr < intersect_addr + intersect_size &&
1688  intersect_addr + intersect_size <= bp_addr + size);
1689  assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1690  size_t buf_offset = intersect_addr - bp_addr;
1691  ::memcpy(buf + buf_offset,
1692  bp_site->GetSavedOpcodeBytes() + opcode_offset,
1693  intersect_size);
1694  }
1695  }
1696  });
1697  }
1698  return bytes_removed;
1699 }
1700 
1701 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1702  PlatformSP platform_sp(GetTarget().GetPlatform());
1703  if (platform_sp)
1704  return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1705  return 0;
1706 }
1707 
1709  Status error;
1710  assert(bp_site != nullptr);
1712  const addr_t bp_addr = bp_site->GetLoadAddress();
1713  LLDB_LOGF(
1714  log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1715  bp_site->GetID(), (uint64_t)bp_addr);
1716  if (bp_site->IsEnabled()) {
1717  LLDB_LOGF(
1718  log,
1719  "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1720  " -- already enabled",
1721  bp_site->GetID(), (uint64_t)bp_addr);
1722  return error;
1723  }
1724 
1725  if (bp_addr == LLDB_INVALID_ADDRESS) {
1726  error.SetErrorString("BreakpointSite contains an invalid load address.");
1727  return error;
1728  }
1729  // Ask the lldb::Process subclass to fill in the correct software breakpoint
1730  // trap for the breakpoint site
1731  const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1732 
1733  if (bp_opcode_size == 0) {
1734  error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1735  "returned zero, unable to get breakpoint "
1736  "trap for address 0x%" PRIx64,
1737  bp_addr);
1738  } else {
1739  const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1740 
1741  if (bp_opcode_bytes == nullptr) {
1742  error.SetErrorString(
1743  "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1744  return error;
1745  }
1746 
1747  // Save the original opcode by reading it
1748  if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1749  error) == bp_opcode_size) {
1750  // Write a software breakpoint in place of the original opcode
1751  if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1752  bp_opcode_size) {
1753  uint8_t verify_bp_opcode_bytes[64];
1754  if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1755  error) == bp_opcode_size) {
1756  if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1757  bp_opcode_size) == 0) {
1758  bp_site->SetEnabled(true);
1760  LLDB_LOGF(log,
1761  "Process::EnableSoftwareBreakpoint (site_id = %d) "
1762  "addr = 0x%" PRIx64 " -- SUCCESS",
1763  bp_site->GetID(), (uint64_t)bp_addr);
1764  } else
1765  error.SetErrorString(
1766  "failed to verify the breakpoint trap in memory.");
1767  } else
1768  error.SetErrorString(
1769  "Unable to read memory to verify breakpoint trap.");
1770  } else
1771  error.SetErrorString("Unable to write breakpoint trap to memory.");
1772  } else
1773  error.SetErrorString("Unable to read memory at breakpoint address.");
1774  }
1775  if (log && error.Fail())
1776  LLDB_LOGF(
1777  log,
1778  "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1779  " -- FAILED: %s",
1780  bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1781  return error;
1782 }
1783 
1785  Status error;
1786  assert(bp_site != nullptr);
1788  addr_t bp_addr = bp_site->GetLoadAddress();
1789  lldb::user_id_t breakID = bp_site->GetID();
1790  LLDB_LOGF(log,
1791  "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1792  ") addr = 0x%" PRIx64,
1793  breakID, (uint64_t)bp_addr);
1794 
1795  if (bp_site->IsHardware()) {
1796  error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1797  } else if (bp_site->IsEnabled()) {
1798  const size_t break_op_size = bp_site->GetByteSize();
1799  const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1800  if (break_op_size > 0) {
1801  // Clear a software breakpoint instruction
1802  uint8_t curr_break_op[8];
1803  assert(break_op_size <= sizeof(curr_break_op));
1804  bool break_op_found = false;
1805 
1806  // Read the breakpoint opcode
1807  if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1808  break_op_size) {
1809  bool verify = false;
1810  // Make sure the breakpoint opcode exists at this address
1811  if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1812  break_op_found = true;
1813  // We found a valid breakpoint opcode at this address, now restore
1814  // the saved opcode.
1815  if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1816  break_op_size, error) == break_op_size) {
1817  verify = true;
1818  } else
1819  error.SetErrorString(
1820  "Memory write failed when restoring original opcode.");
1821  } else {
1822  error.SetErrorString(
1823  "Original breakpoint trap is no longer in memory.");
1824  // Set verify to true and so we can check if the original opcode has
1825  // already been restored
1826  verify = true;
1827  }
1828 
1829  if (verify) {
1830  uint8_t verify_opcode[8];
1831  assert(break_op_size < sizeof(verify_opcode));
1832  // Verify that our original opcode made it back to the inferior
1833  if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1834  break_op_size) {
1835  // compare the memory we just read with the original opcode
1836  if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1837  break_op_size) == 0) {
1838  // SUCCESS
1839  bp_site->SetEnabled(false);
1840  LLDB_LOGF(log,
1841  "Process::DisableSoftwareBreakpoint (site_id = %d) "
1842  "addr = 0x%" PRIx64 " -- SUCCESS",
1843  bp_site->GetID(), (uint64_t)bp_addr);
1844  return error;
1845  } else {
1846  if (break_op_found)
1847  error.SetErrorString("Failed to restore original opcode.");
1848  }
1849  } else
1850  error.SetErrorString("Failed to read memory to verify that "
1851  "breakpoint trap was restored.");
1852  }
1853  } else
1854  error.SetErrorString(
1855  "Unable to read memory that should contain the breakpoint trap.");
1856  }
1857  } else {
1858  LLDB_LOGF(
1859  log,
1860  "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1861  " -- already disabled",
1862  bp_site->GetID(), (uint64_t)bp_addr);
1863  return error;
1864  }
1865 
1866  LLDB_LOGF(
1867  log,
1868  "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1869  " -- FAILED: %s",
1870  bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1871  return error;
1872 }
1873 
1874 // Uncomment to verify memory caching works after making changes to caching
1875 // code
1876 //#define VERIFY_MEMORY_READS
1877 
1878 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1879  error.Clear();
1880  if (!GetDisableMemoryCache()) {
1881 #if defined(VERIFY_MEMORY_READS)
1882  // Memory caching is enabled, with debug verification
1883 
1884  if (buf && size) {
1885  // Uncomment the line below to make sure memory caching is working.
1886  // I ran this through the test suite and got no assertions, so I am
1887  // pretty confident this is working well. If any changes are made to
1888  // memory caching, uncomment the line below and test your changes!
1889 
1890  // Verify all memory reads by using the cache first, then redundantly
1891  // reading the same memory from the inferior and comparing to make sure
1892  // everything is exactly the same.
1893  std::string verify_buf(size, '\0');
1894  assert(verify_buf.size() == size);
1895  const size_t cache_bytes_read =
1896  m_memory_cache.Read(this, addr, buf, size, error);
1897  Status verify_error;
1898  const size_t verify_bytes_read =
1899  ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1900  verify_buf.size(), verify_error);
1901  assert(cache_bytes_read == verify_bytes_read);
1902  assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1903  assert(verify_error.Success() == error.Success());
1904  return cache_bytes_read;
1905  }
1906  return 0;
1907 #else // !defined(VERIFY_MEMORY_READS)
1908  // Memory caching is enabled, without debug verification
1909 
1910  return m_memory_cache.Read(addr, buf, size, error);
1911 #endif // defined (VERIFY_MEMORY_READS)
1912  } else {
1913  // Memory caching is disabled
1914 
1915  return ReadMemoryFromInferior(addr, buf, size, error);
1916  }
1917 }
1918 
1920  Status &error) {
1921  char buf[256];
1922  out_str.clear();
1923  addr_t curr_addr = addr;
1924  while (true) {
1925  size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1926  if (length == 0)
1927  break;
1928  out_str.append(buf, length);
1929  // If we got "length - 1" bytes, we didn't get the whole C string, we need
1930  // to read some more characters
1931  if (length == sizeof(buf) - 1)
1932  curr_addr += length;
1933  else
1934  break;
1935  }
1936  return out_str.size();
1937 }
1938 
1939 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
1940  Status &error, size_t type_width) {
1941  size_t total_bytes_read = 0;
1942  if (dst && max_bytes && type_width && max_bytes >= type_width) {
1943  // Ensure a null terminator independent of the number of bytes that is
1944  // read.
1945  memset(dst, 0, max_bytes);
1946  size_t bytes_left = max_bytes - type_width;
1947 
1948  const char terminator[4] = {'\0', '\0', '\0', '\0'};
1949  assert(sizeof(terminator) >= type_width && "Attempting to validate a "
1950  "string with more than 4 bytes "
1951  "per character!");
1952 
1953  addr_t curr_addr = addr;
1954  const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1955  char *curr_dst = dst;
1956 
1957  error.Clear();
1958  while (bytes_left > 0 && error.Success()) {
1959  addr_t cache_line_bytes_left =
1960  cache_line_size - (curr_addr % cache_line_size);
1961  addr_t bytes_to_read =
1962  std::min<addr_t>(bytes_left, cache_line_bytes_left);
1963  size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
1964 
1965  if (bytes_read == 0)
1966  break;
1967 
1968  // Search for a null terminator of correct size and alignment in
1969  // bytes_read
1970  size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
1971  for (size_t i = aligned_start;
1972  i + type_width <= total_bytes_read + bytes_read; i += type_width)
1973  if (::memcmp(&dst[i], terminator, type_width) == 0) {
1974  error.Clear();
1975  return i;
1976  }
1977 
1978  total_bytes_read += bytes_read;
1979  curr_dst += bytes_read;
1980  curr_addr += bytes_read;
1981  bytes_left -= bytes_read;
1982  }
1983  } else {
1984  if (max_bytes)
1985  error.SetErrorString("invalid arguments");
1986  }
1987  return total_bytes_read;
1988 }
1989 
1990 // Deprecated in favor of ReadStringFromMemory which has wchar support and
1991 // correct code to find null terminators.
1993  size_t dst_max_len,
1994  Status &result_error) {
1995  size_t total_cstr_len = 0;
1996  if (dst && dst_max_len) {
1997  result_error.Clear();
1998  // NULL out everything just to be safe
1999  memset(dst, 0, dst_max_len);
2000  Status error;
2001  addr_t curr_addr = addr;
2002  const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2003  size_t bytes_left = dst_max_len - 1;
2004  char *curr_dst = dst;
2005 
2006  while (bytes_left > 0) {
2007  addr_t cache_line_bytes_left =
2008  cache_line_size - (curr_addr % cache_line_size);
2009  addr_t bytes_to_read =
2010  std::min<addr_t>(bytes_left, cache_line_bytes_left);
2011  size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2012 
2013  if (bytes_read == 0) {
2014  result_error = error;
2015  dst[total_cstr_len] = '\0';
2016  break;
2017  }
2018  const size_t len = strlen(curr_dst);
2019 
2020  total_cstr_len += len;
2021 
2022  if (len < bytes_to_read)
2023  break;
2024 
2025  curr_dst += bytes_read;
2026  curr_addr += bytes_read;
2027  bytes_left -= bytes_read;
2028  }
2029  } else {
2030  if (dst == nullptr)
2031  result_error.SetErrorString("invalid arguments");
2032  else
2033  result_error.Clear();
2034  }
2035  return total_cstr_len;
2036 }
2037 
2038 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2039  Status &error) {
2041 
2042  if (buf == nullptr || size == 0)
2043  return 0;
2044 
2045  size_t bytes_read = 0;
2046  uint8_t *bytes = (uint8_t *)buf;
2047 
2048  while (bytes_read < size) {
2049  const size_t curr_size = size - bytes_read;
2050  const size_t curr_bytes_read =
2051  DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2052  bytes_read += curr_bytes_read;
2053  if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2054  break;
2055  }
2056 
2057  // Replace any software breakpoint opcodes that fall into this range back
2058  // into "buf" before we return
2059  if (bytes_read > 0)
2060  RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2061  return bytes_read;
2062 }
2063 
2065  size_t integer_byte_size,
2066  uint64_t fail_value,
2067  Status &error) {
2068  Scalar scalar;
2069  if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2070  error))
2071  return scalar.ULongLong(fail_value);
2072  return fail_value;
2073 }
2074 
2076  size_t integer_byte_size,
2077  int64_t fail_value,
2078  Status &error) {
2079  Scalar scalar;
2080  if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2081  error))
2082  return scalar.SLongLong(fail_value);
2083  return fail_value;
2084 }
2085 
2087  Scalar scalar;
2088  if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2089  error))
2090  return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2091  return LLDB_INVALID_ADDRESS;
2092 }
2093 
2095  Status &error) {
2096  Scalar scalar;
2097  const uint32_t addr_byte_size = GetAddressByteSize();
2098  if (addr_byte_size <= 4)
2099  scalar = (uint32_t)ptr_value;
2100  else
2101  scalar = ptr_value;
2102  return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2103  addr_byte_size;
2104 }
2105 
2106 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2107  Status &error) {
2108  size_t bytes_written = 0;
2109  const uint8_t *bytes = (const uint8_t *)buf;
2110 
2111  while (bytes_written < size) {
2112  const size_t curr_size = size - bytes_written;
2113  const size_t curr_bytes_written = DoWriteMemory(
2114  addr + bytes_written, bytes + bytes_written, curr_size, error);
2115  bytes_written += curr_bytes_written;
2116  if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2117  break;
2118  }
2119  return bytes_written;
2120 }
2121 
2122 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2123  Status &error) {
2124 #if defined(ENABLE_MEMORY_CACHING)
2125  m_memory_cache.Flush(addr, size);
2126 #endif
2127 
2128  if (buf == nullptr || size == 0)
2129  return 0;
2130 
2132 
2133  // We need to write any data that would go where any current software traps
2134  // (enabled software breakpoints) any software traps (breakpoints) that we
2135  // may have placed in our tasks memory.
2136 
2137  BreakpointSiteList bp_sites_in_range;
2138  if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2139  return WriteMemoryPrivate(addr, buf, size, error);
2140 
2141  // No breakpoint sites overlap
2142  if (bp_sites_in_range.IsEmpty())
2143  return WriteMemoryPrivate(addr, buf, size, error);
2144 
2145  const uint8_t *ubuf = (const uint8_t *)buf;
2146  uint64_t bytes_written = 0;
2147 
2148  bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2149  &error](BreakpointSite *bp) -> void {
2150  if (error.Fail())
2151  return;
2152 
2153  if (bp->GetType() != BreakpointSite::eSoftware)
2154  return;
2155 
2156  addr_t intersect_addr;
2157  size_t intersect_size;
2158  size_t opcode_offset;
2159  const bool intersects = bp->IntersectsRange(
2160  addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2161  UNUSED_IF_ASSERT_DISABLED(intersects);
2162  assert(intersects);
2163  assert(addr <= intersect_addr && intersect_addr < addr + size);
2164  assert(addr < intersect_addr + intersect_size &&
2165  intersect_addr + intersect_size <= addr + size);
2166  assert(opcode_offset + intersect_size <= bp->GetByteSize());
2167 
2168  // Check for bytes before this breakpoint
2169  const addr_t curr_addr = addr + bytes_written;
2170  if (intersect_addr > curr_addr) {
2171  // There are some bytes before this breakpoint that we need to just
2172  // write to memory
2173  size_t curr_size = intersect_addr - curr_addr;
2174  size_t curr_bytes_written =
2175  WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2176  bytes_written += curr_bytes_written;
2177  if (curr_bytes_written != curr_size) {
2178  // We weren't able to write all of the requested bytes, we are
2179  // done looping and will return the number of bytes that we have
2180  // written so far.
2181  if (error.Success())
2182  error.SetErrorToGenericError();
2183  }
2184  }
2185  // Now write any bytes that would cover up any software breakpoints
2186  // directly into the breakpoint opcode buffer
2187  ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2188  intersect_size);
2189  bytes_written += intersect_size;
2190  });
2191 
2192  // Write any remaining bytes after the last breakpoint if we have any left
2193  if (bytes_written < size)
2194  bytes_written +=
2195  WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2196  size - bytes_written, error);
2197 
2198  return bytes_written;
2199 }
2200 
2201 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2202  size_t byte_size, Status &error) {
2203  if (byte_size == UINT32_MAX)
2204  byte_size = scalar.GetByteSize();
2205  if (byte_size > 0) {
2206  uint8_t buf[32];
2207  const size_t mem_size =
2208  scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2209  if (mem_size > 0)
2210  return WriteMemory(addr, buf, mem_size, error);
2211  else
2212  error.SetErrorString("failed to get scalar as memory data");
2213  } else {
2214  error.SetErrorString("invalid scalar value");
2215  }
2216  return 0;
2217 }
2218 
2220  bool is_signed, Scalar &scalar,
2221  Status &error) {
2222  uint64_t uval = 0;
2223  if (byte_size == 0) {
2224  error.SetErrorString("byte size is zero");
2225  } else if (byte_size & (byte_size - 1)) {
2226  error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2227  byte_size);
2228  } else if (byte_size <= sizeof(uval)) {
2229  const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2230  if (bytes_read == byte_size) {
2231  DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2232  GetAddressByteSize());
2233  lldb::offset_t offset = 0;
2234  if (byte_size <= 4)
2235  scalar = data.GetMaxU32(&offset, byte_size);
2236  else
2237  scalar = data.GetMaxU64(&offset, byte_size);
2238  if (is_signed)
2239  scalar.SignExtend(byte_size * 8);
2240  return bytes_read;
2241  }
2242  } else {
2243  error.SetErrorStringWithFormat(
2244  "byte size of %u is too large for integer scalar type", byte_size);
2245  }
2246  return 0;
2247 }
2248 
2249 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2250  Status error;
2251  for (const auto &Entry : entries) {
2252  WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2253  error);
2254  if (!error.Success())
2255  break;
2256  }
2257  return error;
2258 }
2259 
2260 #define USE_ALLOCATE_MEMORY_CACHE 1
2261 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2262  Status &error) {
2263  if (GetPrivateState() != eStateStopped) {
2264  error.SetErrorToGenericError();
2265  return LLDB_INVALID_ADDRESS;
2266  }
2267 
2268 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2269  return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2270 #else
2271  addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2273  LLDB_LOGF(log,
2274  "Process::AllocateMemory(size=%" PRIu64
2275  ", permissions=%s) => 0x%16.16" PRIx64
2276  " (m_stop_id = %u m_memory_id = %u)",
2277  (uint64_t)size, GetPermissionsAsCString(permissions),
2278  (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2279  m_mod_id.GetMemoryID());
2280  return allocated_addr;
2281 #endif
2282 }
2283 
2284 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2285  Status &error) {
2286  addr_t return_addr = AllocateMemory(size, permissions, error);
2287  if (error.Success()) {
2288  std::string buffer(size, 0);
2289  WriteMemory(return_addr, buffer.c_str(), size, error);
2290  }
2291  return return_addr;
2292 }
2293 
2295  if (m_can_jit == eCanJITDontKnow) {
2297  Status err;
2298 
2299  uint64_t allocated_memory = AllocateMemory(
2300  8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2301  err);
2302 
2303  if (err.Success()) {
2305  LLDB_LOGF(log,
2306  "Process::%s pid %" PRIu64
2307  " allocation test passed, CanJIT () is true",
2308  __FUNCTION__, GetID());
2309  } else {
2310  m_can_jit = eCanJITNo;
2311  LLDB_LOGF(log,
2312  "Process::%s pid %" PRIu64
2313  " allocation test failed, CanJIT () is false: %s",
2314  __FUNCTION__, GetID(), err.AsCString());
2315  }
2316 
2317  DeallocateMemory(allocated_memory);
2318  }
2319 
2320  return m_can_jit == eCanJITYes;
2321 }
2322 
2323 void Process::SetCanJIT(bool can_jit) {
2324  m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2325 }
2326 
2327 void Process::SetCanRunCode(bool can_run_code) {
2328  SetCanJIT(can_run_code);
2329  m_can_interpret_function_calls = can_run_code;
2330 }
2331 
2333  Status error;
2334 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2336  error.SetErrorStringWithFormat(
2337  "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2338  }
2339 #else
2340  error = DoDeallocateMemory(ptr);
2341 
2343  LLDB_LOGF(log,
2344  "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2345  ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2346  ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2347  m_mod_id.GetMemoryID());
2348 #endif
2349  return error;
2350 }
2351 
2352 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2353  lldb::addr_t header_addr,
2354  size_t size_to_read) {
2356  if (log) {
2357  LLDB_LOGF(log,
2358  "Process::ReadModuleFromMemory reading %s binary from memory",
2359  file_spec.GetPath().c_str());
2360  }
2361  ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2362  if (module_sp) {
2363  Status error;
2364  ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2365  shared_from_this(), header_addr, error, size_to_read);
2366  if (objfile)
2367  return module_sp;
2368  }
2369  return ModuleSP();
2370 }
2371 
2373  uint32_t &permissions) {
2374  MemoryRegionInfo range_info;
2375  permissions = 0;
2376  Status error(GetMemoryRegionInfo(load_addr, range_info));
2377  if (!error.Success())
2378  return false;
2379  if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2380  range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2381  range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2382  return false;
2383  }
2384 
2385  if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2386  permissions |= lldb::ePermissionsReadable;
2387 
2388  if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2389  permissions |= lldb::ePermissionsWritable;
2390 
2391  if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2392  permissions |= lldb::ePermissionsExecutable;
2393 
2394  return true;
2395 }
2396 
2397 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2398  Status error;
2399  error.SetErrorString("watchpoints are not supported");
2400  return error;
2401 }
2402 
2403 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2404  Status error;
2405  error.SetErrorString("watchpoints are not supported");
2406  return error;
2407 }
2408 
2409 StateType
2411  const Timeout<std::micro> &timeout) {
2412  StateType state;
2413 
2414  while (true) {
2415  event_sp.reset();
2416  state = GetStateChangedEventsPrivate(event_sp, timeout);
2417 
2418  if (StateIsStoppedState(state, false))
2419  break;
2420 
2421  // If state is invalid, then we timed out
2422  if (state == eStateInvalid)
2423  break;
2424 
2425  if (event_sp)
2426  HandlePrivateEvent(event_sp);
2427  }
2428  return state;
2429 }
2430 
2432  if (flush)
2433  m_thread_list.Clear();
2434  m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2435  if (flush)
2436  Flush();
2437 }
2438 
2440  Status error;
2441  m_abi_sp.reset();
2442  m_dyld_up.reset();
2443  m_jit_loaders_up.reset();
2444  m_system_runtime_up.reset();
2445  m_os_up.reset();
2446  m_process_input_reader.reset();
2447 
2448  Module *exe_module = GetTarget().GetExecutableModulePointer();
2449  if (!exe_module) {
2450  error.SetErrorString("executable module does not exist");
2451  return error;
2452  }
2453 
2454  char local_exec_file_path[PATH_MAX];
2455  char platform_exec_file_path[PATH_MAX];
2456  exe_module->GetFileSpec().GetPath(local_exec_file_path,
2457  sizeof(local_exec_file_path));
2458  exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2459  sizeof(platform_exec_file_path));
2460  if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2461  // Install anything that might need to be installed prior to launching.
2462  // For host systems, this will do nothing, but if we are connected to a
2463  // remote platform it will install any needed binaries
2464  error = GetTarget().Install(&launch_info);
2465  if (error.Fail())
2466  return error;
2467 
2468  // Listen and queue events that are broadcasted during the process launch.
2469  ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2470  HijackProcessEvents(listener_sp);
2471  auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2472 
2475 
2476  error = WillLaunch(exe_module);
2477  if (error.Success()) {
2478  const bool restarted = false;
2479  SetPublicState(eStateLaunching, restarted);
2480  m_should_detach = false;
2481 
2483  // Now launch using these arguments.
2484  error = DoLaunch(exe_module, launch_info);
2485  } else {
2486  // This shouldn't happen
2487  error.SetErrorString("failed to acquire process run lock");
2488  }
2489 
2490  if (error.Fail()) {
2491  if (GetID() != LLDB_INVALID_PROCESS_ID) {
2493  const char *error_string = error.AsCString();
2494  if (error_string == nullptr)
2495  error_string = "launch failed";
2496  SetExitStatus(-1, error_string);
2497  }
2498  } else {
2499  EventSP event_sp;
2500 
2501  // Now wait for the process to launch and return control to us, and then
2502  // call DidLaunch:
2503  StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2504 
2505  if (state == eStateInvalid || !event_sp) {
2506  // We were able to launch the process, but we failed to catch the
2507  // initial stop.
2508  error.SetErrorString("failed to catch stop after launch");
2509  SetExitStatus(0, "failed to catch stop after launch");
2510  Destroy(false);
2511  } else if (state == eStateStopped || state == eStateCrashed) {
2512  DidLaunch();
2513 
2514  DynamicLoader *dyld = GetDynamicLoader();
2515  if (dyld)
2516  dyld->DidLaunch();
2517 
2519 
2520  SystemRuntime *system_runtime = GetSystemRuntime();
2521  if (system_runtime)
2522  system_runtime->DidLaunch();
2523 
2524  if (!m_os_up)
2526 
2527  // We successfully launched the process and stopped, now it the
2528  // right time to set up signal filters before resuming.
2530 
2531  // Note, the stop event was consumed above, but not handled. This
2532  // was done to give DidLaunch a chance to run. The target is either
2533  // stopped or crashed. Directly set the state. This is done to
2534  // prevent a stop message with a bunch of spurious output on thread
2535  // status, as well as not pop a ProcessIOHandler.
2536  SetPublicState(state, false);
2537 
2540  else
2542 
2543  // Target was stopped at entry as was intended. Need to notify the
2544  // listeners about it.
2545  if (state == eStateStopped &&
2546  launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2547  HandlePrivateEvent(event_sp);
2548  } else if (state == eStateExited) {
2549  // We exited while trying to launch somehow. Don't call DidLaunch
2550  // as that's not likely to work, and return an invalid pid.
2551  HandlePrivateEvent(event_sp);
2552  }
2553  }
2554  }
2555  } else {
2556  error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2557  local_exec_file_path);
2558  }
2559 
2560  return error;
2561 }
2562 
2564  Status error = DoLoadCore();
2565  if (error.Success()) {
2566  ListenerSP listener_sp(
2567  Listener::MakeListener("lldb.process.load_core_listener"));
2568  HijackProcessEvents(listener_sp);
2569 
2572  else
2574 
2575  DynamicLoader *dyld = GetDynamicLoader();
2576  if (dyld)
2577  dyld->DidAttach();
2578 
2580 
2581  SystemRuntime *system_runtime = GetSystemRuntime();
2582  if (system_runtime)
2583  system_runtime->DidAttach();
2584 
2585  if (!m_os_up)
2587 
2588  // We successfully loaded a core file, now pretend we stopped so we can
2589  // show all of the threads in the core file and explore the crashed state.
2591 
2592  // Wait for a stopped event since we just posted one above...
2593  lldb::EventSP event_sp;
2594  StateType state =
2595  WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
2596 
2597  if (!StateIsStoppedState(state, false)) {
2599  LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2600  StateAsCString(state));
2601  error.SetErrorString(
2602  "Did not get stopped event after loading the core file.");
2603  }
2605  }
2606  return error;
2607 }
2608 
2610  if (!m_dyld_up)
2611  m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2612  return m_dyld_up.get();
2613 }
2614 
2616 
2618  if (!m_jit_loaders_up) {
2619  m_jit_loaders_up = std::make_unique<JITLoaderList>();
2621  }
2622  return *m_jit_loaders_up;
2623 }
2624 
2626  if (!m_system_runtime_up)
2628  return m_system_runtime_up.get();
2629 }
2630 
2632  uint32_t exec_count)
2633  : NextEventAction(process), m_exec_count(exec_count) {
2635  LLDB_LOGF(
2636  log,
2637  "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2638  __FUNCTION__, static_cast<void *>(process), exec_count);
2639 }
2640 
2644 
2645  StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2646  LLDB_LOGF(log,
2647  "Process::AttachCompletionHandler::%s called with state %s (%d)",
2648  __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2649 
2650  switch (state) {
2651  case eStateAttaching:
2652  return eEventActionSuccess;
2653 
2654  case eStateRunning:
2655  case eStateConnected:
2656  return eEventActionRetry;
2657 
2658  case eStateStopped:
2659  case eStateCrashed:
2660  // During attach, prior to sending the eStateStopped event,
2661  // lldb_private::Process subclasses must set the new process ID.
2662  assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2663  // We don't want these events to be reported, so go set the
2664  // ShouldReportStop here:
2666 
2667  if (m_exec_count > 0) {
2668  --m_exec_count;
2669 
2670  LLDB_LOGF(log,
2671  "Process::AttachCompletionHandler::%s state %s: reduced "
2672  "remaining exec count to %" PRIu32 ", requesting resume",
2673  __FUNCTION__, StateAsCString(state), m_exec_count);
2674 
2675  RequestResume();
2676  return eEventActionRetry;
2677  } else {
2678  LLDB_LOGF(log,
2679  "Process::AttachCompletionHandler::%s state %s: no more "
2680  "execs expected to start, continuing with attach",
2681  __FUNCTION__, StateAsCString(state));
2682 
2684  return eEventActionSuccess;
2685  }
2686  break;
2687 
2688  default:
2689  case eStateExited:
2690  case eStateInvalid:
2691  break;
2692  }
2693 
2694  m_exit_string.assign("No valid Process");
2695  return eEventActionExit;
2696 }
2697 
2700  return eEventActionSuccess;
2701 }
2702 
2704  return m_exit_string.c_str();
2705 }
2706 
2708  if (m_listener_sp)
2709  return m_listener_sp;
2710  else
2711  return debugger.GetListener();
2712 }
2713 
2715  m_abi_sp.reset();
2716  m_process_input_reader.reset();
2717  m_dyld_up.reset();
2718  m_jit_loaders_up.reset();
2719  m_system_runtime_up.reset();
2720  m_os_up.reset();
2721 
2722  lldb::pid_t attach_pid = attach_info.GetProcessID();
2723  Status error;
2724  if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2725  char process_name[PATH_MAX];
2726 
2727  if (attach_info.GetExecutableFile().GetPath(process_name,
2728  sizeof(process_name))) {
2729  const bool wait_for_launch = attach_info.GetWaitForLaunch();
2730 
2731  if (wait_for_launch) {
2732  error = WillAttachToProcessWithName(process_name, wait_for_launch);
2733  if (error.Success()) {
2735  m_should_detach = true;
2736  const bool restarted = false;
2737  SetPublicState(eStateAttaching, restarted);
2738  // Now attach using these arguments.
2739  error = DoAttachToProcessWithName(process_name, attach_info);
2740  } else {
2741  // This shouldn't happen
2742  error.SetErrorString("failed to acquire process run lock");
2743  }
2744 
2745  if (error.Fail()) {
2746  if (GetID() != LLDB_INVALID_PROCESS_ID) {
2748  if (error.AsCString() == nullptr)
2749  error.SetErrorString("attach failed");
2750 
2751  SetExitStatus(-1, error.AsCString());
2752  }
2753  } else {
2755  this, attach_info.GetResumeCount()));
2757  }
2758  return error;
2759  }
2760  } else {
2761  ProcessInstanceInfoList process_infos;
2762  PlatformSP platform_sp(GetTarget().GetPlatform());
2763 
2764  if (platform_sp) {
2765  ProcessInstanceInfoMatch match_info;
2766  match_info.GetProcessInfo() = attach_info;
2767  match_info.SetNameMatchType(NameMatch::Equals);
2768  platform_sp->FindProcesses(match_info, process_infos);
2769  const uint32_t num_matches = process_infos.size();
2770  if (num_matches == 1) {
2771  attach_pid = process_infos[0].GetProcessID();
2772  // Fall through and attach using the above process ID
2773  } else {
2774  match_info.GetProcessInfo().GetExecutableFile().GetPath(
2775  process_name, sizeof(process_name));
2776  if (num_matches > 1) {
2777  StreamString s;
2778  ProcessInstanceInfo::DumpTableHeader(s, true, false);
2779  for (size_t i = 0; i < num_matches; i++) {
2780  process_infos[i].DumpAsTableRow(
2781  s, platform_sp->GetUserIDResolver(), true, false);
2782  }
2783  error.SetErrorStringWithFormat(
2784  "more than one process named %s:\n%s", process_name,
2785  s.GetData());
2786  } else
2787  error.SetErrorStringWithFormat(
2788  "could not find a process named %s", process_name);
2789  }
2790  } else {
2791  error.SetErrorString(
2792  "invalid platform, can't find processes by name");
2793  return error;
2794  }
2795  }
2796  } else {
2797  error.SetErrorString("invalid process name");
2798  }
2799  }
2800 
2801  if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2802  error = WillAttachToProcessWithID(attach_pid);
2803  if (error.Success()) {
2804 
2806  // Now attach using these arguments.
2807  m_should_detach = true;
2808  const bool restarted = false;
2809  SetPublicState(eStateAttaching, restarted);
2810  error = DoAttachToProcessWithID(attach_pid, attach_info);
2811  } else {
2812  // This shouldn't happen
2813  error.SetErrorString("failed to acquire process run lock");
2814  }
2815 
2816  if (error.Success()) {
2818  this, attach_info.GetResumeCount()));
2820  } else {
2821  if (GetID() != LLDB_INVALID_PROCESS_ID)
2823 
2824  const char *error_string = error.AsCString();
2825  if (error_string == nullptr)
2826  error_string = "attach failed";
2827 
2828  SetExitStatus(-1, error_string);
2829  }
2830  }
2831  }
2832  return error;
2833 }
2834 
2838  LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
2839 
2840  // Let the process subclass figure out at much as it can about the process
2841  // before we go looking for a dynamic loader plug-in.
2842  ArchSpec process_arch;
2843  DidAttach(process_arch);
2844 
2845  if (process_arch.IsValid()) {
2846  GetTarget().SetArchitecture(process_arch);
2847  if (log) {
2848  const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2849  LLDB_LOGF(log,
2850  "Process::%s replacing process architecture with DidAttach() "
2851  "architecture: %s",
2852  __FUNCTION__, triple_str ? triple_str : "<null>");
2853  }
2854  }
2855 
2856  // We just attached. If we have a platform, ask it for the process
2857  // architecture, and if it isn't the same as the one we've already set,
2858  // switch architectures.
2859  PlatformSP platform_sp(GetTarget().GetPlatform());
2860  assert(platform_sp);
2861  if (platform_sp) {
2862  const ArchSpec &target_arch = GetTarget().GetArchitecture();
2863  if (target_arch.IsValid() &&
2864  !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2865  ArchSpec platform_arch;
2866  platform_sp =
2867  platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2868  if (platform_sp) {
2869  GetTarget().SetPlatform(platform_sp);
2870  GetTarget().SetArchitecture(platform_arch);
2871  LLDB_LOGF(log,
2872  "Process::%s switching platform to %s and architecture "
2873  "to %s based on info from attach",
2874  __FUNCTION__, platform_sp->GetName().AsCString(""),
2875  platform_arch.GetTriple().getTriple().c_str());
2876  }
2877  } else if (!process_arch.IsValid()) {
2878  ProcessInstanceInfo process_info;
2879  GetProcessInfo(process_info);
2880  const ArchSpec &process_arch = process_info.GetArchitecture();
2881  const ArchSpec &target_arch = GetTarget().GetArchitecture();
2882  if (process_arch.IsValid() &&
2883  target_arch.IsCompatibleMatch(process_arch) &&
2884  !target_arch.IsExactMatch(process_arch)) {
2885  GetTarget().SetArchitecture(process_arch);
2886  LLDB_LOGF(log,
2887  "Process::%s switching architecture to %s based on info "
2888  "the platform retrieved for pid %" PRIu64,
2889  __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2890  GetID());
2891  }
2892  }
2893  }
2894 
2895  // We have completed the attach, now it is time to find the dynamic loader
2896  // plug-in
2897  DynamicLoader *dyld = GetDynamicLoader();
2898  if (dyld) {
2899  dyld->DidAttach();
2900  if (log) {
2901  ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2902  LLDB_LOGF(log,
2903  "Process::%s after DynamicLoader::DidAttach(), target "
2904  "executable is %s (using %s plugin)",
2905  __FUNCTION__,
2906  exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2907  : "<none>",
2908  dyld->GetPluginName().AsCString("<unnamed>"));
2909  }
2910  }
2911 
2913 
2914  SystemRuntime *system_runtime = GetSystemRuntime();
2915  if (system_runtime) {
2916  system_runtime->DidAttach();
2917  if (log) {
2918  ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2919  LLDB_LOGF(log,
2920  "Process::%s after SystemRuntime::DidAttach(), target "
2921  "executable is %s (using %s plugin)",
2922  __FUNCTION__,
2923  exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2924  : "<none>",
2925  system_runtime->GetPluginName().AsCString("<unnamed>"));
2926  }
2927  }
2928 
2929  if (!m_os_up) {
2931  if (m_os_up) {
2932  // Somebody might have gotten threads before now, but we need to force the
2933  // update after we've loaded the OperatingSystem plugin or it won't get a
2934  // chance to process the threads.
2935  m_thread_list.Clear();
2937  }
2938  }
2939  // Figure out which one is the executable, and set that in our target:
2940  ModuleSP new_executable_module_sp;
2941  for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
2942  if (module_sp && module_sp->IsExecutable()) {
2943  if (GetTarget().GetExecutableModulePointer() != module_sp.get())
2944  new_executable_module_sp = module_sp;
2945  break;
2946  }
2947  }
2948  if (new_executable_module_sp) {
2949  GetTarget().SetExecutableModule(new_executable_module_sp,
2951  if (log) {
2952  ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2953  LLDB_LOGF(
2954  log,
2955  "Process::%s after looping through modules, target executable is %s",
2956  __FUNCTION__,
2957  exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2958  : "<none>");
2959  }
2960  }
2961 }
2962 
2963 Status Process::ConnectRemote(llvm::StringRef remote_url) {
2964  m_abi_sp.reset();
2965  m_process_input_reader.reset();
2966 
2967  // Find the process and its architecture. Make sure it matches the
2968  // architecture of the current Target, and if not adjust it.
2969 
2970  Status error(DoConnectRemote(remote_url));
2971  if (error.Success()) {
2972  if (GetID() != LLDB_INVALID_PROCESS_ID) {
2973  EventSP event_sp;
2974  StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
2975 
2976  if (state == eStateStopped || state == eStateCrashed) {
2977  // If we attached and actually have a process on the other end, then
2978  // this ended up being the equivalent of an attach.
2979  CompleteAttach();
2980 
2981  // This delays passing the stopped event to listeners till
2982  // CompleteAttach gets a chance to complete...
2983  HandlePrivateEvent(event_sp);
2984  }
2985  }
2986 
2989  else
2991  }
2992  return error;
2993 }
2994 
2997  LIBLLDB_LOG_STEP));
2998  LLDB_LOGF(log,
2999  "Process::PrivateResume() m_stop_id = %u, public state: %s "
3000  "private state: %s",
3003 
3004  // If signals handing status changed we might want to update our signal
3005  // filters before resuming.
3007 
3008  Status error(WillResume());
3009  // Tell the process it is about to resume before the thread list
3010  if (error.Success()) {
3011  // Now let the thread list know we are about to resume so it can let all of
3012  // our threads know that they are about to be resumed. Threads will each be
3013  // called with Thread::WillResume(StateType) where StateType contains the
3014  // state that they are supposed to have when the process is resumed
3015  // (suspended/running/stepping). Threads should also check their resume
3016  // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3017  // start back up with a signal.
3018  if (m_thread_list.WillResume()) {
3019  // Last thing, do the PreResumeActions.
3020  if (!RunPreResumeActions()) {
3021  error.SetErrorString(
3022  "Process::PrivateResume PreResumeActions failed, not resuming.");
3023  } else {
3025  error = DoResume();
3026  if (error.Success()) {
3027  DidResume();
3029  LLDB_LOGF(log, "Process thinks the process has resumed.");
3030  } else {
3031  LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3032  return error;
3033  }
3034  }
3035  } else {
3036  // Somebody wanted to run without running (e.g. we were faking a step
3037  // from one frame of a set of inlined frames that share the same PC to
3038  // another.) So generate a continue & a stopped event, and let the world
3039  // handle them.
3040  LLDB_LOGF(log,
3041  "Process::PrivateResume() asked to simulate a start & stop.");
3042 
3045  }
3046  } else
3047  LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3048  error.AsCString("<unknown error>"));
3049  return error;
3050 }
3051 
3052 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3054  return Status("Process is not running.");
3055 
3056  // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3057  // case it was already set and some thread plan logic calls halt on its own.
3058  m_clear_thread_plans_on_stop |= clear_thread_plans;
3059 
3060  ListenerSP halt_listener_sp(
3061  Listener::MakeListener("lldb.process.halt_listener"));
3062  HijackProcessEvents(halt_listener_sp);
3063 
3064  EventSP event_sp;
3065 
3067 
3069  // Don't hijack and eat the eStateExited as the code that was doing the
3070  // attach will be waiting for this event...
3072  SetExitStatus(SIGKILL, "Cancelled async attach.");
3073  Destroy(false);
3074  return Status();
3075  }
3076 
3077  // Wait for the process halt timeout seconds for the process to stop.
3078  StateType state =
3079  WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3080  halt_listener_sp, nullptr, use_run_lock);
3082 
3083  if (state == eStateInvalid || !event_sp) {
3084  // We timed out and didn't get a stop event...
3085  return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3086  }
3087 
3088  BroadcastEvent(event_sp);
3089 
3090  return Status();
3091 }
3092 
3093 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3094  Status error;
3095 
3096  // Check both the public & private states here. If we're hung evaluating an
3097  // expression, for instance, then the public state will be stopped, but we
3098  // still need to interrupt.
3102  LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3103 
3104  ListenerSP listener_sp(
3105  Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3106  HijackProcessEvents(listener_sp);
3107 
3109 
3110  // Consume the interrupt event.
3112  &exit_event_sp, true, listener_sp);
3113 
3115 
3116  // If the process exited while we were waiting for it to stop, put the
3117  // exited event into the shared pointer passed in and return. Our caller
3118  // doesn't need to do anything else, since they don't have a process
3119  // anymore...
3120 
3121  if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3122  LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3123  __FUNCTION__);
3124  return error;
3125  } else
3126  exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3127 
3128  if (state != eStateStopped) {
3129  LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3130  StateAsCString(state));
3131  // If we really couldn't stop the process then we should just error out
3132  // here, but if the lower levels just bobbled sending the event and we
3133  // really are stopped, then continue on.
3134  StateType private_state = m_private_state.GetValue();
3135  if (private_state != eStateStopped) {
3136  return Status(
3137  "Attempt to stop the target in order to detach timed out. "
3138  "State = %s",
3140  }
3141  }
3142  }
3143  return error;
3144 }
3145 
3146 Status Process::Detach(bool keep_stopped) {
3147  EventSP exit_event_sp;
3148  Status error;
3149  m_destroy_in_process = true;
3150 
3151  error = WillDetach();
3152 
3153  if (error.Success()) {
3154  if (DetachRequiresHalt()) {
3155  error = StopForDestroyOrDetach(exit_event_sp);
3156  if (!error.Success()) {
3157  m_destroy_in_process = false;
3158  return error;
3159  } else if (exit_event_sp) {
3160  // We shouldn't need to do anything else here. There's no process left
3161  // to detach from...
3163  m_destroy_in_process = false;
3164  return error;
3165  }
3166  }
3167 
3170 
3171  error = DoDetach(keep_stopped);
3172  if (error.Success()) {
3173  DidDetach();
3175  } else {
3176  return error;
3177  }
3178  }
3179  m_destroy_in_process = false;
3180 
3181  // If we exited when we were waiting for a process to stop, then forward the
3182  // event here so we don't lose the event
3183  if (exit_event_sp) {
3184  // Directly broadcast our exited event because we shut down our private
3185  // state thread above
3186  BroadcastEvent(exit_event_sp);
3187  }
3188 
3189  // If we have been interrupted (to kill us) in the middle of running, we may
3190  // not end up propagating the last events through the event system, in which
3191  // case we might strand the write lock. Unlock it here so when we do to tear
3192  // down the process we don't get an error destroying the lock.
3193 
3195  return error;
3196 }
3197 
3198 Status Process::Destroy(bool force_kill) {
3199  // If we've already called Process::Finalize then there's nothing useful to
3200  // be done here. Finalize has actually called Destroy already.
3201  if (m_finalizing)
3202  return {};
3203  return DestroyImpl(force_kill);
3204 }
3205 
3206 Status Process::DestroyImpl(bool force_kill) {
3207  // Tell ourselves we are in the process of destroying the process, so that we
3208  // don't do any unnecessary work that might hinder the destruction. Remember
3209  // to set this back to false when we are done. That way if the attempt
3210  // failed and the process stays around for some reason it won't be in a
3211  // confused state.
3212 
3213  if (force_kill)
3214  m_should_detach = false;
3215 
3216  if (GetShouldDetach()) {
3217  // FIXME: This will have to be a process setting:
3218  bool keep_stopped = false;
3219  Detach(keep_stopped);
3220  }
3221 
3222  m_destroy_in_process = true;
3223 
3225  if (error.Success()) {
3226  EventSP exit_event_sp;
3227  if (DestroyRequiresHalt()) {
3228  error = StopForDestroyOrDetach(exit_event_sp);
3229  }
3230 
3232  // Ditch all thread plans, and remove all our breakpoints: in case we
3233  // have to restart the target to kill it, we don't want it hitting a
3234  // breakpoint... Only do this if we've stopped, however, since if we
3235  // didn't manage to halt it above, then we're not going to have much luck
3236  // doing this now.
3239  }
3240 
3241  error = DoDestroy();
3242  if (error.Success()) {
3243  DidDestroy();
3245  }
3248  m_stdin_forward = false;
3249 
3250  if (m_process_input_reader) {
3251  m_process_input_reader->SetIsDone(true);
3252  m_process_input_reader->Cancel();
3253  m_process_input_reader.reset();
3254  }
3255 
3256  // If we exited when we were waiting for a process to stop, then forward
3257  // the event here so we don't lose the event
3258  if (exit_event_sp) {
3259  // Directly broadcast our exited event because we shut down our private
3260  // state thread above
3261  BroadcastEvent(exit_event_sp);
3262  }
3263 
3264  // If we have been interrupted (to kill us) in the middle of running, we
3265  // may not end up propagating the last events through the event system, in
3266  // which case we might strand the write lock. Unlock it here so when we do
3267  // to tear down the process we don't get an error destroying the lock.
3269  }
3270 
3271  m_destroy_in_process = false;
3272 
3273  return error;
3274 }
3275 
3277  Status error(WillSignal());
3278  if (error.Success()) {
3279  error = DoSignal(signal);
3280  if (error.Success())
3281  DidSignal();
3282  }
3283  return error;
3284 }
3285 
3286 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3287  assert(signals_sp && "null signals_sp");
3288  m_unix_signals_sp = signals_sp;
3289 }
3290 
3291 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3292  assert(m_unix_signals_sp && "null m_unix_signals_sp");
3293  return m_unix_signals_sp;
3294 }
3295 
3297  return GetTarget().GetArchitecture().GetByteOrder();
3298 }
3299 
3302 }
3303 
3305  const StateType state =
3307  bool return_value = true;
3310 
3311  switch (state) {
3312  case eStateDetached:
3313  case eStateExited:
3314  case eStateUnloaded:
3318  m_stdin_forward = false;
3319 
3320  LLVM_FALLTHROUGH;
3321  case eStateConnected:
3322  case eStateAttaching:
3323  case eStateLaunching:
3324  // These events indicate changes in the state of the debugging session,
3325  // always report them.
3326  return_value = true;
3327  break;
3328  case eStateInvalid:
3329  // We stopped for no apparent reason, don't report it.
3330  return_value = false;
3331  break;
3332  case eStateRunning:
3333  case eStateStepping:
3334  // If we've started the target running, we handle the cases where we are
3335  // already running and where there is a transition from stopped to running
3336  // differently. running -> running: Automatically suppress extra running
3337  // events stopped -> running: Report except when there is one or more no
3338  // votes
3339  // and no yes votes.
3342  return_value = true;
3343  else {
3344  switch (m_last_broadcast_state) {
3345  case eStateRunning:
3346  case eStateStepping:
3347  // We always suppress multiple runnings with no PUBLIC stop in between.
3348  return_value = false;
3349  break;
3350  default:
3351  // TODO: make this work correctly. For now always report
3352  // run if we aren't running so we don't miss any running events. If I
3353  // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3354  // and hit the breakpoints on multiple threads, then somehow during the
3355  // stepping over of all breakpoints no run gets reported.
3356 
3357  // This is a transition from stop to run.
3358  switch (m_thread_list.ShouldReportRun(event_ptr)) {
3359  case eVoteYes:
3360  case eVoteNoOpinion:
3361  return_value = true;
3362  break;
3363  case eVoteNo:
3364  return_value = false;
3365  break;
3366  }
3367  break;
3368  }
3369  }
3370  break;
3371  case eStateStopped:
3372  case eStateCrashed:
3373  case eStateSuspended:
3374  // We've stopped. First see if we're going to restart the target. If we
3375  // are going to stop, then we always broadcast the event. If we aren't
3376  // going to stop, let the thread plans decide if we're going to report this
3377  // event. If no thread has an opinion, we don't report it.
3378 
3382  LLDB_LOGF(log,
3383  "Process::ShouldBroadcastEvent (%p) stopped due to an "
3384  "interrupt, state: %s",
3385  static_cast<void *>(event_ptr), StateAsCString(state));
3386  // Even though we know we are going to stop, we should let the threads
3387  // have a look at the stop, so they can properly set their state.
3388  m_thread_list.ShouldStop(event_ptr);
3389  return_value = true;
3390  } else {
3391  bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3392  bool should_resume = false;
3393 
3394  // It makes no sense to ask "ShouldStop" if we've already been
3395  // restarted... Asking the thread list is also not likely to go well,
3396  // since we are running again. So in that case just report the event.
3397 
3398  if (!was_restarted)
3399  should_resume = !m_thread_list.ShouldStop(event_ptr);
3400 
3401  if (was_restarted || should_resume || m_resume_requested) {
3402  Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3403  LLDB_LOGF(log,
3404  "Process::ShouldBroadcastEvent: should_resume: %i state: "
3405  "%s was_restarted: %i report_stop_vote: %d.",
3406  should_resume, StateAsCString(state), was_restarted,
3407  report_stop_vote);
3408 
3409  switch (report_stop_vote) {
3410  case eVoteYes:
3411  return_value = true;
3412  break;
3413  case eVoteNoOpinion:
3414  case eVoteNo:
3415  return_value = false;
3416  break;
3417  }
3418 
3419  if (!was_restarted) {
3420  LLDB_LOGF(log,
3421  "Process::ShouldBroadcastEvent (%p) Restarting process "
3422  "from state: %s",
3423  static_cast<void *>(event_ptr), StateAsCString(state));
3424  ProcessEventData::SetRestartedInEvent(event_ptr, true);
3425  PrivateResume();
3426  }
3427  } else {
3428  return_value = true;
3430  }
3431  }
3432  break;
3433  }
3434 
3435  // Forcing the next event delivery is a one shot deal. So reset it here.
3437 
3438  // We do some coalescing of events (for instance two consecutive running
3439  // events get coalesced.) But we only coalesce against events we actually
3440  // broadcast. So we use m_last_broadcast_state to track that. NB - you
3441  // can't use "m_public_state.GetValue()" for that purpose, as was originally
3442  // done, because the PublicState reflects the last event pulled off the
3443  // queue, and there may be several events stacked up on the queue unserviced.
3444  // So the PublicState may not reflect the last broadcasted event yet.
3445  // m_last_broadcast_state gets updated here.
3446 
3447  if (return_value)
3448  m_last_broadcast_state = state;
3449 
3450  LLDB_LOGF(log,
3451  "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3452  "broadcast state: %s - %s",
3453  static_cast<void *>(event_ptr), StateAsCString(state),
3455  return_value ? "YES" : "NO");
3456  return return_value;
3457 }
3458 
3459 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3461 
3462  bool already_running = PrivateStateThreadIsValid();
3463  LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3464  already_running ? " already running"
3465  : " starting private state thread");
3466 
3467  if (!is_secondary_thread && already_running)
3468  return true;
3469 
3470  // Create a thread that watches our internal state and controls which events
3471  // make it to clients (into the DCProcess event queue).
3472  char thread_name[1024];
3473  uint32_t max_len = llvm::get_max_thread_name_length();
3474  if (max_len > 0 && max_len <= 30) {
3475  // On platforms with abbreviated thread name lengths, choose thread names
3476  // that fit within the limit.
3477  if (already_running)
3478  snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3479  else
3480  snprintf(thread_name, sizeof(thread_name), "intern-state");
3481  } else {
3482  if (already_running)
3483  snprintf(thread_name, sizeof(thread_name),
3484  "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3485  GetID());
3486  else
3487  snprintf(thread_name, sizeof(thread_name),
3488  "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3489  }
3490 
3491  // Create the private state thread, and start it running.
3492  PrivateStateThreadArgs *args_ptr =
3493  new PrivateStateThreadArgs(this, is_secondary_thread);
3494  llvm::Expected<HostThread> private_state_thread =
3496  (void *)args_ptr, 8 * 1024 * 1024);
3497  if (!private_state_thread) {
3499  "failed to launch host thread: {}",
3500  llvm::toString(private_state_thread.takeError()));
3501  return false;
3502  }
3503 
3504  assert(private_state_thread->IsJoinable());
3505  m_private_state_thread = *private_state_thread;
3507  return true;
3508 }
3509 
3512 }
3513 
3516 }
3517 
3521  else {
3523  LLDB_LOGF(
3524  log,
3525  "Went to stop the private state thread, but it was already invalid.");
3526  }
3527 }
3528 
3531 
3532  assert(signal == eBroadcastInternalStateControlStop ||
3535 
3536  LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
3537 
3538  // Signal the private state thread
3540  // Broadcast the event.
3541  // It is important to do this outside of the if below, because it's
3542  // possible that the thread state is invalid but that the thread is waiting
3543  // on a control event instead of simply being on its way out (this should
3544  // not happen, but it apparently can).
3545  LLDB_LOGF(log, "Sending control event of type: %d.", signal);
3546  std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3548  event_receipt_sp);
3549 
3550  // Wait for the event receipt or for the private state thread to exit
3551  bool receipt_received = false;
3552  if (PrivateStateThreadIsValid()) {
3553  while (!receipt_received) {
3554  // Check for a receipt for n seconds and then check if the private
3555  // state thread is still around.
3556  receipt_received =
3557  event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
3558  if (!receipt_received) {
3559  // Check if the private state thread is still around. If it isn't
3560  // then we are done waiting
3562  break; // Private state thread exited or is exiting, we are done
3563  }
3564  }
3565  }
3566 
3567  if (signal == eBroadcastInternalStateControlStop) {
3568  thread_result_t result = {};
3569  m_private_state_thread.Join(&result);
3571  }
3572  } else {
3573  LLDB_LOGF(
3574  log,
3575  "Private state thread already dead, no need to signal it to stop.");
3576  }
3577 }
3578 
3582  nullptr);
3583  else
3585 }
3586 
3587 void Process::HandlePrivateEvent(EventSP &event_sp) {
3589  m_resume_requested = false;
3590 
3591  const StateType new_state =
3593 
3594  // First check to see if anybody wants a shot at this event:
3595  if (m_next_event_action_up) {
3596  NextEventAction::EventActionResult action_result =
3597  m_next_event_action_up->PerformAction(event_sp);
3598  LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
3599 
3600  switch (action_result) {
3602  SetNextEventAction(nullptr);
3603  break;
3604 
3606  break;
3607 
3609  // Handle Exiting Here. If we already got an exited event, we should
3610  // just propagate it. Otherwise, swallow this event, and set our state
3611  // to exit so the next event will kill us.
3612  if (new_state != eStateExited) {
3613  // FIXME: should cons up an exited event, and discard this one.
3614  SetExitStatus(0, m_next_event_action_up->GetExitString());
3615  SetNextEventAction(nullptr);
3616  return;
3617  }
3618  SetNextEventAction(nullptr);
3619  break;
3620  }
3621  }
3622 
3623  // See if we should broadcast this state to external clients?
3624  const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3625 
3626  if (should_broadcast) {
3627  const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3628  if (log) {
3629  LLDB_LOGF(log,
3630  "Process::%s (pid = %" PRIu64
3631  ") broadcasting new state %s (old state %s) to %s",
3632  __FUNCTION__, GetID(), StateAsCString(new_state),
3634  is_hijacked ? "hijacked" : "public");
3635  }
3637  if (StateIsRunningState(new_state)) {
3638  // Only push the input handler if we aren't fowarding events, as this
3639  // means the curses GUI is in use... Or don't push it if we are launching
3640  // since it will come up stopped.
3641  if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3642  new_state != eStateLaunching && new_state != eStateAttaching) {
3646  LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3647  __FUNCTION__, m_iohandler_sync.GetValue());
3648  }
3649  } else if (StateIsStoppedState(new_state, false)) {
3650  if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3651  // If the lldb_private::Debugger is handling the events, we don't want
3652  // to pop the process IOHandler here, we want to do it when we receive
3653  // the stopped event so we can carefully control when the process
3654  // IOHandler is popped because when we stop we want to display some
3655  // text stating how and why we stopped, then maybe some
3656  // process/thread/frame info, and then we want the "(lldb) " prompt to
3657  // show up. If we pop the process IOHandler here, then we will cause
3658  // the command interpreter to become the top IOHandler after the
3659  // process pops off and it will update its prompt right away... See the
3660  // Debugger.cpp file where it calls the function as
3661  // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3662  // Otherwise we end up getting overlapping "(lldb) " prompts and
3663  // garbled output.
3664  //
3665  // If we aren't handling the events in the debugger (which is indicated
3666  // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3667  // we are hijacked, then we always pop the process IO handler manually.
3668  // Hijacking happens when the internal process state thread is running
3669  // thread plans, or when commands want to run in synchronous mode and
3670  // they call "process->WaitForProcessToStop()". An example of something
3671  // that will hijack the events is a simple expression:
3672  //
3673  // (lldb) expr (int)puts("hello")
3674  //
3675  // This will cause the internal process state thread to resume and halt
3676  // the process (and _it_ will hijack the eBroadcastBitStateChanged
3677  // events) and we do need the IO handler to be pushed and popped
3678  // correctly.
3679 
3680  if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3682  }
3683  }
3684 
3685  BroadcastEvent(event_sp);
3686  } else {
3687  if (log) {
3688  LLDB_LOGF(
3689  log,
3690  "Process::%s (pid = %" PRIu64
3691  ") suppressing state %s (old state %s): should_broadcast == false",
3692  __FUNCTION__, GetID(), StateAsCString(new_state),
3694  }
3695  }
3696 }
3697 
3699  EventSP event_sp;
3700  Status error(WillHalt());
3701  if (error.Fail())
3702  return error;
3703 
3704  // Ask the process subclass to actually halt our process
3705  bool caused_stop;
3706  error = DoHalt(caused_stop);
3707 
3708  DidHalt();
3709  return error;
3710 }
3711 
3713  std::unique_ptr<PrivateStateThreadArgs> args_up(
3714  static_cast<PrivateStateThreadArgs *>(arg));
3715  thread_result_t result =
3716  args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3717  return result;
3718 }
3719 
3721  bool control_only = true;
3722 
3724  LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3725  __FUNCTION__, static_cast<void *>(this), GetID());
3726 
3727  bool exit_now = false;
3728  bool interrupt_requested = false;
3729  while (!exit_now) {
3730  EventSP event_sp;
3731  GetEventsPrivate(event_sp, llvm::None, control_only);
3732  if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3733  LLDB_LOGF(log,
3734  "Process::%s (arg = %p, pid = %" PRIu64
3735  ") got a control event: %d",
3736  __FUNCTION__, static_cast<void *>(this), GetID(),
3737  event_sp->GetType());
3738 
3739  switch (event_sp->GetType()) {
3741  exit_now = true;
3742  break; // doing any internal state management below
3743 
3745  control_only = true;
3746  break;
3747 
3749  control_only = false;
3750  break;
3751  }
3752 
3753  continue;
3754  } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3756  LLDB_LOGF(log,
3757  "Process::%s (arg = %p, pid = %" PRIu64
3758  ") woke up with an interrupt while attaching - "
3759  "forwarding interrupt.",
3760  __FUNCTION__, static_cast<void *>(this), GetID());
3763  LLDB_LOGF(log,
3764  "Process::%s (arg = %p, pid = %" PRIu64
3765  ") woke up with an interrupt - Halting.",
3766  __FUNCTION__, static_cast<void *>(this), GetID());
3767  Status error = HaltPrivate();
3768  if (error.Fail() && log)
3769  LLDB_LOGF(log,
3770  "Process::%s (arg = %p, pid = %" PRIu64
3771  ") failed to halt the process: %s",
3772  __FUNCTION__, static_cast<void *>(this), GetID(),
3773  error.AsCString());
3774  // Halt should generate a stopped event. Make a note of the fact that
3775  // we were doing the interrupt, so we can set the interrupted flag
3776  // after we receive the event. We deliberately set this to true even if
3777  // HaltPrivate failed, so that we can interrupt on the next natural
3778  // stop.
3779  interrupt_requested = true;
3780  } else {
3781  // This can happen when someone (e.g. Process::Halt) sees that we are
3782  // running and sends an interrupt request, but the process actually
3783  // stops before we receive it. In that case, we can just ignore the
3784  // request. We use m_last_broadcast_state, because the Stopped event
3785  // may not have been popped of the event queue yet, which is when the
3786  // public state gets updated.
3787  LLDB_LOGF(log,
3788  "Process::%s ignoring interrupt as we have already stopped.",
3789  __FUNCTION__);
3790  }
3791  continue;
3792  }
3793 
3794  const StateType internal_state =
3796 
3797  if (internal_state != eStateInvalid) {
3799  StateIsStoppedState(internal_state, true)) {
3802  }
3803 
3804  if (interrupt_requested) {
3805  if (StateIsStoppedState(internal_state, true)) {
3806  // We requested the interrupt, so mark this as such in the stop event
3807  // so clients can tell an interrupted process from a natural stop
3808  ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3809  interrupt_requested = false;
3810  } else if (log) {
3811  LLDB_LOGF(log,
3812  "Process::%s interrupt_requested, but a non-stopped "
3813  "state '%s' received.",
3814  __FUNCTION__, StateAsCString(internal_state));
3815  }
3816  }
3817 
3818  HandlePrivateEvent(event_sp);
3819  }
3820 
3821  if (internal_state == eStateInvalid || internal_state == eStateExited ||
3822  internal_state == eStateDetached) {
3823  LLDB_LOGF(log,
3824  "Process::%s (arg = %p, pid = %" PRIu64
3825  ") about to exit with internal state %s...",
3826  __FUNCTION__, static_cast<void *>(this), GetID(),
3827  StateAsCString(internal_state));
3828 
3829  break;
3830  }
3831  }
3832 
3833  // Verify log is still enabled before attempting to write to it...
3834  LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3835  __FUNCTION__, static_cast<void *>(this), GetID());
3836 
3837  // If we are a secondary thread, then the primary thread we are working for
3838  // will have already acquired the public_run_lock, and isn't done with what
3839  // it was doing yet, so don't try to change it on the way out.
3840  if (!is_secondary_thread)
3842  return {};
3843 }
3844 
3845 // Process Event Data
3846 
3848 
3849 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3850  StateType state)
3851  : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3852  m_update_state(0), m_interrupted(false) {
3853  if (process_sp)
3854  m_process_wp = process_sp;
3855 }
3856 
3858 
3860  static ConstString g_flavor("Process::ProcessEventData");
3861  return g_flavor;
3862 }
3863 
3866 }
3867 
3869  bool &found_valid_stopinfo) {
3870  found_valid_stopinfo = false;
3871 
3872  ProcessSP process_sp(m_process_wp.lock());
3873  if (!process_sp)
3874  return false;
3875 
3876  ThreadList &curr_thread_list = process_sp->GetThreadList();
3877  uint32_t num_threads = curr_thread_list.GetSize();
3878  uint32_t idx;
3879 
3880  // The actions might change one of the thread's stop_info's opinions about
3881  // whether we should stop the process, so we need to query that as we go.
3882 
3883  // One other complication here, is that we try to catch any case where the
3884  // target has run (except for expressions) and immediately exit, but if we
3885  // get that wrong (which is possible) then the thread list might have
3886  // changed, and that would cause our iteration here to crash. We could
3887  // make a copy of the thread list, but we'd really like to also know if it
3888  // has changed at all, so we make up a vector of the thread ID's and check
3889  // what we get back against this list & bag out if anything differs.
3890  ThreadList not_suspended_thread_list(process_sp.get());
3891  std::vector<uint32_t> thread_index_array(num_threads);
3892  uint32_t not_suspended_idx = 0;
3893  for (idx = 0; idx < num_threads; ++idx) {
3894  lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3895 
3896  /*
3897  Filter out all suspended threads, they could not be the reason
3898  of stop and no need to perform any actions on them.
3899  */
3900  if (thread_sp->GetResumeState() != eStateSuspended) {
3901  not_suspended_thread_list.AddThread(thread_sp);
3902  thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
3903  not_suspended_idx++;
3904  }
3905  }
3906 
3907  // Use this to track whether we should continue from here. We will only
3908  // continue the target running if no thread says we should stop. Of course
3909  // if some thread's PerformAction actually sets the target running, then it
3910  // doesn't matter what the other threads say...
3911 
3912  bool still_should_stop = false;
3913 
3914  // Sometimes - for instance if we have a bug in the stub we are talking to,
3915  // we stop but no thread has a valid stop reason. In that case we should
3916  // just stop, because we have no way of telling what the right thing to do
3917  // is, and it's better to let the user decide than continue behind their
3918  // backs.
3919 
3920  for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
3921  curr_thread_list = process_sp->GetThreadList();
3922  if (curr_thread_list.GetSize() != num_threads) {
3925  LLDB_LOGF(
3926  log,
3927  "Number of threads changed from %u to %u while processing event.",
3928  num_threads, curr_thread_list.GetSize());
3929  break;
3930  }
3931 
3932  lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
3933 
3934  if (thread_sp->GetIndexID() != thread_index_array[idx]) {
3937  LLDB_LOGF(log,
3938  "The thread at position %u changed from %u to %u while "
3939  "processing event.",
3940  idx, thread_index_array[idx], thread_sp->GetIndexID());
3941  break;
3942  }
3943 
3944  StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
3945  if (stop_info_sp && stop_info_sp->IsValid()) {
3946  found_valid_stopinfo = true;
3947  bool this_thread_wants_to_stop;
3948  if (stop_info_sp->GetOverrideShouldStop()) {
3949  this_thread_wants_to_stop =
3950  stop_info_sp->GetOverriddenShouldStopValue();
3951  } else {
3952  stop_info_sp->PerformAction(event_ptr);
3953  // The stop action might restart the target. If it does, then we
3954  // want to mark that in the event so that whoever is receiving it
3955  // will know to wait for the running event and reflect that state
3956  // appropriately. We also need to stop processing actions, since they
3957  // aren't expecting the target to be running.
3958 
3959  // FIXME: we might have run.
3960  if (stop_info_sp->HasTargetRunSinceMe()) {
3961  SetRestarted(true);
3962  break;
3963  }
3964 
3965  this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
3966  }
3967 
3968  if (!still_should_stop)
3969  still_should_stop = this_thread_wants_to_stop;
3970  }
3971  }
3972 
3973  return still_should_stop;
3974 }
3975 
3977  ProcessSP process_sp(m_process_wp.lock());
3978 
3979  if (!process_sp)
3980  return;
3981 
3982  // This function gets called twice for each event, once when the event gets
3983  // pulled off of the private process event queue, and then any number of
3984  // times, first when it gets pulled off of the public event queue, then other
3985  // times when we're pretending that this is where we stopped at the end of
3986  // expression evaluation. m_update_state is used to distinguish these three
3987  // cases; it is 0 when we're just pulling it off for private handling, and >
3988  // 1 for expression evaluation, and we don't want to do the breakpoint
3989  // command handling then.
3990  if (m_update_state != 1)
3991  return;
3992 
3993  process_sp->SetPublicState(
3995 
3996  if (m_state == eStateStopped && !m_restarted) {
3997  // Let process subclasses know we are about to do a public stop and do
3998  // anything they might need to in order to speed up register and memory
3999  // accesses.
4000  process_sp->WillPublicStop();
4001  }
4002 
4003  // If this is a halt event, even if the halt stopped with some reason other
4004  // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4005  // the halt request came through) don't do the StopInfo actions, as they may
4006  // end up restarting the process.
4007  if (m_interrupted)
4008  return;
4009 
4010  // If we're not stopped or have restarted, then skip the StopInfo actions:
4011  if (m_state != eStateStopped || m_restarted) {
4012  return;
4013  }
4014 
4015  bool does_anybody_have_an_opinion = false;
4016  bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4017 
4018  if (GetRestarted()) {
4019  return;
4020  }
4021 
4022  if (!still_should_stop && does_anybody_have_an_opinion) {
4023  // We've been asked to continue, so do that here.
4024  SetRestarted(true);
4025  // Use the public resume method here, since this is just extending a
4026  // public resume.
4027  process_sp->PrivateResume();
4028  } else {
4029  bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4030  !process_sp->StateChangedIsHijackedForSynchronousResume();
4031 
4032  if (!hijacked) {
4033  // If we didn't restart, run the Stop Hooks here.
4034  // Don't do that if state changed events aren't hooked up to the
4035  // public (or SyncResume) broadcasters. StopHooks are just for
4036  // real public stops. They might also restart the target,
4037  // so watch for that.
4038  if (process_sp->GetTarget().RunStopHooks())
4039  SetRestarted(true);
4040  }
4041  }
4042 }
4043 
4045  ProcessSP process_sp(m_process_wp.lock());
4046 
4047  if (process_sp)
4048  s->Printf(" process = %p (pid = %" PRIu64 "), ",
4049  static_cast<void *>(process_sp.get()), process_sp->GetID());
4050  else
4051  s->PutCString(" process = NULL, ");
4052 
4053  s->Printf("state = %s", StateAsCString(GetState()));
4054 }
4055 
4058  if (event_ptr) {
4059  const EventData *event_data = event_ptr->GetData();
4060  if (event_data &&
4061  event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4062  return static_cast<const ProcessEventData *>(event_ptr->GetData());
4063  }
4064  return nullptr;
4065 }
4066 
4067 ProcessSP
4069  ProcessSP process_sp;
4070  const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4071  if (data)
4072  process_sp = data->GetProcessSP();
4073  return process_sp;
4074 }
4075 
4077  const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4078  if (data == nullptr)
4079  return eStateInvalid;
4080  else
4081  return data->GetState();
4082 }
4083 
4085  const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4086  if (data == nullptr)
4087  return false;
4088  else
4089  return data->GetRestarted();
4090 }
4091 
4093  bool new_value) {
4094  ProcessEventData *data =
4095  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4096  if (data != nullptr)
4097  data->SetRestarted(new_value);
4098 }
4099 
4100 size_t
4102  ProcessEventData *data =
4103  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4104  if (data != nullptr)
4105  return data->GetNumRestartedReasons();
4106  else
4107  return 0;
4108 }
4109 
4110 const char *
4112  size_t idx) {
4113  ProcessEventData *data =
4114  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4115  if (data != nullptr)
4116  return data->GetRestartedReasonAtIndex(idx);
4117  else
4118  return nullptr;
4119 }
4120 
4122  const char *reason) {
4123  ProcessEventData *data =
4124  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4125  if (data != nullptr)
4126  data->AddRestartedReason(reason);
4127 }
4128 
4130  const Event *event_ptr) {
4131  const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4132  if (data == nullptr)
4133  return false;
4134  else
4135  return data->GetInterrupted();
4136 }
4137 
4139  bool new_value) {
4140  ProcessEventData *data =
4141  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4142  if (data != nullptr)
4143  data->SetInterrupted(new_value);
4144 }
4145 
4147  ProcessEventData *data =
4148  const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4149  if (data) {
4150  data->SetUpdateStateOnRemoval();
4151  return true;
4152  }
4153  return false;
4154 }
4155 
4156 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
4157 
4159  exe_ctx.SetTargetPtr(&GetTarget());
4160  exe_ctx.SetProcessPtr(this);
4161  exe_ctx.SetThreadPtr(nullptr);
4162  exe_ctx.SetFramePtr(nullptr);
4163 }
4164 
4165 // uint32_t
4166 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4167 // std::vector<lldb::pid_t> &pids)
4168 //{
4169 // return 0;
4170 //}
4171 //
4172 // ArchSpec
4173 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4174 //{
4175 // return Host::GetArchSpecForExistingProcess (pid);
4176 //}
4177 //
4178 // ArchSpec
4179 // Process::GetArchSpecForExistingProcess (const char *process_name)
4180 //{
4181 // return Host::GetArchSpecForExistingProcess (process_name);
4182 //}
4183 
4184 void Process::AppendSTDOUT(const char *s, size_t len) {
4185  std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4186  m_stdout_data.append(s, len);
4188  new ProcessEventData(shared_from_this(), GetState()));
4189 }
4190 
4191 void Process::AppendSTDERR(const char *s, size_t len) {
4192  std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4193  m_stderr_data.append(s, len);
4195  new ProcessEventData(shared_from_this(), GetState()));
4196 }
4197 
4198 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4199  std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4200  m_profile_data.push_back(one_profile_data);
4202  new ProcessEventData(shared_from_this(), GetState()));
4203 }
4204 
4206  const StructuredDataPluginSP &plugin_sp) {
4209  new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4210 }
4211 
4212 StructuredDataPluginSP
4214  auto find_it = m_structured_data_plugin_map.find(type_name);
4215  if (find_it != m_structured_data_plugin_map.end())
4216  return find_it->second;
4217  else
4218  return StructuredDataPluginSP();
4219 }
4220 
4221 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4222  std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4223  if (m_profile_data.empty())
4224  return 0;
4225 
4226  std::string &one_profile_data = m_profile_data.front();
4227  size_t bytes_available = one_profile_data.size();
4228  if (bytes_available > 0) {
4230  LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4231  static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4232  if (bytes_available > buf_size) {
4233  memcpy(buf, one_profile_data.c_str(), buf_size);
4234  one_profile_data.erase(0, buf_size);
4235  bytes_available = buf_size;
4236  } else {
4237  memcpy(buf, one_profile_data.c_str(), bytes_available);
4238  m_profile_data.erase(m_profile_data.begin());
4239  }
4240  }
4241  return bytes_available;
4242 }
4243 
4244 // Process STDIO
4245 
4246 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4247  std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4248  size_t bytes_available = m_stdout_data.size();
4249  if (bytes_available > 0) {
4251  LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4252  static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4253  if (bytes_available > buf_size) {
4254  memcpy(buf, m_stdout_data.c_str(), buf_size);
4255  m_stdout_data.erase(0, buf_size);
4256  bytes_available = buf_size;
4257  } else {
4258  memcpy(buf, m_stdout_data.c_str(), bytes_available);
4259  m_stdout_data.clear();
4260  }
4261  }
4262  return bytes_available;
4263 }
4264 
4265 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4266  std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4267  size_t bytes_available = m_stderr_data.size();
4268  if (bytes_available > 0) {
4270  LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4271  static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4272  if (bytes_available > buf_size) {
4273  memcpy(buf, m_stderr_data.c_str(), buf_size);
4274  m_stderr_data.erase(0, buf_size);
4275  bytes_available = buf_size;
4276  } else {
4277  memcpy(buf, m_stderr_data.c_str(), bytes_available);
4278  m_stderr_data.clear();
4279  }
4280  }
4281  return bytes_available;
4282 }
4283 
4284 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4285  size_t src_len) {
4286  Process *process = (Process *)baton;
4287  process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4288 }
4289 
4291 public:
4292  IOHandlerProcessSTDIO(Process *process, int write_fd)
4293  : IOHandler(process->GetTarget().GetDebugger(),
4294  IOHandler::Type::ProcessIO),
4295  m_process(process),
4296  m_read_file(GetInputFD(), File::eOpenOptionRead, false),
4297  m_write_file(write_fd, File::eOpenOptionWrite, false) {
4298  m_pipe.CreateNew(false);
4299  }
4300 
4301  ~IOHandlerProcessSTDIO() override = default;
4302 
4303  // Each IOHandler gets to run until it is done. It should read data from the
4304  // "in" and place output into "out" and "err and return when done.
4305  void Run() override {
4306  if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4307  !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4308  SetIsDone(true);
4309  return;
4310  }
4311 
4312  SetIsDone(false);
4313  const int read_fd = m_read_file.GetDescriptor();
4314  TerminalState terminal_state;
4315  terminal_state.Save(read_fd, false);
4316  Terminal terminal(read_fd);
4317  terminal.SetCanonical(false);
4318  terminal.SetEcho(false);
4319 // FD_ZERO, FD_SET are not supported on windows
4320 #ifndef _WIN32
4321  const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4322  m_is_running = true;
4323  while (!GetIsDone()) {
4324  SelectHelper select_helper;
4325  select_helper.FDSetRead(read_fd);
4326  select_helper.FDSetRead(pipe_read_fd);
4327  Status error = select_helper.Select();
4328 
4329  if (error.Fail()) {
4330  SetIsDone(true);
4331  } else {
4332  char ch = 0;
4333  size_t n;
4334  if (select_helper.FDIsSetRead(read_fd)) {
4335  n = 1;
4336  if (m_read_file.Read(&ch, n).Success() && n == 1) {
4337  if (m_write_file.Write(&ch, n).Fail() || n != 1)
4338  SetIsDone(true);
4339  } else
4340  SetIsDone(true);
4341  }
4342  if (select_helper.FDIsSetRead(pipe_read_fd)) {
4343  size_t bytes_read;
4344  // Consume the interrupt byte
4345  Status error = m_pipe.Read(&ch, 1, bytes_read);
4346  if (error.Success()) {
4347  switch (ch) {
4348  case 'q':
4349  SetIsDone(true);
4350  break;
4351  case 'i':
4354  break;
4355  }
4356  }
4357  }
4358  }
4359  }
4360  m_is_running = false;
4361 #endif
4362  terminal_state.Restore();
4363  }
4364 
4365  void Cancel() override {
4366  SetIsDone(true);
4367  // Only write to our pipe to cancel if we are in
4368  // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4369  // is being run from the command interpreter:
4370  //
4371  // (lldb) step_process_thousands_of_times
4372  //
4373  // In this case the command interpreter will be in the middle of handling
4374  // the command and if the process pushes and pops the IOHandler thousands
4375  // of times, we can end up writing to m_pipe without ever consuming the
4376  // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4377  // deadlocking when the pipe gets fed up and blocks until data is consumed.
4378  if (m_is_running) {
4379  char ch = 'q'; // Send 'q' for quit
4380  size_t bytes_written = 0;
4381  m_pipe.Write(&ch, 1, bytes_written);
4382  }
4383  }
4384 
4385  bool Interrupt() override {
4386  // Do only things that are safe to do in an interrupt context (like in a
4387  // SIGINT handler), like write 1 byte to a file descriptor. This will
4388  // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4389  // that was written to the pipe and then call
4390  // m_process->SendAsyncInterrupt() from a much safer location in code.
4391  if (m_active) {
4392  char ch = 'i'; // Send 'i' for interrupt
4393  size_t bytes_written = 0;
4394  Status result = m_pipe.Write(&ch, 1, bytes_written);
4395  return result.Success();
4396  } else {
4397  // This IOHandler might be pushed on the stack, but not being run
4398  // currently so do the right thing if we aren't actively watching for
4399  // STDIN by sending the interrupt to the process. Otherwise the write to
4400  // the pipe above would do nothing. This can happen when the command
4401  // interpreter is running and gets a "expression ...". It will be on the
4402  // IOHandler thread and sending the input is complete to the delegate
4403  // which will cause the expression to run, which will push the process IO
4404  // handler, but not run it.
4405 
4408  return true;
4409  }
4410  }
4411  return false;
4412  }
4413 
4414  void GotEOF() override {}
4415 
4416 protected:
4418  NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4419  NativeFile m_write_file; // Write to this file (usually the master pty for
4420  // getting io to debuggee)
4422  std::atomic<bool> m_is_running{false};
4423 };
4424 
4426  // First set up the Read Thread for reading/handling process I/O
4428  std::make_unique<ConnectionFileDescriptor>(fd, true));
4433 
4434  // Now read thread is set up, set up input reader.
4435 
4438  std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4439  }
4440 }
4441 
4443  IOHandlerSP io_handler_sp(m_process_input_reader);
4444  if (io_handler_sp)
4445  return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4446  return false;
4447 }
4449  IOHandlerSP io_handler_sp(m_process_input_reader);
4450  if (io_handler_sp) {
4452  LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
4453 
4454  io_handler_sp->SetIsDone(false);
4455  // If we evaluate an utility function, then we don't cancel the current
4456  // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4457  // existing IOHandler that potentially provides the user interface (e.g.
4458  // the IOHandler for Editline).
4459  bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4460  GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4461  cancel_top_handler);
4462  return true;
4463  }
4464  return false;
4465 }
4466 
4468  IOHandlerSP io_handler_sp(m_process_input_reader);
4469  if (io_handler_sp)
4470  return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
4471  return false;
4472 }
4473 
4474 // The process needs to know about installed plug-ins
4476 
4478 
4479 namespace {
4480 // RestorePlanState is used to record the "is private", "is master" and "okay
4481 // to discard" fields of the plan we are running, and reset it on Clean or on
4482 // destruction. It will only reset the state once, so you can call Clean and
4483 // then monkey with the state and it won't get reset on you again.
4484 
4485 class RestorePlanState {
4486 public:
4487  RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4488  : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4489  if (m_thread_plan_sp) {
4490  m_private = m_thread_plan_sp->GetPrivate();
4491  m_is_master = m_thread_plan_sp->IsMasterPlan();
4492  m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4493  }
4494  }
4495 
4496  ~RestorePlanState() { Clean(); }
4497 
4498  void Clean() {
4499  if (!m_already_reset && m_thread_plan_sp) {
4500  m_already_reset = true;
4501  m_thread_plan_sp->SetPrivate(m_private);
4502  m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4503  m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4504  }
4505  }
4506 
4507 private:
4508  lldb::ThreadPlanSP m_thread_plan_sp;
4509  bool m_already_reset;
4510  bool m_private;
4511  bool m_is_master;
4512  bool m_okay_to_discard;
4513 };
4514 } // anonymous namespace
4515 
4516 static microseconds
4518  const milliseconds default_one_thread_timeout(250);
4519 
4520  // If the overall wait is forever, then we don't need to worry about it.
4521  if (!options.GetTimeout()) {
4522  return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4523  : default_one_thread_timeout;
4524  }
4525 
4526  // If the one thread timeout is set, use it.
4527  if (options.GetOneThreadTimeout())
4528  return *options.GetOneThreadTimeout();
4529 
4530  // Otherwise use half the total timeout, bounded by the
4531  // default_one_thread_timeout.
4532  return std::min<microseconds>(default_one_thread_timeout,
4533  *options.GetTimeout() / 2);
4534 }
4535 
4536 static Timeout<std::micro>
4538  bool before_first_timeout) {
4539  // If we are going to run all threads the whole time, or if we are only going
4540  // to run one thread, we can just return the overall timeout.
4541  if (!options.GetStopOthers() || !options.GetTryAllThreads())
4542  return options.GetTimeout();
4543 
4544  if (before_first_timeout)
4545  return GetOneThreadExpressionTimeout(options);
4546 
4547  if (!options.GetTimeout())
4548  return llvm::None;
4549  else
4550  return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4551 }
4552 
4553 static llvm::Optional<ExpressionResults>
4554 HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
4555  RestorePlanState &restorer, const EventSP &event_sp,
4556  EventSP &event_to_broadcast_sp,
4557  const EvaluateExpressionOptions &options,
4558  bool handle_interrupts) {
4560 
4561  ThreadSP thread_sp = thread_plan_sp->GetTarget()
4562  .GetProcessSP()
4563  ->GetThreadList()
4564  .FindThreadByID(thread_id);
4565  if (!thread_sp) {
4566  LLDB_LOG(log,
4567  "The thread on which we were running the "
4568  "expression: tid = {0}, exited while "
4569  "the expression was running.",
4570  thread_id);
4572  }
4573 
4574  ThreadPlanSP plan = thread_sp->GetCompletedPlan();
4575  if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4576  LLDB_LOG(log, "execution completed successfully");
4577 
4578  // Restore the plan state so it will get reported as intended when we are
4579  // done.
4580  restorer.Clean();
4581  return eExpressionCompleted;
4582  }
4583 
4584  StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4585  if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4586  stop_info_sp->ShouldNotify(event_sp.get())) {
4587  LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4588  if (!options.DoesIgnoreBreakpoints()) {
4589  // Restore the plan state and then force Private to false. We are going
4590  // to stop because of this plan so we need it to become a public plan or
4591  // it won't report correctly when we continue to its termination later
4592  // on.
4593  restorer.Clean();
4594  thread_plan_sp->SetPrivate(false);
4595  event_to_broadcast_sp = event_sp;
4596  }
4597  return eExpressionHitBreakpoint;
4598  }
4599 
4600  if (!handle_interrupts &&
4602  return llvm::None;
4603 
4604  LLDB_LOG(log, "thread plan did not successfully complete");
4605  if (!options.DoesUnwindOnError())
4606  event_to_broadcast_sp = event_sp;
4607  return eExpressionInterrupted;
4608 }
4609 
4612  lldb::ThreadPlanSP &thread_plan_sp,
4613  const EvaluateExpressionOptions &options,
4614  DiagnosticManager &diagnostic_manager) {
4616 
4617  std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4618 
4619  if (!thread_plan_sp) {
4620  diagnostic_manager.PutString(
4622  "RunThreadPlan called with empty thread plan.");
4623  return eExpressionSetupError;
4624  }
4625 
4626  if (!thread_plan_sp->ValidatePlan(nullptr)) {
4627  diagnostic_manager.PutString(
4629  "RunThreadPlan called with an invalid thread plan.");
4630  return eExpressionSetupError;
4631  }
4632 
4633  if (exe_ctx.GetProcessPtr() != this) {
4634  diagnostic_manager.PutString(eDiagnosticSeverityError,
4635  "RunThreadPlan called on wrong process.");
4636  return eExpressionSetupError;
4637  }
4638 
4639  Thread *thread = exe_ctx.GetThreadPtr();
4640  if (thread == nullptr) {
4641  diagnostic_manager.PutString(eDiagnosticSeverityError,
4642  "RunThreadPlan called with invalid thread.");
4643  return eExpressionSetupError;
4644  }
4645 
4646  // Record the thread's id so we can tell when a thread we were using
4647  // to run the expression exits during the expression evaluation.
4648  lldb::tid_t expr_thread_id = thread->GetID();
4649 
4650  // We need to change some of the thread plan attributes for the thread plan
4651  // runner. This will restore them when we are done:
4652 
4653  RestorePlanState thread_plan_restorer(thread_plan_sp);
4654 
4655  // We rely on the thread plan we are running returning "PlanCompleted" if
4656  // when it successfully completes. For that to be true the plan can't be
4657  // private - since private plans suppress themselves in the GetCompletedPlan
4658  // call.
4659 
4660  thread_plan_sp->SetPrivate(false);
4661 
4662  // The plans run with RunThreadPlan also need to be terminal master plans or
4663  // when they are done we will end up asking the plan above us whether we
4664  // should stop, which may give the wrong answer.
4665 
4666  thread_plan_sp->SetIsMasterPlan(true);
4667  thread_plan_sp->SetOkayToDiscard(false);
4668 
4669  // If we are running some utility expression for LLDB, we now have to mark
4670  // this in the ProcesModID of this process. This RAII takes care of marking
4671  // and reverting the mark it once we are done running the expression.
4672  UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4673 
4675  diagnostic_manager.PutString(
4677  "RunThreadPlan called while the private state was not stopped.");
4678  return eExpressionSetupError;
4679  }
4680 
4681  // Save the thread & frame from the exe_ctx for restoration after we run
4682  const uint32_t thread_idx_id = thread->GetIndexID();
4683  StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4684  if (!selected_frame_sp) {
4685  thread->SetSelectedFrame(nullptr);
4686  selected_frame_sp = thread->GetSelectedFrame();
4687  if (!selected_frame_sp) {
4688  diagnostic_manager.Printf(
4690  "RunThreadPlan called without a selected frame on thread %d",
4691  thread_idx_id);
4692  return eExpressionSetupError;
4693  }
4694  }
4695 
4696  // Make sure the timeout values make sense. The one thread timeout needs to
4697  // be smaller than the overall timeout.
4698  if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4699  *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4700  diagnostic_manager.PutString(eDiagnosticSeverityError,
4701  "RunThreadPlan called with one thread "
4702  "timeout greater than total timeout");
4703  return eExpressionSetupError;
4704  }
4705 
4706  StackID ctx_frame_id = selected_frame_sp->GetStackID();
4707 
4708  // N.B. Running the target may unset the currently selected thread and frame.
4709  // We don't want to do that either, so we should arrange to reset them as
4710  // well.
4711 
4712  lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4713 
4714  uint32_t selected_tid;
4715  StackID selected_stack_id;
4716  if (selected_thread_sp) {
4717  selected_tid = selected_thread_sp->GetIndexID();
4718  selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4719  } else {
4720  selected_tid = LLDB_INVALID_THREAD_ID;
4721  }
4722 
4723  HostThread backup_private_state_thread;
4724  lldb::StateType old_state = eStateInvalid;
4725  lldb::ThreadPlanSP stopper_base_plan_sp;
4726 
4730  // Yikes, we are running on the private state thread! So we can't wait for
4731  // public events on this thread, since we are the thread that is generating
4732  // public events. The simplest thing to do is to spin up a temporary thread
4733  // to handle private state thread events while we are fielding public
4734  // events here.
4735  LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4736  "another state thread to handle the events.");
4737 
4738  backup_private_state_thread = m_private_state_thread;
4739 
4740  // One other bit of business: we want to run just this thread plan and
4741  // anything it pushes, and then stop, returning control here. But in the
4742  // normal course of things, the plan above us on the stack would be given a
4743  // shot at the stop event before deciding to stop, and we don't want that.
4744  // So we insert a "stopper" base plan on the stack before the plan we want
4745  // to run. Since base plans always stop and return control to the user,
4746  // that will do just what we want.
4747  stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4748  thread->QueueThreadPlan(stopper_base_plan_sp, false);
4749  // Have to make sure our public state is stopped, since otherwise the
4750  // reporting logic below doesn't work correctly.
4751  old_state = m_public_state.GetValue();
4753 
4754  // Now spin up the private state thread:
4756  }
4757 
4758  thread->QueueThreadPlan(
4759  thread_plan_sp, false); // This used to pass "true" does that make sense?
4760 
4761  if (options.GetDebug()) {
4762  // In this case, we aren't actually going to run, we just want to stop
4763  // right away. Flush this thread so we will refetch the stacks and show the
4764  // correct backtrace.
4765  // FIXME: To make this prettier we should invent some stop reason for this,
4766  // but that
4767  // is only cosmetic, and this functionality is only of use to lldb
4768  // developers who can live with not pretty...
4769  thread->Flush();
4771  }
4772 
4773  ListenerSP listener_sp(
4774  Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4775 
4776  lldb::EventSP event_to_broadcast_sp;
4777 
4778  {
4779  // This process event hijacker Hijacks the Public events and its destructor
4780  // makes sure that the process events get restored on exit to the function.
4781  //
4782  // If the event needs to propagate beyond the hijacker (e.g., the process
4783  // exits during execution), then the event is put into
4784  // event_to_broadcast_sp for rebroadcasting.
4785 
4786  ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4787 
4788  if (log) {
4789  StreamString s;
4790  thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4791  LLDB_LOGF(log,
4792  "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4793  " to run thread plan \"%s\".",
4794  thread_idx_id, expr_thread_id, s.GetData());
4795  }
4796 
4797  bool got_event;
4798  lldb::EventSP event_sp;
4799  lldb::StateType stop_state = lldb::eStateInvalid;
4800 
4801  bool before_first_timeout = true; // This is set to false the first time
4802  // that we have to halt the target.
4803  bool do_resume = true;
4804  bool handle_running_event = true;
4805 
4806  // This is just for accounting:
4807  uint32_t num_resumes = 0;
4808 
4809  // If we are going to run all threads the whole time, or if we are only
4810  // going to run one thread, then we don't need the first timeout. So we
4811  // pretend we are after the first timeout already.
4812  if (!options.GetStopOthers() || !options.GetTryAllThreads())
4813  before_first_timeout = false;
4814 
4815  LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4816  options.GetStopOthers(), options.GetTryAllThreads(),
4817  before_first_timeout);
4818 
4819  // This isn't going to work if there are unfetched events on the queue. Are
4820  // there cases where we might want to run the remaining events here, and
4821  // then try to call the function? That's probably being too tricky for our
4822  // own good.
4823 
4824  Event *other_events = listener_sp->PeekAtNextEvent();
4825  if (other_events != nullptr) {
4826  diagnostic_manager.PutString(
4828  "RunThreadPlan called with pending events on the queue.");
4829  return eExpressionSetupError;
4830  }
4831 
4832  // We also need to make sure that the next event is delivered. We might be
4833  // calling a function as part of a thread plan, in which case the last
4834  // delivered event could be the running event, and we don't want event
4835  // coalescing to cause us to lose OUR running event...
4837 
4838 // This while loop must exit out the bottom, there's cleanup that we need to do
4839 // when we are done. So don't call return anywhere within it.
4840 
4841 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4842  // It's pretty much impossible to write test cases for things like: One
4843  // thread timeout expires, I go to halt, but the process already stopped on
4844  // the function call stop breakpoint. Turning on this define will make us
4845  // not fetch the first event till after the halt. So if you run a quick
4846  // function, it will have completed, and the completion event will be
4847  // waiting, when you interrupt for halt. The expression evaluation should
4848  // still succeed.
4849  bool miss_first_event = true;
4850 #endif
4851  while (true) {
4852  // We usually want to resume the process if we get to the top of the
4853  // loop. The only exception is if we get two running events with no
4854  // intervening stop, which can happen, we will just wait for then next
4855  // stop event.
4856  LLDB_LOGF(log,
4857  "Top of while loop: do_resume: %i handle_running_event: %i "
4858  "before_first_timeout: %i.",
4859  do_resume, handle_running_event, before_first_timeout);
4860 
4861  if (do_resume || handle_running_event) {
4862  // Do the initial resume and wait for the running event before going
4863  // further.
4864 
4865  if (do_resume) {
4866  num_resumes++;
4867  Status resume_error = PrivateResume();
4868  if (!resume_error.Success()) {
4869  diagnostic_manager.Printf(
4871  "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4872  resume_error.AsCString());
4873  return_value = eExpressionSetupError;
4874  break;
4875  }
4876  }
4877 
4878  got_event =
4879  listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
4880  if (!got_event) {
4881  LLDB_LOGF(log,
4882  "Process::RunThreadPlan(): didn't get any event after "
4883  "resume %" PRIu32 ", exiting.",
4884  num_resumes);
4885 
4886  diagnostic_manager.Printf(eDiagnosticSeverityError,
4887  "didn't get any event after resume %" PRIu32
4888  ", exiting.",
4889  num_resumes);
4890  return_value = eExpressionSetupError;
4891  break;
4892  }
4893 
4894  stop_state =
4896 
4897  if (stop_state != eStateRunning) {
4898  bool restarted = false;
4899 
4900  if (stop_state == eStateStopped) {
4902  event_sp.get());
4903  LLDB_LOGF(
4904  log,
4905  "Process::RunThreadPlan(): didn't get running event after "
4906  "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4907  "handle_running_event: %i).",
4908  num_resumes, StateAsCString(stop_state), restarted, do_resume,
4909  handle_running_event);
4910  }
4911 
4912  if (restarted) {
4913  // This is probably an overabundance of caution, I don't think I
4914  // should ever get a stopped & restarted event here. But if I do,
4915  // the best thing is to Halt and then get out of here.
4916  const bool clear_thread_plans = false;
4917  const bool use_run_lock = false;
4918  Halt(clear_thread_plans, use_run_lock);
4919  }
4920 
4921  diagnostic_manager.Printf(
4923  "didn't get running event after initial resume, got %s instead.",
4924  StateAsCString(stop_state));
4925  return_value = eExpressionSetupError;
4926  break;
4927  }
4928 
4929  if (log)
4930  log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
4931  // We need to call the function synchronously, so spin waiting for it
4932  // to return. If we get interrupted while executing, we're going to
4933  // lose our context, and won't be able to gather the result at this
4934  // point. We set the timeout AFTER the resume, since the resume takes
4935  // some time and we don't want to charge that to the timeout.
4936  } else {
4937  if (log)
4938  log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4939  }
4940 
4941  do_resume = true;
4942  handle_running_event = true;
4943 
4944  // Now wait for the process to stop again:
4945  event_sp.reset();
4946 
4947  Timeout<std::micro> timeout =
4948  GetExpressionTimeout(options, before_first_timeout);
4949  if (log) {
4950  if (timeout) {
4951  auto now = system_clock::now();
4952  LLDB_LOGF(log,
4953  "Process::RunThreadPlan(): about to wait - now is %s - "
4954  "endpoint is %s",
4955  llvm::to_string(now).c_str(),
4956  llvm::to_string(now + *timeout).c_str());
4957  } else {
4958  LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
4959  }
4960  }
4961 
4962 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4963  // See comment above...
4964  if (miss_first_event) {
4965  std::this_thread::sleep_for(std::chrono::milliseconds(1));
4966  miss_first_event = false;
4967  got_event = false;
4968  } else
4969 #endif
4970  got_event = listener_sp->GetEvent(event_sp, timeout);
4971 
4972  if (got_event) {
4973  if (event_sp) {
4974  bool keep_going = false;
4975  if (event_sp->GetType() == eBroadcastBitInterrupt) {
4976  const bool clear_thread_plans = false;
4977  const bool use_run_lock = false;
4978  Halt(clear_thread_plans, use_run_lock);
4979  return_value = eExpressionInterrupted;
4980  diagnostic_manager.PutString(eDiagnosticSeverityRemark,
4981  "execution halted by user interrupt.");
4982  LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
4983  "eBroadcastBitInterrupted, exiting.");
4984  break;
4985  } else {
4986  stop_state =
4988  LLDB_LOGF(log,
4989  "Process::RunThreadPlan(): in while loop, got event: %s.",
4990  StateAsCString(stop_state));
4991 
4992  switch (stop_state) {
4993  case lldb::eStateStopped: {
4995  event_sp.get())) {
4996  // If we were restarted, we just need to go back up to fetch
4997  // another event.
4998  LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
4999  "restart, so we'll continue waiting.");
5000  keep_going = true;
5001  do_resume = false;
5002  handle_running_event = true;
5003  } else {
5004  const bool handle_interrupts = true;
5005  return_value = *HandleStoppedEvent(
5006  expr_thread_id, thread_plan_sp, thread_plan_restorer,
5007  event_sp, event_to_broadcast_sp, options,
5008  handle_interrupts);
5009  if (return_value == eExpressionThreadVanished)
5010  keep_going = false;
5011  }
5012  } break;
5013 
5014  case lldb::eStateRunning:
5015  // This shouldn't really happen, but sometimes we do get two
5016  // running events without an intervening stop, and in that case
5017  // we should just go back to waiting for the stop.
5018  do_resume = false;
5019  keep_going = true;
5020  handle_running_event = false;
5021  break;
5022 
5023  default:
5024  LLDB_LOGF(log,
5025  "Process::RunThreadPlan(): execution stopped with "
5026  "unexpected state: %s.",
5027  StateAsCString(stop_state));
5028 
5029  if (stop_state == eStateExited)
5030  event_to_broadcast_sp = event_sp;
5031 
5032  diagnostic_manager.PutString(
5034  "execution stopped with unexpected state.");
5035  return_value = eExpressionInterrupted;
5036  break;
5037  }
5038  }
5039 
5040  if (keep_going)
5041  continue;
5042  else
5043  break;
5044  } else {
5045  if (log)
5046  log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5047  "the event pointer was null. How odd...");
5048  return_value = eExpressionInterrupted;
5049  break;
5050  }
5051  } else {
5052  // If we didn't get an event that means we've timed out... We will
5053  // interrupt the process here. Depending on what we were asked to do
5054  // we will either exit, or try with all threads running for the same
5055  // timeout.
5056 
5057  if (log) {
5058  if (options.GetTryAllThreads()) {
5059  if (before_first_timeout) {
5060  LLDB_LOG(log,
5061  "Running function with one thread timeout timed out.");
5062  } else
5063  LLDB_LOG(log, "Restarting function with all threads enabled and "
5064  "timeout: {0} timed out, abandoning execution.",
5065  timeout);
5066  } else
5067  LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5068  "abandoning execution.",
5069  timeout);
5070  }
5071 
5072  // It is possible that between the time we issued the Halt, and we get
5073  // around to calling Halt the target could have stopped. That's fine,
5074  // Halt will figure that out and send the appropriate Stopped event.
5075  // BUT it is also possible that we stopped & restarted (e.g. hit a
5076  // signal with "stop" set to false.) In
5077  // that case, we'll get the stopped & restarted event, and we should go
5078  // back to waiting for the Halt's stopped event. That's what this
5079  // while loop does.
5080 
5081  bool back_to_top = true;
5082  uint32_t try_halt_again = 0;
5083  bool do_halt = true;
5084  const uint32_t num_retries = 5;
5085  while (try_halt_again < num_retries) {
5086  Status halt_error;
5087  if (do_halt) {
5088  LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5089  const bool clear_thread_plans = false;
5090  const bool use_run_lock = false;
5091  Halt(clear_thread_plans, use_run_lock);
5092  }
5093  if (halt_error.Success()) {
5094  if (log)
5095  log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5096 
5097  got_event =
5098  listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5099 
5100  if (got_event) {
5101  stop_state =
5103  if (log) {
5104  LLDB_LOGF(log,
5105  "Process::RunThreadPlan(): Stopped with event: %s",
5106  StateAsCString(stop_state));
5107  if (stop_state == lldb::eStateStopped &&
5109  event_sp.get()))
5110  log->PutCString(" Event was the Halt interruption event.");
5111  }
5112 
5113  if (stop_state == lldb::eStateStopped) {
5115  event_sp.get())) {
5116  if (log)
5117  log->PutCString("Process::RunThreadPlan(): Went to halt "
5118  "but got a restarted event, there must be "
5119  "an un-restarted stopped event so try "
5120  "again... "
5121  "Exiting wait loop.");
5122  try_halt_again++;
5123  do_halt = false;
5124  continue;
5125  }
5126 
5127  // Between the time we initiated the Halt and the time we
5128  // delivered it, the process could have already finished its
5129  // job. Check that here:
5130  const bool handle_interrupts = false;
5131  if (auto result = HandleStoppedEvent(
5132  expr_thread_id, thread_plan_sp, thread_plan_restorer,
5133  event_sp, event_to_broadcast_sp, options,
5134  handle_interrupts)) {
5135  return_value = *result;
5136  back_to_top = false;
5137  break;
5138  }
5139 
5140  if (!options.GetTryAllThreads()) {
5141  if (log)
5142  log->PutCString("Process::RunThreadPlan(): try_all_threads "
5143  "was false, we stopped so now we're "
5144  "quitting.");
5145  return_value = eExpressionInterrupted;
5146  back_to_top = false;
5147  break;
5148  }
5149 
5150  if (before_first_timeout) {
5151  // Set all the other threads to run, and return to the top of
5152  // the loop, which will continue;
5153  before_first_timeout = false;
5154  thread_plan_sp->SetStopOthers(false);
5155  if (log)
5156  log->PutCString(
5157  "Process::RunThreadPlan(): about to resume.");
5158 
5159  back_to_top = true;
5160  break;
5161  } else {
5162  // Running all threads failed, so return Interrupted.
5163  if (log)
5164  log->PutCString("Process::RunThreadPlan(): running all "
5165  "threads timed out.");
5166  return_value = eExpressionInterrupted;
5167  back_to_top = false;
5168  break;
5169  }
5170  }
5171  } else {
5172  if (log)
5173  log->PutCString("Process::RunThreadPlan(): halt said it "
5174  "succeeded, but I got no event. "
5175  "I'm getting out of here passing Interrupted.");
5176  return_value = eExpressionInterrupted;
5177  back_to_top = false;
5178  break;
5179  }
5180  } else {
5181  try_halt_again++;
5182  continue;
5183  }
5184  }
5185 
5186  if (!back_to_top || try_halt_again > num_retries)
5187  break;
5188  else
5189  continue;
5190  }
5191  } // END WAIT LOOP
5192 
5193  // If we had to start up a temporary private state thread to run this
5194  // thread plan, shut it down now.
5195  if (backup_private_state_thread.IsJoinable()) {
5197  Status error;
5198  m_private_state_thread = backup_private_state_thread;
5199  if (stopper_base_plan_sp) {
5200  thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5201  }
5202  if (old_state != eStateInvalid)
5203  m_public_state.SetValueNoLock(old_state);
5204  }
5205 
5206  // If our thread went away on us, we need to get out of here without
5207  // doing any more work. We don't have to clean up the thread plan, that
5208  // will have happened when the Thread was destroyed.
5209  if (return_value == eExpressionThreadVanished) {
5210  return return_value;
5211  }
5212 
5213  if (return_value != eExpressionCompleted && log) {
5214  // Print a backtrace into the log so we can figure out where we are:
5215  StreamString s;
5216  s.PutCString("Thread state after unsuccessful completion: \n");
5217  thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5218  log->PutString(s.GetString());
5219  }
5220  // Restore the thread state if we are going to discard the plan execution.
5221  // There are three cases where this could happen: 1) The execution
5222  // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5223  // was true 3) We got some other error, and discard_on_error was true
5224  bool should_unwind = (return_value == eExpressionInterrupted &&
5225  options.DoesUnwindOnError()) ||
5226  (return_value == eExpressionHitBreakpoint &&
5227  options.DoesIgnoreBreakpoints());
5228 
5229  if (return_value == eExpressionCompleted || should_unwind) {
5230  thread_plan_sp->RestoreThreadState();
5231  }
5232 
5233  // Now do some processing on the results of the run:
5234  if (return_value == eExpressionInterrupted ||
5235  return_value == eExpressionHitBreakpoint) {
5236  if (log) {
5237  StreamString s;
5238  if (event_sp)
5239  event_sp->Dump(&s);
5240  else {
5241  log->PutCString("Process::RunThreadPlan(): Stop event that "
5242  "interrupted us is NULL.");
5243  }
5244 
5245  StreamString ts;
5246 
5247  const char *event_explanation = nullptr;
5248 
5249  do {
5250  if (!event_sp) {
5251  event_explanation = "<no event>";
5252  break;
5253  } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5254  event_explanation = "<user interrupt>";
5255  break;
5256  } else {
5257  const Process::ProcessEventData *event_data =
5259  event_sp.get());
5260 
5261  if (!event_data) {
5262  event_explanation = "<no event data>";
5263  break;
5264  }
5265 
5266  Process *process = event_data->GetProcessSP().get();
5267 
5268  if (!process) {
5269  event_explanation = "<no process>";
5270  break;
5271  }
5272 
5273  ThreadList &thread_list = process->GetThreadList();
5274 
5275  uint32_t num_threads = thread_list.GetSize();
5276  uint32_t thread_index;
5277 
5278  ts.Printf("<%u threads> ", num_threads);
5279 
5280  for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5281  Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5282 
5283  if (!thread) {
5284  ts.Printf("<?> ");
5285  continue;
5286  }
5287 
5288  ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5289  RegisterContext *register_context =
5290  thread->GetRegisterContext().get();
5291 
5292  if (register_context)
5293  ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5294  else
5295  ts.Printf("[ip unknown] ");
5296 
5297  // Show the private stop info here, the public stop info will be
5298  // from the last natural stop.
5299  lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5300  if (stop_info_sp) {
5301  const char *stop_desc = stop_info_sp->GetDescription();
5302  if (stop_desc)
5303  ts.PutCString(stop_desc);
5304  }
5305  ts.Printf(">");
5306  }
5307 
5308  event_explanation = ts.GetData();
5309  }
5310  } while (false);
5311 
5312  if (event_explanation)
5313  LLDB_LOGF(log,
5314  "Process::RunThreadPlan(): execution interrupted: %s %s",
5315  s.GetData(), event_explanation);
5316  else
5317  LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5318  s.GetData());
5319  }
5320 
5321  if (should_unwind) {
5322  LLDB_LOGF(log,
5323  "Process::RunThreadPlan: ExecutionInterrupted - "
5324  "discarding thread plans up to %p.",
5325  static_cast<void *>(thread_plan_sp.get()));
5326  thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5327  } else {
5328  LLDB_LOGF(log,
5329  "Process::RunThreadPlan: ExecutionInterrupted - for "
5330  "plan: %p not discarding.",
5331  static_cast<void *>(thread_plan_sp.get()));
5332  }
5333  } else if (return_value == eExpressionSetupError) {
5334  if (log)
5335  log->PutCString("Process::RunThreadPlan(): execution set up error.");
5336 
5337  if (options.DoesUnwindOnError()) {
5338  thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5339  }
5340  } else {
5341  if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5342  if (log)
5343  log->PutCString("Process::RunThreadPlan(): thread plan is done");
5344  return_value = eExpressionCompleted;
5345  } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5346  if (log)
5347  log->PutCString(
5348  "Process::RunThreadPlan(): thread plan was discarded");
5349  return_value = eExpressionDiscarded;
5350  } else {
5351  if (log)
5352  log->PutCString(
5353  "Process::RunThreadPlan(): thread plan stopped in mid course");
5354  if (options.DoesUnwindOnError() && thread_plan_sp) {
5355  if (log)
5356  log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5357  "'cause unwind_on_error is set.");
5358  thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5359  }
5360  }
5361  }
5362 
5363  // Thread we ran the function in may have gone away because we ran the
5364  // target Check that it's still there, and if it is put it back in the
5365  // context. Also restore the frame in the context if it is still present.
5366  thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5367  if (thread) {
5368  exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5369  }
5370 
5371  // Also restore the current process'es selected frame & thread, since this
5372  // function calling may be done behind the user's back.
5373 
5374  if (selected_tid != LLDB_INVALID_THREAD_ID) {
5375  if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5376  selected_stack_id.IsValid()) {
5377  // We were able to restore the selected thread, now restore the frame:
5378  std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5379  StackFrameSP old_frame_sp =
5380  GetTh