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