1 //===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <atomic>
10 #include <memory>
11 #include <mutex>
12 
13 #include "llvm/Support/ScopedPrinter.h"
14 #include "llvm/Support/Threading.h"
15 
16 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Breakpoint/StoppointCallbackContext.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleSpec.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Expression/DiagnosticManager.h"
25 #include "lldb/Expression/IRDynamicChecks.h"
26 #include "lldb/Expression/UserExpression.h"
27 #include "lldb/Expression/UtilityFunction.h"
28 #include "lldb/Host/ConnectionFileDescriptor.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"
35 #include "lldb/Host/ThreadLauncher.h"
36 #include "lldb/Interpreter/CommandInterpreter.h"
37 #include "lldb/Interpreter/OptionArgParser.h"
38 #include "lldb/Interpreter/OptionValueProperties.h"
39 #include "lldb/Symbol/Function.h"
40 #include "lldb/Symbol/Symbol.h"
41 #include "lldb/Target/ABI.h"
42 #include "lldb/Target/CPPLanguageRuntime.h"
43 #include "lldb/Target/DynamicLoader.h"
44 #include "lldb/Target/InstrumentationRuntime.h"
45 #include "lldb/Target/JITLoader.h"
46 #include "lldb/Target/JITLoaderList.h"
47 #include "lldb/Target/LanguageRuntime.h"
48 #include "lldb/Target/MemoryHistory.h"
49 #include "lldb/Target/MemoryRegionInfo.h"
50 #include "lldb/Target/ObjCLanguageRuntime.h"
51 #include "lldb/Target/OperatingSystem.h"
52 #include "lldb/Target/Platform.h"
53 #include "lldb/Target/Process.h"
54 #include "lldb/Target/RegisterContext.h"
55 #include "lldb/Target/StopInfo.h"
56 #include "lldb/Target/StructuredDataPlugin.h"
57 #include "lldb/Target/SystemRuntime.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"
62 #include "lldb/Target/ThreadPlanBase.h"
63 #include "lldb/Target/UnixSignals.h"
64 #include "lldb/Utility/Event.h"
65 #include "lldb/Utility/Log.h"
66 #include "lldb/Utility/NameMatches.h"
67 #include "lldb/Utility/ProcessInfo.h"
68 #include "lldb/Utility/SelectHelper.h"
69 #include "lldb/Utility/State.h"
70 
71 using namespace lldb;
72 using namespace lldb_private;
73 using namespace std::chrono;
74 
75 // Comment out line below to disable memory caching, overriding the process
76 // setting target.process.disable-memory-cache
77 #define ENABLE_MEMORY_CACHING
78 
79 #ifdef ENABLE_MEMORY_CACHING
80 #define DISABLE_MEM_CACHE_DEFAULT false
81 #else
82 #define DISABLE_MEM_CACHE_DEFAULT true
83 #endif
84 
85 class ProcessOptionValueProperties : public OptionValueProperties {
86 public:
87   ProcessOptionValueProperties(ConstString name)
88       : OptionValueProperties(name) {}
89 
90   // This constructor is used when creating ProcessOptionValueProperties when
91   // it is part of a new lldb_private::Process instance. It will copy all
92   // current global property values as needed
93   ProcessOptionValueProperties(ProcessProperties *global_properties)
94       : OptionValueProperties(*global_properties->GetValueProperties()) {}
95 
96   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
97                                      bool will_modify,
98                                      uint32_t idx) const override {
99     // When getting the value for a key from the process options, we will
100     // always try and grab the setting from the current process if there is
101     // one. Else we just use the one from this instance.
102     if (exe_ctx) {
103       Process *process = exe_ctx->GetProcessPtr();
104       if (process) {
105         ProcessOptionValueProperties *instance_properties =
106             static_cast<ProcessOptionValueProperties *>(
107                 process->GetValueProperties().get());
108         if (this != instance_properties)
109           return instance_properties->ProtectedGetPropertyAtIndex(idx);
110       }
111     }
112     return ProtectedGetPropertyAtIndex(idx);
113   }
114 };
115 
116 static constexpr PropertyDefinition g_properties[] = {
117     {"disable-memory-cache", OptionValue::eTypeBoolean, false,
118      DISABLE_MEM_CACHE_DEFAULT, nullptr, {},
119      "Disable reading and caching of memory in fixed-size units."},
120     {"extra-startup-command", OptionValue::eTypeArray, false,
121      OptionValue::eTypeString, nullptr, {},
122      "A list containing extra commands understood by the particular process "
123      "plugin used.  "
124      "For instance, to turn on debugserver logging set this to "
125      "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
126     {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
127      nullptr, {},
128      "If true, breakpoints will be ignored during expression evaluation."},
129     {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
130      nullptr, {}, "If true, errors in expression evaluation will unwind "
131                   "the stack back to the state before the call."},
132     {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
133      {}, "A path to a python OS plug-in module file that contains a "
134          "OperatingSystemPlugIn class."},
135     {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
136      nullptr, {},
137      "If true, stop when a shared library is loaded or unloaded."},
138     {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
139      {}, "If true, detach will attempt to keep the process stopped."},
140     {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
141      {}, "The memory cache line size"},
142     {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
143      {}, "If true, warn when stopped in code that is optimized where "
144          "stepping and variable availability may not behave as expected."},
145     {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
146      nullptr, {},
147      "If true, stop when a shared library is loaded or unloaded."},
148     {"utility-expression-timeout", OptionValue::eTypeUInt64, false, 15,
149      nullptr, {},
150      "The time in seconds to wait for LLDB-internal utility expressions."}
151 };
152 
153 enum {
154   ePropertyDisableMemCache,
155   ePropertyExtraStartCommand,
156   ePropertyIgnoreBreakpointsInExpressions,
157   ePropertyUnwindOnErrorInExpressions,
158   ePropertyPythonOSPluginPath,
159   ePropertyStopOnSharedLibraryEvents,
160   ePropertyDetachKeepsStopped,
161   ePropertyMemCacheLineSize,
162   ePropertyWarningOptimization,
163   ePropertyStopOnExec,
164   ePropertyUtilityExpressionTimeout,
165 };
166 
167 ProcessProperties::ProcessProperties(lldb_private::Process *process)
168     : Properties(),
169       m_process(process) // Can be nullptr for global ProcessProperties
170 {
171   if (process == nullptr) {
172     // Global process properties, set them up one time
173     m_collection_sp =
174         std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
175     m_collection_sp->Initialize(g_properties);
176     m_collection_sp->AppendProperty(
177         ConstString("thread"), ConstString("Settings specific to threads."),
178         true, Thread::GetGlobalProperties()->GetValueProperties());
179   } else {
180     m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
181         Process::GetGlobalProperties().get());
182     m_collection_sp->SetValueChangedCallback(
183         ePropertyPythonOSPluginPath,
184         ProcessProperties::OptionValueChangedCallback, this);
185   }
186 }
187 
188 ProcessProperties::~ProcessProperties() = default;
189 
190 void ProcessProperties::OptionValueChangedCallback(void *baton,
191                                                    OptionValue *option_value) {
192   ProcessProperties *properties = (ProcessProperties *)baton;
193   if (properties->m_process)
194     properties->m_process->LoadOperatingSystemPlugin(true);
195 }
196 
197 bool ProcessProperties::GetDisableMemoryCache() const {
198   const uint32_t idx = ePropertyDisableMemCache;
199   return m_collection_sp->GetPropertyAtIndexAsBoolean(
200       nullptr, idx, g_properties[idx].default_uint_value != 0);
201 }
202 
203 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
204   const uint32_t idx = ePropertyMemCacheLineSize;
205   return m_collection_sp->GetPropertyAtIndexAsUInt64(
206       nullptr, idx, g_properties[idx].default_uint_value);
207 }
208 
209 Args ProcessProperties::GetExtraStartupCommands() const {
210   Args args;
211   const uint32_t idx = ePropertyExtraStartCommand;
212   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
213   return args;
214 }
215 
216 void ProcessProperties::SetExtraStartupCommands(const Args &args) {
217   const uint32_t idx = ePropertyExtraStartCommand;
218   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
219 }
220 
221 FileSpec ProcessProperties::GetPythonOSPluginPath() const {
222   const uint32_t idx = ePropertyPythonOSPluginPath;
223   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
224 }
225 
226 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
227   const uint32_t idx = ePropertyPythonOSPluginPath;
228   m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
229 }
230 
231 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
232   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
233   return m_collection_sp->GetPropertyAtIndexAsBoolean(
234       nullptr, idx, g_properties[idx].default_uint_value != 0);
235 }
236 
237 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
238   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
239   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
240 }
241 
242 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
243   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
244   return m_collection_sp->GetPropertyAtIndexAsBoolean(
245       nullptr, idx, g_properties[idx].default_uint_value != 0);
246 }
247 
248 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
249   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
250   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
251 }
252 
253 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
254   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
255   return m_collection_sp->GetPropertyAtIndexAsBoolean(
256       nullptr, idx, g_properties[idx].default_uint_value != 0);
257 }
258 
259 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
260   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
261   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
262 }
263 
264 bool ProcessProperties::GetDetachKeepsStopped() const {
265   const uint32_t idx = ePropertyDetachKeepsStopped;
266   return m_collection_sp->GetPropertyAtIndexAsBoolean(
267       nullptr, idx, g_properties[idx].default_uint_value != 0);
268 }
269 
270 void ProcessProperties::SetDetachKeepsStopped(bool stop) {
271   const uint32_t idx = ePropertyDetachKeepsStopped;
272   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
273 }
274 
275 bool ProcessProperties::GetWarningsOptimization() const {
276   const uint32_t idx = ePropertyWarningOptimization;
277   return m_collection_sp->GetPropertyAtIndexAsBoolean(
278       nullptr, idx, g_properties[idx].default_uint_value != 0);
279 }
280 
281 bool ProcessProperties::GetStopOnExec() const {
282   const uint32_t idx = ePropertyStopOnExec;
283   return m_collection_sp->GetPropertyAtIndexAsBoolean(
284       nullptr, idx, g_properties[idx].default_uint_value != 0);
285 }
286 
287 std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
288   const uint32_t idx = ePropertyUtilityExpressionTimeout;
289   uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
290      nullptr, idx, g_properties[idx].default_uint_value);
291   return std::chrono::seconds(value);
292 }
293 
294 Status ProcessLaunchCommandOptions::SetOptionValue(
295     uint32_t option_idx, llvm::StringRef option_arg,
296     ExecutionContext *execution_context) {
297   Status error;
298   const int short_option = m_getopt_table[option_idx].val;
299 
300   switch (short_option) {
301   case 's': // Stop at program entry point
302     launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
303     break;
304 
305   case 'i': // STDIN for read only
306   {
307     FileAction action;
308     if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
309       launch_info.AppendFileAction(action);
310     break;
311   }
312 
313   case 'o': // Open STDOUT for write only
314   {
315     FileAction action;
316     if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
317       launch_info.AppendFileAction(action);
318     break;
319   }
320 
321   case 'e': // STDERR for write only
322   {
323     FileAction action;
324     if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
325       launch_info.AppendFileAction(action);
326     break;
327   }
328 
329   case 'p': // Process plug-in name
330     launch_info.SetProcessPluginName(option_arg);
331     break;
332 
333   case 'n': // Disable STDIO
334   {
335     FileAction action;
336     const FileSpec dev_null(FileSystem::DEV_NULL);
337     if (action.Open(STDIN_FILENO, dev_null, true, false))
338       launch_info.AppendFileAction(action);
339     if (action.Open(STDOUT_FILENO, dev_null, false, true))
340       launch_info.AppendFileAction(action);
341     if (action.Open(STDERR_FILENO, dev_null, false, true))
342       launch_info.AppendFileAction(action);
343     break;
344   }
345 
346   case 'w':
347     launch_info.SetWorkingDirectory(FileSpec(option_arg));
348     break;
349 
350   case 't': // Open process in new terminal window
351     launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
352     break;
353 
354   case 'a': {
355     TargetSP target_sp =
356         execution_context ? execution_context->GetTargetSP() : TargetSP();
357     PlatformSP platform_sp =
358         target_sp ? target_sp->GetPlatform() : PlatformSP();
359     launch_info.GetArchitecture() =
360         Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
361   } break;
362 
363   case 'A': // Disable ASLR.
364   {
365     bool success;
366     const bool disable_aslr_arg =
367         OptionArgParser::ToBoolean(option_arg, true, &success);
368     if (success)
369       disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
370     else
371       error.SetErrorStringWithFormat(
372           "Invalid boolean value for disable-aslr option: '%s'",
373           option_arg.empty() ? "<null>" : option_arg.str().c_str());
374     break;
375   }
376 
377   case 'X': // shell expand args.
378   {
379     bool success;
380     const bool expand_args =
381         OptionArgParser::ToBoolean(option_arg, true, &success);
382     if (success)
383       launch_info.SetShellExpandArguments(expand_args);
384     else
385       error.SetErrorStringWithFormat(
386           "Invalid boolean value for shell-expand-args option: '%s'",
387           option_arg.empty() ? "<null>" : option_arg.str().c_str());
388     break;
389   }
390 
391   case 'c':
392     if (!option_arg.empty())
393       launch_info.SetShell(FileSpec(option_arg));
394     else
395       launch_info.SetShell(HostInfo::GetDefaultShell());
396     break;
397 
398   case 'v':
399     launch_info.GetEnvironment().insert(option_arg);
400     break;
401 
402   default:
403     error.SetErrorStringWithFormat("unrecognized short option character '%c'",
404                                    short_option);
405     break;
406   }
407   return error;
408 }
409 
410 static constexpr OptionDefinition g_process_launch_options[] = {
411     {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
412      nullptr, {}, 0, eArgTypeNone,
413      "Stop at the entry point of the program when launching a process."},
414     {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
415      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
416      "Set whether to disable address space layout randomization when launching "
417      "a process."},
418     {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
419      nullptr, {}, 0, eArgTypePlugin,
420      "Name of the process plugin you want to use."},
421     {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
422      OptionParser::eRequiredArgument, nullptr, {}, 0,
423      eArgTypeDirectoryName,
424      "Set the current working directory to <path> when running the inferior."},
425     {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
426      nullptr, {}, 0, eArgTypeArchitecture,
427      "Set the architecture for the process to launch when ambiguous."},
428     {LLDB_OPT_SET_ALL, false, "environment", 'v',
429      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
430      "Specify an environment variable name/value string (--environment "
431      "NAME=VALUE). Can be specified multiple times for subsequent environment "
432      "entries."},
433     {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
434      OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
435      "Run the process in a shell (not supported on all platforms)."},
436 
437     {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
438      nullptr, {}, 0, eArgTypeFilename,
439      "Redirect stdin for the process to <filename>."},
440     {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
441      nullptr, {}, 0, eArgTypeFilename,
442      "Redirect stdout for the process to <filename>."},
443     {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
444      nullptr, {}, 0, eArgTypeFilename,
445      "Redirect stderr for the process to <filename>."},
446 
447     {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
448      {}, 0, eArgTypeNone,
449      "Start the process in a terminal (not supported on all platforms)."},
450 
451     {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
452      {}, 0, eArgTypeNone,
453      "Do not set up for terminal I/O to go to running process."},
454     {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
455      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
456      "Set whether to shell expand arguments to the process when launching."},
457 };
458 
459 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
460   return llvm::makeArrayRef(g_process_launch_options);
461 }
462 
463 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
464                               llvm::StringRef plugin_name,
465                               ListenerSP listener_sp,
466                               const FileSpec *crash_file_path) {
467   static uint32_t g_process_unique_id = 0;
468 
469   ProcessSP process_sp;
470   ProcessCreateInstance create_callback = nullptr;
471   if (!plugin_name.empty()) {
472     ConstString const_plugin_name(plugin_name);
473     create_callback =
474         PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
475     if (create_callback) {
476       process_sp = create_callback(target_sp, listener_sp, crash_file_path);
477       if (process_sp) {
478         if (process_sp->CanDebug(target_sp, true)) {
479           process_sp->m_process_unique_id = ++g_process_unique_id;
480         } else
481           process_sp.reset();
482       }
483     }
484   } else {
485     for (uint32_t idx = 0;
486          (create_callback =
487               PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
488          ++idx) {
489       process_sp = create_callback(target_sp, listener_sp, crash_file_path);
490       if (process_sp) {
491         if (process_sp->CanDebug(target_sp, false)) {
492           process_sp->m_process_unique_id = ++g_process_unique_id;
493           break;
494         } else
495           process_sp.reset();
496       }
497     }
498   }
499   return process_sp;
500 }
501 
502 ConstString &Process::GetStaticBroadcasterClass() {
503   static ConstString class_name("lldb.process");
504   return class_name;
505 }
506 
507 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
508     : Process(target_sp, listener_sp,
509               UnixSignals::Create(HostInfo::GetArchitecture())) {
510   // This constructor just delegates to the full Process constructor,
511   // defaulting to using the Host's UnixSignals.
512 }
513 
514 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
515                  const UnixSignalsSP &unix_signals_sp)
516     : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
517       Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
518                   Process::GetStaticBroadcasterClass().AsCString()),
519       m_target_wp(target_sp), m_public_state(eStateUnloaded),
520       m_private_state(eStateUnloaded),
521       m_private_state_broadcaster(nullptr,
522                                   "lldb.process.internal_state_broadcaster"),
523       m_private_state_control_broadcaster(
524           nullptr, "lldb.process.internal_state_control_broadcaster"),
525       m_private_state_listener_sp(
526           Listener::MakeListener("lldb.process.internal_state_listener")),
527       m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
528       m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
529       m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
530       m_thread_list(this), m_extended_thread_list(this),
531       m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
532       m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
533       m_breakpoint_site_list(), m_dynamic_checkers_up(),
534       m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
535       m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
536       m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
537       m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
538       m_memory_cache(*this), m_allocated_memory_cache(*this),
539       m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
540       m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
541       m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
542       m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
543       m_can_interpret_function_calls(false), m_warnings_issued(),
544       m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
545   CheckInWithManager();
546 
547   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
548   if (log)
549     log->Printf("%p Process::Process()", static_cast<void *>(this));
550 
551   if (!m_unix_signals_sp)
552     m_unix_signals_sp = std::make_shared<UnixSignals>();
553 
554   SetEventName(eBroadcastBitStateChanged, "state-changed");
555   SetEventName(eBroadcastBitInterrupt, "interrupt");
556   SetEventName(eBroadcastBitSTDOUT, "stdout-available");
557   SetEventName(eBroadcastBitSTDERR, "stderr-available");
558   SetEventName(eBroadcastBitProfileData, "profile-data-available");
559   SetEventName(eBroadcastBitStructuredData, "structured-data-available");
560 
561   m_private_state_control_broadcaster.SetEventName(
562       eBroadcastInternalStateControlStop, "control-stop");
563   m_private_state_control_broadcaster.SetEventName(
564       eBroadcastInternalStateControlPause, "control-pause");
565   m_private_state_control_broadcaster.SetEventName(
566       eBroadcastInternalStateControlResume, "control-resume");
567 
568   m_listener_sp->StartListeningForEvents(
569       this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
570                 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
571                 eBroadcastBitProfileData | eBroadcastBitStructuredData);
572 
573   m_private_state_listener_sp->StartListeningForEvents(
574       &m_private_state_broadcaster,
575       eBroadcastBitStateChanged | eBroadcastBitInterrupt);
576 
577   m_private_state_listener_sp->StartListeningForEvents(
578       &m_private_state_control_broadcaster,
579       eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
580           eBroadcastInternalStateControlResume);
581   // We need something valid here, even if just the default UnixSignalsSP.
582   assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
583 
584   // Allow the platform to override the default cache line size
585   OptionValueSP value_sp =
586       m_collection_sp
587           ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
588           ->GetValue();
589   uint32_t platform_cache_line_size =
590       target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
591   if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
592     value_sp->SetUInt64Value(platform_cache_line_size);
593 }
594 
595 Process::~Process() {
596   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
597   if (log)
598     log->Printf("%p Process::~Process()", static_cast<void *>(this));
599   StopPrivateStateThread();
600 
601   // ThreadList::Clear() will try to acquire this process's mutex, so
602   // explicitly clear the thread list here to ensure that the mutex is not
603   // destroyed before the thread list.
604   m_thread_list.Clear();
605 }
606 
607 const ProcessPropertiesSP &Process::GetGlobalProperties() {
608   // NOTE: intentional leak so we don't crash if global destructor chain gets
609   // called as other threads still use the result of this function
610   static ProcessPropertiesSP *g_settings_sp_ptr =
611       new ProcessPropertiesSP(new ProcessProperties(nullptr));
612   return *g_settings_sp_ptr;
613 }
614 
615 void Process::Finalize() {
616   m_finalizing = true;
617 
618   // Destroy this process if needed
619   switch (GetPrivateState()) {
620   case eStateConnected:
621   case eStateAttaching:
622   case eStateLaunching:
623   case eStateStopped:
624   case eStateRunning:
625   case eStateStepping:
626   case eStateCrashed:
627   case eStateSuspended:
628     Destroy(false);
629     break;
630 
631   case eStateInvalid:
632   case eStateUnloaded:
633   case eStateDetached:
634   case eStateExited:
635     break;
636   }
637 
638   // Clear our broadcaster before we proceed with destroying
639   Broadcaster::Clear();
640 
641   // Do any cleanup needed prior to being destructed... Subclasses that
642   // override this method should call this superclass method as well.
643 
644   // We need to destroy the loader before the derived Process class gets
645   // destroyed since it is very likely that undoing the loader will require
646   // access to the real process.
647   m_dynamic_checkers_up.reset();
648   m_abi_sp.reset();
649   m_os_up.reset();
650   m_system_runtime_up.reset();
651   m_dyld_up.reset();
652   m_jit_loaders_up.reset();
653   m_thread_list_real.Destroy();
654   m_thread_list.Destroy();
655   m_extended_thread_list.Destroy();
656   m_queue_list.Clear();
657   m_queue_list_stop_id = 0;
658   std::vector<Notifications> empty_notifications;
659   m_notifications.swap(empty_notifications);
660   m_image_tokens.clear();
661   m_memory_cache.Clear();
662   m_allocated_memory_cache.Clear();
663   m_language_runtimes.clear();
664   m_instrumentation_runtimes.clear();
665   m_next_event_action_up.reset();
666   // Clear the last natural stop ID since it has a strong reference to this
667   // process
668   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
669   //#ifdef LLDB_CONFIGURATION_DEBUG
670   //    StreamFile s(stdout, false);
671   //    EventSP event_sp;
672   //    while (m_private_state_listener_sp->GetNextEvent(event_sp))
673   //    {
674   //        event_sp->Dump (&s);
675   //        s.EOL();
676   //    }
677   //#endif
678   // We have to be very careful here as the m_private_state_listener might
679   // contain events that have ProcessSP values in them which can keep this
680   // process around forever. These events need to be cleared out.
681   m_private_state_listener_sp->Clear();
682   m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
683   m_public_run_lock.SetStopped();
684   m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
685   m_private_run_lock.SetStopped();
686   m_structured_data_plugin_map.clear();
687   m_finalize_called = true;
688 }
689 
690 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
691   m_notifications.push_back(callbacks);
692   if (callbacks.initialize != nullptr)
693     callbacks.initialize(callbacks.baton, this);
694 }
695 
696 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
697   std::vector<Notifications>::iterator pos, end = m_notifications.end();
698   for (pos = m_notifications.begin(); pos != end; ++pos) {
699     if (pos->baton == callbacks.baton &&
700         pos->initialize == callbacks.initialize &&
701         pos->process_state_changed == callbacks.process_state_changed) {
702       m_notifications.erase(pos);
703       return true;
704     }
705   }
706   return false;
707 }
708 
709 void Process::SynchronouslyNotifyStateChanged(StateType state) {
710   std::vector<Notifications>::iterator notification_pos,
711       notification_end = m_notifications.end();
712   for (notification_pos = m_notifications.begin();
713        notification_pos != notification_end; ++notification_pos) {
714     if (notification_pos->process_state_changed)
715       notification_pos->process_state_changed(notification_pos->baton, this,
716                                               state);
717   }
718 }
719 
720 // FIXME: We need to do some work on events before the general Listener sees
721 // them.
722 // For instance if we are continuing from a breakpoint, we need to ensure that
723 // we do the little "insert real insn, step & stop" trick.  But we can't do
724 // that when the event is delivered by the broadcaster - since that is done on
725 // the thread that is waiting for new events, so if we needed more than one
726 // event for our handling, we would stall.  So instead we do it when we fetch
727 // the event off of the queue.
728 //
729 
730 StateType Process::GetNextEvent(EventSP &event_sp) {
731   StateType state = eStateInvalid;
732 
733   if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
734                                             std::chrono::seconds(0)) &&
735       event_sp)
736     state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
737 
738   return state;
739 }
740 
741 void Process::SyncIOHandler(uint32_t iohandler_id,
742                             const Timeout<std::micro> &timeout) {
743   // don't sync (potentially context switch) in case where there is no process
744   // IO
745   if (!m_process_input_reader)
746     return;
747 
748   auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
749 
750   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
751   if (Result) {
752     LLDB_LOG(
753         log,
754         "waited from m_iohandler_sync to change from {0}. New value is {1}.",
755         iohandler_id, *Result);
756   } else {
757     LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
758              iohandler_id);
759   }
760 }
761 
762 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
763                                         EventSP *event_sp_ptr, bool wait_always,
764                                         ListenerSP hijack_listener_sp,
765                                         Stream *stream, bool use_run_lock) {
766   // We can't just wait for a "stopped" event, because the stopped event may
767   // have restarted the target. We have to actually check each event, and in
768   // the case of a stopped event check the restarted flag on the event.
769   if (event_sp_ptr)
770     event_sp_ptr->reset();
771   StateType state = GetState();
772   // If we are exited or detached, we won't ever get back to any other valid
773   // state...
774   if (state == eStateDetached || state == eStateExited)
775     return state;
776 
777   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
778   LLDB_LOG(log, "timeout = {0}", timeout);
779 
780   if (!wait_always && StateIsStoppedState(state, true) &&
781       StateIsStoppedState(GetPrivateState(), true)) {
782     if (log)
783       log->Printf("Process::%s returning without waiting for events; process "
784                   "private and public states are already 'stopped'.",
785                   __FUNCTION__);
786     // We need to toggle the run lock as this won't get done in
787     // SetPublicState() if the process is hijacked.
788     if (hijack_listener_sp && use_run_lock)
789       m_public_run_lock.SetStopped();
790     return state;
791   }
792 
793   while (state != eStateInvalid) {
794     EventSP event_sp;
795     state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
796     if (event_sp_ptr && event_sp)
797       *event_sp_ptr = event_sp;
798 
799     bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
800     Process::HandleProcessStateChangedEvent(event_sp, stream,
801                                             pop_process_io_handler);
802 
803     switch (state) {
804     case eStateCrashed:
805     case eStateDetached:
806     case eStateExited:
807     case eStateUnloaded:
808       // We need to toggle the run lock as this won't get done in
809       // SetPublicState() if the process is hijacked.
810       if (hijack_listener_sp && use_run_lock)
811         m_public_run_lock.SetStopped();
812       return state;
813     case eStateStopped:
814       if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
815         continue;
816       else {
817         // We need to toggle the run lock as this won't get done in
818         // SetPublicState() if the process is hijacked.
819         if (hijack_listener_sp && use_run_lock)
820           m_public_run_lock.SetStopped();
821         return state;
822       }
823     default:
824       continue;
825     }
826   }
827   return state;
828 }
829 
830 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
831                                              Stream *stream,
832                                              bool &pop_process_io_handler) {
833   const bool handle_pop = pop_process_io_handler;
834 
835   pop_process_io_handler = false;
836   ProcessSP process_sp =
837       Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
838 
839   if (!process_sp)
840     return false;
841 
842   StateType event_state =
843       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
844   if (event_state == eStateInvalid)
845     return false;
846 
847   switch (event_state) {
848   case eStateInvalid:
849   case eStateUnloaded:
850   case eStateAttaching:
851   case eStateLaunching:
852   case eStateStepping:
853   case eStateDetached:
854     if (stream)
855       stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
856                      StateAsCString(event_state));
857     if (event_state == eStateDetached)
858       pop_process_io_handler = true;
859     break;
860 
861   case eStateConnected:
862   case eStateRunning:
863     // Don't be chatty when we run...
864     break;
865 
866   case eStateExited:
867     if (stream)
868       process_sp->GetStatus(*stream);
869     pop_process_io_handler = true;
870     break;
871 
872   case eStateStopped:
873   case eStateCrashed:
874   case eStateSuspended:
875     // Make sure the program hasn't been auto-restarted:
876     if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
877       if (stream) {
878         size_t num_reasons =
879             Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
880         if (num_reasons > 0) {
881           // FIXME: Do we want to report this, or would that just be annoyingly
882           // chatty?
883           if (num_reasons == 1) {
884             const char *reason =
885                 Process::ProcessEventData::GetRestartedReasonAtIndex(
886                     event_sp.get(), 0);
887             stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
888                            process_sp->GetID(),
889                            reason ? reason : "<UNKNOWN REASON>");
890           } else {
891             stream->Printf("Process %" PRIu64
892                            " stopped and restarted, reasons:\n",
893                            process_sp->GetID());
894 
895             for (size_t i = 0; i < num_reasons; i++) {
896               const char *reason =
897                   Process::ProcessEventData::GetRestartedReasonAtIndex(
898                       event_sp.get(), i);
899               stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
900             }
901           }
902         }
903       }
904     } else {
905       StopInfoSP curr_thread_stop_info_sp;
906       // Lock the thread list so it doesn't change on us, this is the scope for
907       // the locker:
908       {
909         ThreadList &thread_list = process_sp->GetThreadList();
910         std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
911 
912         ThreadSP curr_thread(thread_list.GetSelectedThread());
913         ThreadSP thread;
914         StopReason curr_thread_stop_reason = eStopReasonInvalid;
915         if (curr_thread) {
916           curr_thread_stop_reason = curr_thread->GetStopReason();
917           curr_thread_stop_info_sp = curr_thread->GetStopInfo();
918         }
919         if (!curr_thread || !curr_thread->IsValid() ||
920             curr_thread_stop_reason == eStopReasonInvalid ||
921             curr_thread_stop_reason == eStopReasonNone) {
922           // Prefer a thread that has just completed its plan over another
923           // thread as current thread.
924           ThreadSP plan_thread;
925           ThreadSP other_thread;
926 
927           const size_t num_threads = thread_list.GetSize();
928           size_t i;
929           for (i = 0; i < num_threads; ++i) {
930             thread = thread_list.GetThreadAtIndex(i);
931             StopReason thread_stop_reason = thread->GetStopReason();
932             switch (thread_stop_reason) {
933             case eStopReasonInvalid:
934             case eStopReasonNone:
935               break;
936 
937             case eStopReasonSignal: {
938               // Don't select a signal thread if we weren't going to stop at
939               // that signal.  We have to have had another reason for stopping
940               // here, and the user doesn't want to see this thread.
941               uint64_t signo = thread->GetStopInfo()->GetValue();
942               if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
943                 if (!other_thread)
944                   other_thread = thread;
945               }
946               break;
947             }
948             case eStopReasonTrace:
949             case eStopReasonBreakpoint:
950             case eStopReasonWatchpoint:
951             case eStopReasonException:
952             case eStopReasonExec:
953             case eStopReasonThreadExiting:
954             case eStopReasonInstrumentation:
955               if (!other_thread)
956                 other_thread = thread;
957               break;
958             case eStopReasonPlanComplete:
959               if (!plan_thread)
960                 plan_thread = thread;
961               break;
962             }
963           }
964           if (plan_thread)
965             thread_list.SetSelectedThreadByID(plan_thread->GetID());
966           else if (other_thread)
967             thread_list.SetSelectedThreadByID(other_thread->GetID());
968           else {
969             if (curr_thread && curr_thread->IsValid())
970               thread = curr_thread;
971             else
972               thread = thread_list.GetThreadAtIndex(0);
973 
974             if (thread)
975               thread_list.SetSelectedThreadByID(thread->GetID());
976           }
977         }
978       }
979       // Drop the ThreadList mutex by here, since GetThreadStatus below might
980       // have to run code, e.g. for Data formatters, and if we hold the
981       // ThreadList mutex, then the process is going to have a hard time
982       // restarting the process.
983       if (stream) {
984         Debugger &debugger = process_sp->GetTarget().GetDebugger();
985         if (debugger.GetTargetList().GetSelectedTarget().get() ==
986             &process_sp->GetTarget()) {
987           const bool only_threads_with_stop_reason = true;
988           const uint32_t start_frame = 0;
989           const uint32_t num_frames = 1;
990           const uint32_t num_frames_with_source = 1;
991           const bool stop_format = true;
992           process_sp->GetStatus(*stream);
993           process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
994                                       start_frame, num_frames,
995                                       num_frames_with_source,
996                                       stop_format);
997           if (curr_thread_stop_info_sp) {
998             lldb::addr_t crashing_address;
999             ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1000                 curr_thread_stop_info_sp, &crashing_address);
1001             if (valobj_sp) {
1002               const bool qualify_cxx_base_classes = false;
1003 
1004               const ValueObject::GetExpressionPathFormat format =
1005                   ValueObject::GetExpressionPathFormat::
1006                       eGetExpressionPathFormatHonorPointers;
1007               stream->PutCString("Likely cause: ");
1008               valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1009                                            format);
1010               stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1011             }
1012           }
1013         } else {
1014           uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1015               process_sp->GetTarget().shared_from_this());
1016           if (target_idx != UINT32_MAX)
1017             stream->Printf("Target %d: (", target_idx);
1018           else
1019             stream->Printf("Target <unknown index>: (");
1020           process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1021           stream->Printf(") stopped.\n");
1022         }
1023       }
1024 
1025       // Pop the process IO handler
1026       pop_process_io_handler = true;
1027     }
1028     break;
1029   }
1030 
1031   if (handle_pop && pop_process_io_handler)
1032     process_sp->PopProcessIOHandler();
1033 
1034   return true;
1035 }
1036 
1037 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1038   if (listener_sp) {
1039     return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1040                                               eBroadcastBitInterrupt);
1041   } else
1042     return false;
1043 }
1044 
1045 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
1046 
1047 StateType Process::GetStateChangedEvents(EventSP &event_sp,
1048                                          const Timeout<std::micro> &timeout,
1049                                          ListenerSP hijack_listener_sp) {
1050   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1051   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1052 
1053   ListenerSP listener_sp = hijack_listener_sp;
1054   if (!listener_sp)
1055     listener_sp = m_listener_sp;
1056 
1057   StateType state = eStateInvalid;
1058   if (listener_sp->GetEventForBroadcasterWithType(
1059           this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1060           timeout)) {
1061     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1062       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1063     else
1064       LLDB_LOG(log, "got no event or was interrupted.");
1065   }
1066 
1067   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
1068   return state;
1069 }
1070 
1071 Event *Process::PeekAtStateChangedEvents() {
1072   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1073 
1074   if (log)
1075     log->Printf("Process::%s...", __FUNCTION__);
1076 
1077   Event *event_ptr;
1078   event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1079       this, eBroadcastBitStateChanged);
1080   if (log) {
1081     if (event_ptr) {
1082       log->Printf(
1083           "Process::%s (event_ptr) => %s", __FUNCTION__,
1084           StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1085     } else {
1086       log->Printf("Process::%s no events found", __FUNCTION__);
1087     }
1088   }
1089   return event_ptr;
1090 }
1091 
1092 StateType
1093 Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1094                                       const Timeout<std::micro> &timeout) {
1095   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1096   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1097 
1098   StateType state = eStateInvalid;
1099   if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1100           &m_private_state_broadcaster,
1101           eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1102           timeout))
1103     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1104       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1105 
1106   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1107            state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1108   return state;
1109 }
1110 
1111 bool Process::GetEventsPrivate(EventSP &event_sp,
1112                                const Timeout<std::micro> &timeout,
1113                                bool control_only) {
1114   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1115   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1116 
1117   if (control_only)
1118     return m_private_state_listener_sp->GetEventForBroadcaster(
1119         &m_private_state_control_broadcaster, event_sp, timeout);
1120   else
1121     return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1122 }
1123 
1124 bool Process::IsRunning() const {
1125   return StateIsRunningState(m_public_state.GetValue());
1126 }
1127 
1128 int Process::GetExitStatus() {
1129   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1130 
1131   if (m_public_state.GetValue() == eStateExited)
1132     return m_exit_status;
1133   return -1;
1134 }
1135 
1136 const char *Process::GetExitDescription() {
1137   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1138 
1139   if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1140     return m_exit_string.c_str();
1141   return nullptr;
1142 }
1143 
1144 bool Process::SetExitStatus(int status, const char *cstr) {
1145   // Use a mutex to protect setting the exit status.
1146   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1147 
1148   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1149                                                   LIBLLDB_LOG_PROCESS));
1150   if (log)
1151     log->Printf(
1152         "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1153         status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1154         cstr ? "\"" : "");
1155 
1156   // We were already in the exited state
1157   if (m_private_state.GetValue() == eStateExited) {
1158     if (log)
1159       log->Printf("Process::SetExitStatus () ignoring exit status because "
1160                   "state was already set to eStateExited");
1161     return false;
1162   }
1163 
1164   m_exit_status = status;
1165   if (cstr)
1166     m_exit_string = cstr;
1167   else
1168     m_exit_string.clear();
1169 
1170   // Clear the last natural stop ID since it has a strong reference to this
1171   // process
1172   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1173 
1174   SetPrivateState(eStateExited);
1175 
1176   // Allow subclasses to do some cleanup
1177   DidExit();
1178 
1179   return true;
1180 }
1181 
1182 bool Process::IsAlive() {
1183   switch (m_private_state.GetValue()) {
1184   case eStateConnected:
1185   case eStateAttaching:
1186   case eStateLaunching:
1187   case eStateStopped:
1188   case eStateRunning:
1189   case eStateStepping:
1190   case eStateCrashed:
1191   case eStateSuspended:
1192     return true;
1193   default:
1194     return false;
1195   }
1196 }
1197 
1198 // This static callback can be used to watch for local child processes on the
1199 // current host. The child process exits, the process will be found in the
1200 // global target list (we want to be completely sure that the
1201 // lldb_private::Process doesn't go away before we can deliver the signal.
1202 bool Process::SetProcessExitStatus(
1203     lldb::pid_t pid, bool exited,
1204     int signo,      // Zero for no signal
1205     int exit_status // Exit value of process if signal is zero
1206     ) {
1207   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1208   if (log)
1209     log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1210                 ", exited=%i, signal=%i, exit_status=%i)\n",
1211                 pid, exited, signo, exit_status);
1212 
1213   if (exited) {
1214     TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1215     if (target_sp) {
1216       ProcessSP process_sp(target_sp->GetProcessSP());
1217       if (process_sp) {
1218         const char *signal_cstr = nullptr;
1219         if (signo)
1220           signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1221 
1222         process_sp->SetExitStatus(exit_status, signal_cstr);
1223       }
1224     }
1225     return true;
1226   }
1227   return false;
1228 }
1229 
1230 void Process::UpdateThreadListIfNeeded() {
1231   const uint32_t stop_id = GetStopID();
1232   if (m_thread_list.GetSize(false) == 0 ||
1233       stop_id != m_thread_list.GetStopID()) {
1234     const StateType state = GetPrivateState();
1235     if (StateIsStoppedState(state, true)) {
1236       std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1237       // m_thread_list does have its own mutex, but we need to hold onto the
1238       // mutex between the call to UpdateThreadList(...) and the
1239       // os->UpdateThreadList(...) so it doesn't change on us
1240       ThreadList &old_thread_list = m_thread_list;
1241       ThreadList real_thread_list(this);
1242       ThreadList new_thread_list(this);
1243       // Always update the thread list with the protocol specific thread list,
1244       // but only update if "true" is returned
1245       if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1246         // Don't call into the OperatingSystem to update the thread list if we
1247         // are shutting down, since that may call back into the SBAPI's,
1248         // requiring the API lock which is already held by whoever is shutting
1249         // us down, causing a deadlock.
1250         OperatingSystem *os = GetOperatingSystem();
1251         if (os && !m_destroy_in_process) {
1252           // Clear any old backing threads where memory threads might have been
1253           // backed by actual threads from the lldb_private::Process subclass
1254           size_t num_old_threads = old_thread_list.GetSize(false);
1255           for (size_t i = 0; i < num_old_threads; ++i)
1256             old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1257 
1258           // Turn off dynamic types to ensure we don't run any expressions.
1259           // Objective-C can run an expression to determine if a SBValue is a
1260           // dynamic type or not and we need to avoid this. OperatingSystem
1261           // plug-ins can't run expressions that require running code...
1262 
1263           Target &target = GetTarget();
1264           const lldb::DynamicValueType saved_prefer_dynamic =
1265               target.GetPreferDynamicValue();
1266           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1267             target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1268 
1269           // Now let the OperatingSystem plug-in update the thread list
1270 
1271           os->UpdateThreadList(
1272               old_thread_list, // Old list full of threads created by OS plug-in
1273               real_thread_list, // The actual thread list full of threads
1274                                 // created by each lldb_private::Process
1275                                 // subclass
1276               new_thread_list); // The new thread list that we will show to the
1277                                 // user that gets filled in
1278 
1279           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1280             target.SetPreferDynamicValue(saved_prefer_dynamic);
1281         } else {
1282           // No OS plug-in, the new thread list is the same as the real thread
1283           // list
1284           new_thread_list = real_thread_list;
1285         }
1286 
1287         m_thread_list_real.Update(real_thread_list);
1288         m_thread_list.Update(new_thread_list);
1289         m_thread_list.SetStopID(stop_id);
1290 
1291         if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1292           // Clear any extended threads that we may have accumulated previously
1293           m_extended_thread_list.Clear();
1294           m_extended_thread_stop_id = GetLastNaturalStopID();
1295 
1296           m_queue_list.Clear();
1297           m_queue_list_stop_id = GetLastNaturalStopID();
1298         }
1299       }
1300     }
1301   }
1302 }
1303 
1304 void Process::UpdateQueueListIfNeeded() {
1305   if (m_system_runtime_up) {
1306     if (m_queue_list.GetSize() == 0 ||
1307         m_queue_list_stop_id != GetLastNaturalStopID()) {
1308       const StateType state = GetPrivateState();
1309       if (StateIsStoppedState(state, true)) {
1310         m_system_runtime_up->PopulateQueueList(m_queue_list);
1311         m_queue_list_stop_id = GetLastNaturalStopID();
1312       }
1313     }
1314   }
1315 }
1316 
1317 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1318   OperatingSystem *os = GetOperatingSystem();
1319   if (os)
1320     return os->CreateThread(tid, context);
1321   return ThreadSP();
1322 }
1323 
1324 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1325   return AssignIndexIDToThread(thread_id);
1326 }
1327 
1328 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1329   return (m_thread_id_to_index_id_map.find(thread_id) !=
1330           m_thread_id_to_index_id_map.end());
1331 }
1332 
1333 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1334   uint32_t result = 0;
1335   std::map<uint64_t, uint32_t>::iterator iterator =
1336       m_thread_id_to_index_id_map.find(thread_id);
1337   if (iterator == m_thread_id_to_index_id_map.end()) {
1338     result = ++m_thread_index_id;
1339     m_thread_id_to_index_id_map[thread_id] = result;
1340   } else {
1341     result = iterator->second;
1342   }
1343 
1344   return result;
1345 }
1346 
1347 StateType Process::GetState() {
1348   return m_public_state.GetValue();
1349 }
1350 
1351 void Process::SetPublicState(StateType new_state, bool restarted) {
1352   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1353                                                   LIBLLDB_LOG_PROCESS));
1354   if (log)
1355     log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1356                 StateAsCString(new_state), restarted);
1357   const StateType old_state = m_public_state.GetValue();
1358   m_public_state.SetValue(new_state);
1359 
1360   // On the transition from Run to Stopped, we unlock the writer end of the run
1361   // lock.  The lock gets locked in Resume, which is the public API to tell the
1362   // program to run.
1363   if (!StateChangedIsExternallyHijacked()) {
1364     if (new_state == eStateDetached) {
1365       if (log)
1366         log->Printf(
1367             "Process::SetPublicState (%s) -- unlocking run lock for detach",
1368             StateAsCString(new_state));
1369       m_public_run_lock.SetStopped();
1370     } else {
1371       const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1372       const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1373       if ((old_state_is_stopped != new_state_is_stopped)) {
1374         if (new_state_is_stopped && !restarted) {
1375           if (log)
1376             log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1377                         StateAsCString(new_state));
1378           m_public_run_lock.SetStopped();
1379         }
1380       }
1381     }
1382   }
1383 }
1384 
1385 Status Process::Resume() {
1386   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1387                                                   LIBLLDB_LOG_PROCESS));
1388   if (log)
1389     log->Printf("Process::Resume -- locking run lock");
1390   if (!m_public_run_lock.TrySetRunning()) {
1391     Status error("Resume request failed - process still running.");
1392     if (log)
1393       log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1394     return error;
1395   }
1396   Status error = PrivateResume();
1397   if (!error.Success()) {
1398     // Undo running state change
1399     m_public_run_lock.SetStopped();
1400   }
1401   return error;
1402 }
1403 
1404 static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1405 
1406 Status Process::ResumeSynchronous(Stream *stream) {
1407   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1408                                                   LIBLLDB_LOG_PROCESS));
1409   if (log)
1410     log->Printf("Process::ResumeSynchronous -- locking run lock");
1411   if (!m_public_run_lock.TrySetRunning()) {
1412     Status error("Resume request failed - process still running.");
1413     if (log)
1414       log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1415     return error;
1416   }
1417 
1418   ListenerSP listener_sp(
1419       Listener::MakeListener(g_resume_sync_name));
1420   HijackProcessEvents(listener_sp);
1421 
1422   Status error = PrivateResume();
1423   if (error.Success()) {
1424     StateType state =
1425         WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
1426     const bool must_be_alive =
1427         false; // eStateExited is ok, so this must be false
1428     if (!StateIsStoppedState(state, must_be_alive))
1429       error.SetErrorStringWithFormat(
1430           "process not in stopped state after synchronous resume: %s",
1431           StateAsCString(state));
1432   } else {
1433     // Undo running state change
1434     m_public_run_lock.SetStopped();
1435   }
1436 
1437   // Undo the hijacking of process events...
1438   RestoreProcessEvents();
1439 
1440   return error;
1441 }
1442 
1443 bool Process::StateChangedIsExternallyHijacked() {
1444   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1445     const char *hijacking_name = GetHijackingListenerName();
1446     if (hijacking_name &&
1447         strcmp(hijacking_name, g_resume_sync_name))
1448       return true;
1449   }
1450   return false;
1451 }
1452 
1453 bool Process::StateChangedIsHijackedForSynchronousResume() {
1454   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1455     const char *hijacking_name = GetHijackingListenerName();
1456     if (hijacking_name &&
1457         strcmp(hijacking_name, g_resume_sync_name) == 0)
1458       return true;
1459   }
1460   return false;
1461 }
1462 
1463 StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
1464 
1465 void Process::SetPrivateState(StateType new_state) {
1466   if (m_finalize_called)
1467     return;
1468 
1469   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1470                                                   LIBLLDB_LOG_PROCESS));
1471   bool state_changed = false;
1472 
1473   if (log)
1474     log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1475 
1476   std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1477   std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1478 
1479   const StateType old_state = m_private_state.GetValueNoLock();
1480   state_changed = old_state != new_state;
1481 
1482   const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1483   const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1484   if (old_state_is_stopped != new_state_is_stopped) {
1485     if (new_state_is_stopped)
1486       m_private_run_lock.SetStopped();
1487     else
1488       m_private_run_lock.SetRunning();
1489   }
1490 
1491   if (state_changed) {
1492     m_private_state.SetValueNoLock(new_state);
1493     EventSP event_sp(
1494         new Event(eBroadcastBitStateChanged,
1495                   new ProcessEventData(shared_from_this(), new_state)));
1496     if (StateIsStoppedState(new_state, false)) {
1497       // Note, this currently assumes that all threads in the list stop when
1498       // the process stops.  In the future we will want to support a debugging
1499       // model where some threads continue to run while others are stopped.
1500       // When that happens we will either need a way for the thread list to
1501       // identify which threads are stopping or create a special thread list
1502       // containing only threads which actually stopped.
1503       //
1504       // The process plugin is responsible for managing the actual behavior of
1505       // the threads and should have stopped any threads that are going to stop
1506       // before we get here.
1507       m_thread_list.DidStop();
1508 
1509       m_mod_id.BumpStopID();
1510       if (!m_mod_id.IsLastResumeForUserExpression())
1511         m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1512       m_memory_cache.Clear();
1513       if (log)
1514         log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1515                     StateAsCString(new_state), m_mod_id.GetStopID());
1516     }
1517 
1518     // Use our target to get a shared pointer to ourselves...
1519     if (m_finalize_called && !PrivateStateThreadIsValid())
1520       BroadcastEvent(event_sp);
1521     else
1522       m_private_state_broadcaster.BroadcastEvent(event_sp);
1523   } else {
1524     if (log)
1525       log->Printf(
1526           "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1527           StateAsCString(new_state));
1528   }
1529 }
1530 
1531 void Process::SetRunningUserExpression(bool on) {
1532   m_mod_id.SetRunningUserExpression(on);
1533 }
1534 
1535 void Process::SetRunningUtilityFunction(bool on) {
1536   m_mod_id.SetRunningUtilityFunction(on);
1537 }
1538 
1539 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1540 
1541 const lldb::ABISP &Process::GetABI() {
1542   if (!m_abi_sp)
1543     m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1544   return m_abi_sp;
1545 }
1546 
1547 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1548                                              bool retry_if_null) {
1549   if (m_finalizing)
1550     return nullptr;
1551 
1552   LanguageRuntimeCollection::iterator pos;
1553   pos = m_language_runtimes.find(language);
1554   if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1555     lldb::LanguageRuntimeSP runtime_sp(
1556         LanguageRuntime::FindPlugin(this, language));
1557 
1558     m_language_runtimes[language] = runtime_sp;
1559     return runtime_sp.get();
1560   } else
1561     return (*pos).second.get();
1562 }
1563 
1564 CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1565   LanguageRuntime *runtime =
1566       GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1567   if (runtime != nullptr &&
1568       runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1569     return static_cast<CPPLanguageRuntime *>(runtime);
1570   return nullptr;
1571 }
1572 
1573 ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1574   LanguageRuntime *runtime =
1575       GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1576   if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1577     return static_cast<ObjCLanguageRuntime *>(runtime);
1578   return nullptr;
1579 }
1580 
1581 bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1582   if (m_finalizing)
1583     return false;
1584 
1585   if (in_value.IsDynamic())
1586     return false;
1587   LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1588 
1589   if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1590     LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1591     return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1592   }
1593 
1594   LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1595   if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1596     return true;
1597 
1598   LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1599   return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1600 }
1601 
1602 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1603   m_dynamic_checkers_up.reset(dynamic_checkers);
1604 }
1605 
1606 BreakpointSiteList &Process::GetBreakpointSiteList() {
1607   return m_breakpoint_site_list;
1608 }
1609 
1610 const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1611   return m_breakpoint_site_list;
1612 }
1613 
1614 void Process::DisableAllBreakpointSites() {
1615   m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1616     //        bp_site->SetEnabled(true);
1617     DisableBreakpointSite(bp_site);
1618   });
1619 }
1620 
1621 Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1622   Status error(DisableBreakpointSiteByID(break_id));
1623 
1624   if (error.Success())
1625     m_breakpoint_site_list.Remove(break_id);
1626 
1627   return error;
1628 }
1629 
1630 Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1631   Status error;
1632   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1633   if (bp_site_sp) {
1634     if (bp_site_sp->IsEnabled())
1635       error = DisableBreakpointSite(bp_site_sp.get());
1636   } else {
1637     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1638                                    break_id);
1639   }
1640 
1641   return error;
1642 }
1643 
1644 Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1645   Status error;
1646   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1647   if (bp_site_sp) {
1648     if (!bp_site_sp->IsEnabled())
1649       error = EnableBreakpointSite(bp_site_sp.get());
1650   } else {
1651     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1652                                    break_id);
1653   }
1654   return error;
1655 }
1656 
1657 lldb::break_id_t
1658 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1659                               bool use_hardware) {
1660   addr_t load_addr = LLDB_INVALID_ADDRESS;
1661 
1662   bool show_error = true;
1663   switch (GetState()) {
1664   case eStateInvalid:
1665   case eStateUnloaded:
1666   case eStateConnected:
1667   case eStateAttaching:
1668   case eStateLaunching:
1669   case eStateDetached:
1670   case eStateExited:
1671     show_error = false;
1672     break;
1673 
1674   case eStateStopped:
1675   case eStateRunning:
1676   case eStateStepping:
1677   case eStateCrashed:
1678   case eStateSuspended:
1679     show_error = IsAlive();
1680     break;
1681   }
1682 
1683   // Reset the IsIndirect flag here, in case the location changes from pointing
1684   // to a indirect symbol to a regular symbol.
1685   owner->SetIsIndirect(false);
1686 
1687   if (owner->ShouldResolveIndirectFunctions()) {
1688     Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1689     if (symbol && symbol->IsIndirect()) {
1690       Status error;
1691       Address symbol_address = symbol->GetAddress();
1692       load_addr = ResolveIndirectFunction(&symbol_address, error);
1693       if (!error.Success() && show_error) {
1694         GetTarget().GetDebugger().GetErrorFile()->Printf(
1695             "warning: failed to resolve indirect function at 0x%" PRIx64
1696             " for breakpoint %i.%i: %s\n",
1697             symbol->GetLoadAddress(&GetTarget()),
1698             owner->GetBreakpoint().GetID(), owner->GetID(),
1699             error.AsCString() ? error.AsCString() : "unknown error");
1700         return LLDB_INVALID_BREAK_ID;
1701       }
1702       Address resolved_address(load_addr);
1703       load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1704       owner->SetIsIndirect(true);
1705     } else
1706       load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1707   } else
1708     load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1709 
1710   if (load_addr != LLDB_INVALID_ADDRESS) {
1711     BreakpointSiteSP bp_site_sp;
1712 
1713     // Look up this breakpoint site.  If it exists, then add this new owner,
1714     // otherwise create a new breakpoint site and add it.
1715 
1716     bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1717 
1718     if (bp_site_sp) {
1719       bp_site_sp->AddOwner(owner);
1720       owner->SetBreakpointSite(bp_site_sp);
1721       return bp_site_sp->GetID();
1722     } else {
1723       bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1724                                           load_addr, use_hardware));
1725       if (bp_site_sp) {
1726         Status error = EnableBreakpointSite(bp_site_sp.get());
1727         if (error.Success()) {
1728           owner->SetBreakpointSite(bp_site_sp);
1729           return m_breakpoint_site_list.Add(bp_site_sp);
1730         } else {
1731           if (show_error || use_hardware) {
1732             // Report error for setting breakpoint...
1733             GetTarget().GetDebugger().GetErrorFile()->Printf(
1734                 "warning: failed to set breakpoint site at 0x%" PRIx64
1735                 " for breakpoint %i.%i: %s\n",
1736                 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1737                 error.AsCString() ? error.AsCString() : "unknown error");
1738           }
1739         }
1740       }
1741     }
1742   }
1743   // We failed to enable the breakpoint
1744   return LLDB_INVALID_BREAK_ID;
1745 }
1746 
1747 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1748                                             lldb::user_id_t owner_loc_id,
1749                                             BreakpointSiteSP &bp_site_sp) {
1750   uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1751   if (num_owners == 0) {
1752     // Don't try to disable the site if we don't have a live process anymore.
1753     if (IsAlive())
1754       DisableBreakpointSite(bp_site_sp.get());
1755     m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1756   }
1757 }
1758 
1759 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1760                                                   uint8_t *buf) const {
1761   size_t bytes_removed = 0;
1762   BreakpointSiteList bp_sites_in_range;
1763 
1764   if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1765                                          bp_sites_in_range)) {
1766     bp_sites_in_range.ForEach([bp_addr, size,
1767                                buf](BreakpointSite *bp_site) -> void {
1768       if (bp_site->GetType() == BreakpointSite::eSoftware) {
1769         addr_t intersect_addr;
1770         size_t intersect_size;
1771         size_t opcode_offset;
1772         if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1773                                      &intersect_size, &opcode_offset)) {
1774           assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1775           assert(bp_addr < intersect_addr + intersect_size &&
1776                  intersect_addr + intersect_size <= bp_addr + size);
1777           assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1778           size_t buf_offset = intersect_addr - bp_addr;
1779           ::memcpy(buf + buf_offset,
1780                    bp_site->GetSavedOpcodeBytes() + opcode_offset,
1781                    intersect_size);
1782         }
1783       }
1784     });
1785   }
1786   return bytes_removed;
1787 }
1788 
1789 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1790   PlatformSP platform_sp(GetTarget().GetPlatform());
1791   if (platform_sp)
1792     return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1793   return 0;
1794 }
1795 
1796 Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1797   Status error;
1798   assert(bp_site != nullptr);
1799   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1800   const addr_t bp_addr = bp_site->GetLoadAddress();
1801   if (log)
1802     log->Printf(
1803         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1804         bp_site->GetID(), (uint64_t)bp_addr);
1805   if (bp_site->IsEnabled()) {
1806     if (log)
1807       log->Printf(
1808           "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1809           " -- already enabled",
1810           bp_site->GetID(), (uint64_t)bp_addr);
1811     return error;
1812   }
1813 
1814   if (bp_addr == LLDB_INVALID_ADDRESS) {
1815     error.SetErrorString("BreakpointSite contains an invalid load address.");
1816     return error;
1817   }
1818   // Ask the lldb::Process subclass to fill in the correct software breakpoint
1819   // trap for the breakpoint site
1820   const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1821 
1822   if (bp_opcode_size == 0) {
1823     error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1824                                    "returned zero, unable to get breakpoint "
1825                                    "trap for address 0x%" PRIx64,
1826                                    bp_addr);
1827   } else {
1828     const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1829 
1830     if (bp_opcode_bytes == nullptr) {
1831       error.SetErrorString(
1832           "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1833       return error;
1834     }
1835 
1836     // Save the original opcode by reading it
1837     if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1838                      error) == bp_opcode_size) {
1839       // Write a software breakpoint in place of the original opcode
1840       if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1841           bp_opcode_size) {
1842         uint8_t verify_bp_opcode_bytes[64];
1843         if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1844                          error) == bp_opcode_size) {
1845           if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1846                        bp_opcode_size) == 0) {
1847             bp_site->SetEnabled(true);
1848             bp_site->SetType(BreakpointSite::eSoftware);
1849             if (log)
1850               log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
1851                           "addr = 0x%" PRIx64 " -- SUCCESS",
1852                           bp_site->GetID(), (uint64_t)bp_addr);
1853           } else
1854             error.SetErrorString(
1855                 "failed to verify the breakpoint trap in memory.");
1856         } else
1857           error.SetErrorString(
1858               "Unable to read memory to verify breakpoint trap.");
1859       } else
1860         error.SetErrorString("Unable to write breakpoint trap to memory.");
1861     } else
1862       error.SetErrorString("Unable to read memory at breakpoint address.");
1863   }
1864   if (log && error.Fail())
1865     log->Printf(
1866         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1867         " -- FAILED: %s",
1868         bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1869   return error;
1870 }
1871 
1872 Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1873   Status error;
1874   assert(bp_site != nullptr);
1875   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1876   addr_t bp_addr = bp_site->GetLoadAddress();
1877   lldb::user_id_t breakID = bp_site->GetID();
1878   if (log)
1879     log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1880                 ") addr = 0x%" PRIx64,
1881                 breakID, (uint64_t)bp_addr);
1882 
1883   if (bp_site->IsHardware()) {
1884     error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1885   } else if (bp_site->IsEnabled()) {
1886     const size_t break_op_size = bp_site->GetByteSize();
1887     const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1888     if (break_op_size > 0) {
1889       // Clear a software breakpoint instruction
1890       uint8_t curr_break_op[8];
1891       assert(break_op_size <= sizeof(curr_break_op));
1892       bool break_op_found = false;
1893 
1894       // Read the breakpoint opcode
1895       if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1896           break_op_size) {
1897         bool verify = false;
1898         // Make sure the breakpoint opcode exists at this address
1899         if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1900           break_op_found = true;
1901           // We found a valid breakpoint opcode at this address, now restore
1902           // the saved opcode.
1903           if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1904                             break_op_size, error) == break_op_size) {
1905             verify = true;
1906           } else
1907             error.SetErrorString(
1908                 "Memory write failed when restoring original opcode.");
1909         } else {
1910           error.SetErrorString(
1911               "Original breakpoint trap is no longer in memory.");
1912           // Set verify to true and so we can check if the original opcode has
1913           // already been restored
1914           verify = true;
1915         }
1916 
1917         if (verify) {
1918           uint8_t verify_opcode[8];
1919           assert(break_op_size < sizeof(verify_opcode));
1920           // Verify that our original opcode made it back to the inferior
1921           if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1922               break_op_size) {
1923             // compare the memory we just read with the original opcode
1924             if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1925                          break_op_size) == 0) {
1926               // SUCCESS
1927               bp_site->SetEnabled(false);
1928               if (log)
1929                 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
1930                             "addr = 0x%" PRIx64 " -- SUCCESS",
1931                             bp_site->GetID(), (uint64_t)bp_addr);
1932               return error;
1933             } else {
1934               if (break_op_found)
1935                 error.SetErrorString("Failed to restore original opcode.");
1936             }
1937           } else
1938             error.SetErrorString("Failed to read memory to verify that "
1939                                  "breakpoint trap was restored.");
1940         }
1941       } else
1942         error.SetErrorString(
1943             "Unable to read memory that should contain the breakpoint trap.");
1944     }
1945   } else {
1946     if (log)
1947       log->Printf(
1948           "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1949           " -- already disabled",
1950           bp_site->GetID(), (uint64_t)bp_addr);
1951     return error;
1952   }
1953 
1954   if (log)
1955     log->Printf(
1956         "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1957         " -- FAILED: %s",
1958         bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1959   return error;
1960 }
1961 
1962 // Uncomment to verify memory caching works after making changes to caching
1963 // code
1964 //#define VERIFY_MEMORY_READS
1965 
1966 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1967   error.Clear();
1968   if (!GetDisableMemoryCache()) {
1969 #if defined(VERIFY_MEMORY_READS)
1970     // Memory caching is enabled, with debug verification
1971 
1972     if (buf && size) {
1973       // Uncomment the line below to make sure memory caching is working.
1974       // I ran this through the test suite and got no assertions, so I am
1975       // pretty confident this is working well. If any changes are made to
1976       // memory caching, uncomment the line below and test your changes!
1977 
1978       // Verify all memory reads by using the cache first, then redundantly
1979       // reading the same memory from the inferior and comparing to make sure
1980       // everything is exactly the same.
1981       std::string verify_buf(size, '\0');
1982       assert(verify_buf.size() == size);
1983       const size_t cache_bytes_read =
1984           m_memory_cache.Read(this, addr, buf, size, error);
1985       Status verify_error;
1986       const size_t verify_bytes_read =
1987           ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1988                                  verify_buf.size(), verify_error);
1989       assert(cache_bytes_read == verify_bytes_read);
1990       assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1991       assert(verify_error.Success() == error.Success());
1992       return cache_bytes_read;
1993     }
1994     return 0;
1995 #else  // !defined(VERIFY_MEMORY_READS)
1996     // Memory caching is enabled, without debug verification
1997 
1998     return m_memory_cache.Read(addr, buf, size, error);
1999 #endif // defined (VERIFY_MEMORY_READS)
2000   } else {
2001     // Memory caching is disabled
2002 
2003     return ReadMemoryFromInferior(addr, buf, size, error);
2004   }
2005 }
2006 
2007 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2008                                       Status &error) {
2009   char buf[256];
2010   out_str.clear();
2011   addr_t curr_addr = addr;
2012   while (true) {
2013     size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2014     if (length == 0)
2015       break;
2016     out_str.append(buf, length);
2017     // If we got "length - 1" bytes, we didn't get the whole C string, we need
2018     // to read some more characters
2019     if (length == sizeof(buf) - 1)
2020       curr_addr += length;
2021     else
2022       break;
2023   }
2024   return out_str.size();
2025 }
2026 
2027 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2028                                      Status &error, size_t type_width) {
2029   size_t total_bytes_read = 0;
2030   if (dst && max_bytes && type_width && max_bytes >= type_width) {
2031     // Ensure a null terminator independent of the number of bytes that is
2032     // read.
2033     memset(dst, 0, max_bytes);
2034     size_t bytes_left = max_bytes - type_width;
2035 
2036     const char terminator[4] = {'\0', '\0', '\0', '\0'};
2037     assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2038                                                "string with more than 4 bytes "
2039                                                "per character!");
2040 
2041     addr_t curr_addr = addr;
2042     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2043     char *curr_dst = dst;
2044 
2045     error.Clear();
2046     while (bytes_left > 0 && error.Success()) {
2047       addr_t cache_line_bytes_left =
2048           cache_line_size - (curr_addr % cache_line_size);
2049       addr_t bytes_to_read =
2050           std::min<addr_t>(bytes_left, cache_line_bytes_left);
2051       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2052 
2053       if (bytes_read == 0)
2054         break;
2055 
2056       // Search for a null terminator of correct size and alignment in
2057       // bytes_read
2058       size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2059       for (size_t i = aligned_start;
2060            i + type_width <= total_bytes_read + bytes_read; i += type_width)
2061         if (::memcmp(&dst[i], terminator, type_width) == 0) {
2062           error.Clear();
2063           return i;
2064         }
2065 
2066       total_bytes_read += bytes_read;
2067       curr_dst += bytes_read;
2068       curr_addr += bytes_read;
2069       bytes_left -= bytes_read;
2070     }
2071   } else {
2072     if (max_bytes)
2073       error.SetErrorString("invalid arguments");
2074   }
2075   return total_bytes_read;
2076 }
2077 
2078 // Deprecated in favor of ReadStringFromMemory which has wchar support and
2079 // correct code to find null terminators.
2080 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2081                                       size_t dst_max_len,
2082                                       Status &result_error) {
2083   size_t total_cstr_len = 0;
2084   if (dst && dst_max_len) {
2085     result_error.Clear();
2086     // NULL out everything just to be safe
2087     memset(dst, 0, dst_max_len);
2088     Status error;
2089     addr_t curr_addr = addr;
2090     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2091     size_t bytes_left = dst_max_len - 1;
2092     char *curr_dst = dst;
2093 
2094     while (bytes_left > 0) {
2095       addr_t cache_line_bytes_left =
2096           cache_line_size - (curr_addr % cache_line_size);
2097       addr_t bytes_to_read =
2098           std::min<addr_t>(bytes_left, cache_line_bytes_left);
2099       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2100 
2101       if (bytes_read == 0) {
2102         result_error = error;
2103         dst[total_cstr_len] = '\0';
2104         break;
2105       }
2106       const size_t len = strlen(curr_dst);
2107 
2108       total_cstr_len += len;
2109 
2110       if (len < bytes_to_read)
2111         break;
2112 
2113       curr_dst += bytes_read;
2114       curr_addr += bytes_read;
2115       bytes_left -= bytes_read;
2116     }
2117   } else {
2118     if (dst == nullptr)
2119       result_error.SetErrorString("invalid arguments");
2120     else
2121       result_error.Clear();
2122   }
2123   return total_cstr_len;
2124 }
2125 
2126 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2127                                        Status &error) {
2128   if (buf == nullptr || size == 0)
2129     return 0;
2130 
2131   size_t bytes_read = 0;
2132   uint8_t *bytes = (uint8_t *)buf;
2133 
2134   while (bytes_read < size) {
2135     const size_t curr_size = size - bytes_read;
2136     const size_t curr_bytes_read =
2137         DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2138     bytes_read += curr_bytes_read;
2139     if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2140       break;
2141   }
2142 
2143   // Replace any software breakpoint opcodes that fall into this range back
2144   // into "buf" before we return
2145   if (bytes_read > 0)
2146     RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2147   return bytes_read;
2148 }
2149 
2150 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2151                                                 size_t integer_byte_size,
2152                                                 uint64_t fail_value,
2153                                                 Status &error) {
2154   Scalar scalar;
2155   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2156                                   error))
2157     return scalar.ULongLong(fail_value);
2158   return fail_value;
2159 }
2160 
2161 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2162                                              size_t integer_byte_size,
2163                                              int64_t fail_value,
2164                                              Status &error) {
2165   Scalar scalar;
2166   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2167                                   error))
2168     return scalar.SLongLong(fail_value);
2169   return fail_value;
2170 }
2171 
2172 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
2173   Scalar scalar;
2174   if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2175                                   error))
2176     return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2177   return LLDB_INVALID_ADDRESS;
2178 }
2179 
2180 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2181                                    Status &error) {
2182   Scalar scalar;
2183   const uint32_t addr_byte_size = GetAddressByteSize();
2184   if (addr_byte_size <= 4)
2185     scalar = (uint32_t)ptr_value;
2186   else
2187     scalar = ptr_value;
2188   return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2189          addr_byte_size;
2190 }
2191 
2192 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2193                                    Status &error) {
2194   size_t bytes_written = 0;
2195   const uint8_t *bytes = (const uint8_t *)buf;
2196 
2197   while (bytes_written < size) {
2198     const size_t curr_size = size - bytes_written;
2199     const size_t curr_bytes_written = DoWriteMemory(
2200         addr + bytes_written, bytes + bytes_written, curr_size, error);
2201     bytes_written += curr_bytes_written;
2202     if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2203       break;
2204   }
2205   return bytes_written;
2206 }
2207 
2208 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2209                             Status &error) {
2210 #if defined(ENABLE_MEMORY_CACHING)
2211   m_memory_cache.Flush(addr, size);
2212 #endif
2213 
2214   if (buf == nullptr || size == 0)
2215     return 0;
2216 
2217   m_mod_id.BumpMemoryID();
2218 
2219   // We need to write any data that would go where any current software traps
2220   // (enabled software breakpoints) any software traps (breakpoints) that we
2221   // may have placed in our tasks memory.
2222 
2223   BreakpointSiteList bp_sites_in_range;
2224   if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2225     return WriteMemoryPrivate(addr, buf, size, error);
2226 
2227   // No breakpoint sites overlap
2228   if (bp_sites_in_range.IsEmpty())
2229     return WriteMemoryPrivate(addr, buf, size, error);
2230 
2231   const uint8_t *ubuf = (const uint8_t *)buf;
2232   uint64_t bytes_written = 0;
2233 
2234   bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2235                              &error](BreakpointSite *bp) -> void {
2236     if (error.Fail())
2237       return;
2238 
2239     addr_t intersect_addr;
2240     size_t intersect_size;
2241     size_t opcode_offset;
2242     const bool intersects = bp->IntersectsRange(
2243         addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2244     UNUSED_IF_ASSERT_DISABLED(intersects);
2245     assert(intersects);
2246     assert(addr <= intersect_addr && intersect_addr < addr + size);
2247     assert(addr < intersect_addr + intersect_size &&
2248            intersect_addr + intersect_size <= addr + size);
2249     assert(opcode_offset + intersect_size <= bp->GetByteSize());
2250 
2251     // Check for bytes before this breakpoint
2252     const addr_t curr_addr = addr + bytes_written;
2253     if (intersect_addr > curr_addr) {
2254       // There are some bytes before this breakpoint that we need to just
2255       // write to memory
2256       size_t curr_size = intersect_addr - curr_addr;
2257       size_t curr_bytes_written =
2258           WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2259       bytes_written += curr_bytes_written;
2260       if (curr_bytes_written != curr_size) {
2261         // We weren't able to write all of the requested bytes, we are
2262         // done looping and will return the number of bytes that we have
2263         // written so far.
2264         if (error.Success())
2265           error.SetErrorToGenericError();
2266       }
2267     }
2268     // Now write any bytes that would cover up any software breakpoints
2269     // directly into the breakpoint opcode buffer
2270     ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2271              intersect_size);
2272     bytes_written += intersect_size;
2273   });
2274 
2275   // Write any remaining bytes after the last breakpoint if we have any left
2276   if (bytes_written < size)
2277     bytes_written +=
2278         WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2279                            size - bytes_written, error);
2280 
2281   return bytes_written;
2282 }
2283 
2284 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2285                                     size_t byte_size, Status &error) {
2286   if (byte_size == UINT32_MAX)
2287     byte_size = scalar.GetByteSize();
2288   if (byte_size > 0) {
2289     uint8_t buf[32];
2290     const size_t mem_size =
2291         scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2292     if (mem_size > 0)
2293       return WriteMemory(addr, buf, mem_size, error);
2294     else
2295       error.SetErrorString("failed to get scalar as memory data");
2296   } else {
2297     error.SetErrorString("invalid scalar value");
2298   }
2299   return 0;
2300 }
2301 
2302 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2303                                             bool is_signed, Scalar &scalar,
2304                                             Status &error) {
2305   uint64_t uval = 0;
2306   if (byte_size == 0) {
2307     error.SetErrorString("byte size is zero");
2308   } else if (byte_size & (byte_size - 1)) {
2309     error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2310                                    byte_size);
2311   } else if (byte_size <= sizeof(uval)) {
2312     const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2313     if (bytes_read == byte_size) {
2314       DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2315                          GetAddressByteSize());
2316       lldb::offset_t offset = 0;
2317       if (byte_size <= 4)
2318         scalar = data.GetMaxU32(&offset, byte_size);
2319       else
2320         scalar = data.GetMaxU64(&offset, byte_size);
2321       if (is_signed)
2322         scalar.SignExtend(byte_size * 8);
2323       return bytes_read;
2324     }
2325   } else {
2326     error.SetErrorStringWithFormat(
2327         "byte size of %u is too large for integer scalar type", byte_size);
2328   }
2329   return 0;
2330 }
2331 
2332 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2333   Status error;
2334   for (const auto &Entry : entries) {
2335     WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2336                 error);
2337     if (!error.Success())
2338       break;
2339   }
2340   return error;
2341 }
2342 
2343 #define USE_ALLOCATE_MEMORY_CACHE 1
2344 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2345                                Status &error) {
2346   if (GetPrivateState() != eStateStopped) {
2347     error.SetErrorToGenericError();
2348     return LLDB_INVALID_ADDRESS;
2349   }
2350 
2351 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2352   return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2353 #else
2354   addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2355   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2356   if (log)
2357     log->Printf("Process::AllocateMemory(size=%" PRIu64
2358                 ", permissions=%s) => 0x%16.16" PRIx64
2359                 " (m_stop_id = %u m_memory_id = %u)",
2360                 (uint64_t)size, GetPermissionsAsCString(permissions),
2361                 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2362                 m_mod_id.GetMemoryID());
2363   return allocated_addr;
2364 #endif
2365 }
2366 
2367 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2368                                 Status &error) {
2369   addr_t return_addr = AllocateMemory(size, permissions, error);
2370   if (error.Success()) {
2371     std::string buffer(size, 0);
2372     WriteMemory(return_addr, buffer.c_str(), size, error);
2373   }
2374   return return_addr;
2375 }
2376 
2377 bool Process::CanJIT() {
2378   if (m_can_jit == eCanJITDontKnow) {
2379     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2380     Status err;
2381 
2382     uint64_t allocated_memory = AllocateMemory(
2383         8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2384         err);
2385 
2386     if (err.Success()) {
2387       m_can_jit = eCanJITYes;
2388       if (log)
2389         log->Printf("Process::%s pid %" PRIu64
2390                     " allocation test passed, CanJIT () is true",
2391                     __FUNCTION__, GetID());
2392     } else {
2393       m_can_jit = eCanJITNo;
2394       if (log)
2395         log->Printf("Process::%s pid %" PRIu64
2396                     " allocation test failed, CanJIT () is false: %s",
2397                     __FUNCTION__, GetID(), err.AsCString());
2398     }
2399 
2400     DeallocateMemory(allocated_memory);
2401   }
2402 
2403   return m_can_jit == eCanJITYes;
2404 }
2405 
2406 void Process::SetCanJIT(bool can_jit) {
2407   m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2408 }
2409 
2410 void Process::SetCanRunCode(bool can_run_code) {
2411   SetCanJIT(can_run_code);
2412   m_can_interpret_function_calls = can_run_code;
2413 }
2414 
2415 Status Process::DeallocateMemory(addr_t ptr) {
2416   Status error;
2417 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2418   if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2419     error.SetErrorStringWithFormat(
2420         "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2421   }
2422 #else
2423   error = DoDeallocateMemory(ptr);
2424 
2425   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2426   if (log)
2427     log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2428                 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2429                 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2430                 m_mod_id.GetMemoryID());
2431 #endif
2432   return error;
2433 }
2434 
2435 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2436                                        lldb::addr_t header_addr,
2437                                        size_t size_to_read) {
2438   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2439   if (log) {
2440     log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2441                 file_spec.GetPath().c_str());
2442   }
2443   ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2444   if (module_sp) {
2445     Status error;
2446     ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2447         shared_from_this(), header_addr, error, size_to_read);
2448     if (objfile)
2449       return module_sp;
2450   }
2451   return ModuleSP();
2452 }
2453 
2454 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2455                                         uint32_t &permissions) {
2456   MemoryRegionInfo range_info;
2457   permissions = 0;
2458   Status error(GetMemoryRegionInfo(load_addr, range_info));
2459   if (!error.Success())
2460     return false;
2461   if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2462       range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2463       range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2464     return false;
2465   }
2466 
2467   if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2468     permissions |= lldb::ePermissionsReadable;
2469 
2470   if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2471     permissions |= lldb::ePermissionsWritable;
2472 
2473   if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2474     permissions |= lldb::ePermissionsExecutable;
2475 
2476   return true;
2477 }
2478 
2479 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2480   Status error;
2481   error.SetErrorString("watchpoints are not supported");
2482   return error;
2483 }
2484 
2485 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2486   Status error;
2487   error.SetErrorString("watchpoints are not supported");
2488   return error;
2489 }
2490 
2491 StateType
2492 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2493                                    const Timeout<std::micro> &timeout) {
2494   StateType state;
2495 
2496   while (true) {
2497     event_sp.reset();
2498     state = GetStateChangedEventsPrivate(event_sp, timeout);
2499 
2500     if (StateIsStoppedState(state, false))
2501       break;
2502 
2503     // If state is invalid, then we timed out
2504     if (state == eStateInvalid)
2505       break;
2506 
2507     if (event_sp)
2508       HandlePrivateEvent(event_sp);
2509   }
2510   return state;
2511 }
2512 
2513 void Process::LoadOperatingSystemPlugin(bool flush) {
2514   if (flush)
2515     m_thread_list.Clear();
2516   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2517   if (flush)
2518     Flush();
2519 }
2520 
2521 Status Process::Launch(ProcessLaunchInfo &launch_info) {
2522   Status error;
2523   m_abi_sp.reset();
2524   m_dyld_up.reset();
2525   m_jit_loaders_up.reset();
2526   m_system_runtime_up.reset();
2527   m_os_up.reset();
2528   m_process_input_reader.reset();
2529 
2530   Module *exe_module = GetTarget().GetExecutableModulePointer();
2531   if (!exe_module) {
2532     error.SetErrorString("executable module does not exist");
2533     return error;
2534   }
2535 
2536   char local_exec_file_path[PATH_MAX];
2537   char platform_exec_file_path[PATH_MAX];
2538   exe_module->GetFileSpec().GetPath(local_exec_file_path,
2539                                     sizeof(local_exec_file_path));
2540   exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2541                                             sizeof(platform_exec_file_path));
2542   if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2543     // Install anything that might need to be installed prior to launching.
2544     // For host systems, this will do nothing, but if we are connected to a
2545     // remote platform it will install any needed binaries
2546     error = GetTarget().Install(&launch_info);
2547     if (error.Fail())
2548       return error;
2549 
2550     if (PrivateStateThreadIsValid())
2551       PausePrivateStateThread();
2552 
2553     error = WillLaunch(exe_module);
2554     if (error.Success()) {
2555       const bool restarted = false;
2556       SetPublicState(eStateLaunching, restarted);
2557       m_should_detach = false;
2558 
2559       if (m_public_run_lock.TrySetRunning()) {
2560         // Now launch using these arguments.
2561         error = DoLaunch(exe_module, launch_info);
2562       } else {
2563         // This shouldn't happen
2564         error.SetErrorString("failed to acquire process run lock");
2565       }
2566 
2567       if (error.Fail()) {
2568         if (GetID() != LLDB_INVALID_PROCESS_ID) {
2569           SetID(LLDB_INVALID_PROCESS_ID);
2570           const char *error_string = error.AsCString();
2571           if (error_string == nullptr)
2572             error_string = "launch failed";
2573           SetExitStatus(-1, error_string);
2574         }
2575       } else {
2576         EventSP event_sp;
2577 
2578         // Now wait for the process to launch and return control to us, and then
2579         // call DidLaunch:
2580         StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2581 
2582         if (state == eStateInvalid || !event_sp) {
2583           // We were able to launch the process, but we failed to catch the
2584           // initial stop.
2585           error.SetErrorString("failed to catch stop after launch");
2586           SetExitStatus(0, "failed to catch stop after launch");
2587           Destroy(false);
2588         } else if (state == eStateStopped || state == eStateCrashed) {
2589           DidLaunch();
2590 
2591           DynamicLoader *dyld = GetDynamicLoader();
2592           if (dyld)
2593             dyld->DidLaunch();
2594 
2595           GetJITLoaders().DidLaunch();
2596 
2597           SystemRuntime *system_runtime = GetSystemRuntime();
2598           if (system_runtime)
2599             system_runtime->DidLaunch();
2600 
2601           if (!m_os_up)
2602             LoadOperatingSystemPlugin(false);
2603 
2604           // We successfully launched the process and stopped, now it the
2605           // right time to set up signal filters before resuming.
2606           UpdateAutomaticSignalFiltering();
2607 
2608           // Note, the stop event was consumed above, but not handled. This
2609           // was done to give DidLaunch a chance to run. The target is either
2610           // stopped or crashed. Directly set the state.  This is done to
2611           // prevent a stop message with a bunch of spurious output on thread
2612           // status, as well as not pop a ProcessIOHandler.
2613           SetPublicState(state, false);
2614 
2615           if (PrivateStateThreadIsValid())
2616             ResumePrivateStateThread();
2617           else
2618             StartPrivateStateThread();
2619 
2620           // Target was stopped at entry as was intended. Need to notify the
2621           // listeners about it.
2622           if (state == eStateStopped &&
2623               launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2624             HandlePrivateEvent(event_sp);
2625         } else if (state == eStateExited) {
2626           // We exited while trying to launch somehow.  Don't call DidLaunch
2627           // as that's not likely to work, and return an invalid pid.
2628           HandlePrivateEvent(event_sp);
2629         }
2630       }
2631     }
2632   } else {
2633     error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2634                                    local_exec_file_path);
2635   }
2636 
2637   return error;
2638 }
2639 
2640 Status Process::LoadCore() {
2641   Status error = DoLoadCore();
2642   if (error.Success()) {
2643     ListenerSP listener_sp(
2644         Listener::MakeListener("lldb.process.load_core_listener"));
2645     HijackProcessEvents(listener_sp);
2646 
2647     if (PrivateStateThreadIsValid())
2648       ResumePrivateStateThread();
2649     else
2650       StartPrivateStateThread();
2651 
2652     DynamicLoader *dyld = GetDynamicLoader();
2653     if (dyld)
2654       dyld->DidAttach();
2655 
2656     GetJITLoaders().DidAttach();
2657 
2658     SystemRuntime *system_runtime = GetSystemRuntime();
2659     if (system_runtime)
2660       system_runtime->DidAttach();
2661 
2662     if (!m_os_up)
2663       LoadOperatingSystemPlugin(false);
2664 
2665     // We successfully loaded a core file, now pretend we stopped so we can
2666     // show all of the threads in the core file and explore the crashed state.
2667     SetPrivateState(eStateStopped);
2668 
2669     // Wait for a stopped event since we just posted one above...
2670     lldb::EventSP event_sp;
2671     StateType state =
2672         WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
2673 
2674     if (!StateIsStoppedState(state, false)) {
2675       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2676       if (log)
2677         log->Printf("Process::Halt() failed to stop, state is: %s",
2678                     StateAsCString(state));
2679       error.SetErrorString(
2680           "Did not get stopped event after loading the core file.");
2681     }
2682     RestoreProcessEvents();
2683   }
2684   return error;
2685 }
2686 
2687 DynamicLoader *Process::GetDynamicLoader() {
2688   if (!m_dyld_up)
2689     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2690   return m_dyld_up.get();
2691 }
2692 
2693 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2694 
2695 JITLoaderList &Process::GetJITLoaders() {
2696   if (!m_jit_loaders_up) {
2697     m_jit_loaders_up.reset(new JITLoaderList());
2698     JITLoader::LoadPlugins(this, *m_jit_loaders_up);
2699   }
2700   return *m_jit_loaders_up;
2701 }
2702 
2703 SystemRuntime *Process::GetSystemRuntime() {
2704   if (!m_system_runtime_up)
2705     m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2706   return m_system_runtime_up.get();
2707 }
2708 
2709 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2710                                                           uint32_t exec_count)
2711     : NextEventAction(process), m_exec_count(exec_count) {
2712   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2713   if (log)
2714     log->Printf(
2715         "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2716         __FUNCTION__, static_cast<void *>(process), exec_count);
2717 }
2718 
2719 Process::NextEventAction::EventActionResult
2720 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2721   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2722 
2723   StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2724   if (log)
2725     log->Printf(
2726         "Process::AttachCompletionHandler::%s called with state %s (%d)",
2727         __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2728 
2729   switch (state) {
2730   case eStateAttaching:
2731     return eEventActionSuccess;
2732 
2733   case eStateRunning:
2734   case eStateConnected:
2735     return eEventActionRetry;
2736 
2737   case eStateStopped:
2738   case eStateCrashed:
2739     // During attach, prior to sending the eStateStopped event,
2740     // lldb_private::Process subclasses must set the new process ID.
2741     assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2742     // We don't want these events to be reported, so go set the
2743     // ShouldReportStop here:
2744     m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2745 
2746     if (m_exec_count > 0) {
2747       --m_exec_count;
2748 
2749       if (log)
2750         log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2751                     "remaining exec count to %" PRIu32 ", requesting resume",
2752                     __FUNCTION__, StateAsCString(state), m_exec_count);
2753 
2754       RequestResume();
2755       return eEventActionRetry;
2756     } else {
2757       if (log)
2758         log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2759                     "execs expected to start, continuing with attach",
2760                     __FUNCTION__, StateAsCString(state));
2761 
2762       m_process->CompleteAttach();
2763       return eEventActionSuccess;
2764     }
2765     break;
2766 
2767   default:
2768   case eStateExited:
2769   case eStateInvalid:
2770     break;
2771   }
2772 
2773   m_exit_string.assign("No valid Process");
2774   return eEventActionExit;
2775 }
2776 
2777 Process::NextEventAction::EventActionResult
2778 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2779   return eEventActionSuccess;
2780 }
2781 
2782 const char *Process::AttachCompletionHandler::GetExitString() {
2783   return m_exit_string.c_str();
2784 }
2785 
2786 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2787   if (m_listener_sp)
2788     return m_listener_sp;
2789   else
2790     return debugger.GetListener();
2791 }
2792 
2793 Status Process::Attach(ProcessAttachInfo &attach_info) {
2794   m_abi_sp.reset();
2795   m_process_input_reader.reset();
2796   m_dyld_up.reset();
2797   m_jit_loaders_up.reset();
2798   m_system_runtime_up.reset();
2799   m_os_up.reset();
2800 
2801   lldb::pid_t attach_pid = attach_info.GetProcessID();
2802   Status error;
2803   if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2804     char process_name[PATH_MAX];
2805 
2806     if (attach_info.GetExecutableFile().GetPath(process_name,
2807                                                 sizeof(process_name))) {
2808       const bool wait_for_launch = attach_info.GetWaitForLaunch();
2809 
2810       if (wait_for_launch) {
2811         error = WillAttachToProcessWithName(process_name, wait_for_launch);
2812         if (error.Success()) {
2813           if (m_public_run_lock.TrySetRunning()) {
2814             m_should_detach = true;
2815             const bool restarted = false;
2816             SetPublicState(eStateAttaching, restarted);
2817             // Now attach using these arguments.
2818             error = DoAttachToProcessWithName(process_name, attach_info);
2819           } else {
2820             // This shouldn't happen
2821             error.SetErrorString("failed to acquire process run lock");
2822           }
2823 
2824           if (error.Fail()) {
2825             if (GetID() != LLDB_INVALID_PROCESS_ID) {
2826               SetID(LLDB_INVALID_PROCESS_ID);
2827               if (error.AsCString() == nullptr)
2828                 error.SetErrorString("attach failed");
2829 
2830               SetExitStatus(-1, error.AsCString());
2831             }
2832           } else {
2833             SetNextEventAction(new Process::AttachCompletionHandler(
2834                 this, attach_info.GetResumeCount()));
2835             StartPrivateStateThread();
2836           }
2837           return error;
2838         }
2839       } else {
2840         ProcessInstanceInfoList process_infos;
2841         PlatformSP platform_sp(GetTarget().GetPlatform());
2842 
2843         if (platform_sp) {
2844           ProcessInstanceInfoMatch match_info;
2845           match_info.GetProcessInfo() = attach_info;
2846           match_info.SetNameMatchType(NameMatch::Equals);
2847           platform_sp->FindProcesses(match_info, process_infos);
2848           const uint32_t num_matches = process_infos.GetSize();
2849           if (num_matches == 1) {
2850             attach_pid = process_infos.GetProcessIDAtIndex(0);
2851             // Fall through and attach using the above process ID
2852           } else {
2853             match_info.GetProcessInfo().GetExecutableFile().GetPath(
2854                 process_name, sizeof(process_name));
2855             if (num_matches > 1) {
2856               StreamString s;
2857               ProcessInstanceInfo::DumpTableHeader(s, true, false);
2858               for (size_t i = 0; i < num_matches; i++) {
2859                 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
2860                     s, platform_sp->GetUserIDResolver(), true, false);
2861               }
2862               error.SetErrorStringWithFormat(
2863                   "more than one process named %s:\n%s", process_name,
2864                   s.GetData());
2865             } else
2866               error.SetErrorStringWithFormat(
2867                   "could not find a process named %s", process_name);
2868           }
2869         } else {
2870           error.SetErrorString(
2871               "invalid platform, can't find processes by name");
2872           return error;
2873         }
2874       }
2875     } else {
2876       error.SetErrorString("invalid process name");
2877     }
2878   }
2879 
2880   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2881     error = WillAttachToProcessWithID(attach_pid);
2882     if (error.Success()) {
2883 
2884       if (m_public_run_lock.TrySetRunning()) {
2885         // Now attach using these arguments.
2886         m_should_detach = true;
2887         const bool restarted = false;
2888         SetPublicState(eStateAttaching, restarted);
2889         error = DoAttachToProcessWithID(attach_pid, attach_info);
2890       } else {
2891         // This shouldn't happen
2892         error.SetErrorString("failed to acquire process run lock");
2893       }
2894 
2895       if (error.Success()) {
2896         SetNextEventAction(new Process::AttachCompletionHandler(
2897             this, attach_info.GetResumeCount()));
2898         StartPrivateStateThread();
2899       } else {
2900         if (GetID() != LLDB_INVALID_PROCESS_ID)
2901           SetID(LLDB_INVALID_PROCESS_ID);
2902 
2903         const char *error_string = error.AsCString();
2904         if (error_string == nullptr)
2905           error_string = "attach failed";
2906 
2907         SetExitStatus(-1, error_string);
2908       }
2909     }
2910   }
2911   return error;
2912 }
2913 
2914 void Process::CompleteAttach() {
2915   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2916                                                   LIBLLDB_LOG_TARGET));
2917   if (log)
2918     log->Printf("Process::%s()", __FUNCTION__);
2919 
2920   // Let the process subclass figure out at much as it can about the process
2921   // before we go looking for a dynamic loader plug-in.
2922   ArchSpec process_arch;
2923   DidAttach(process_arch);
2924 
2925   if (process_arch.IsValid()) {
2926     GetTarget().SetArchitecture(process_arch);
2927     if (log) {
2928       const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2929       log->Printf("Process::%s replacing process architecture with DidAttach() "
2930                   "architecture: %s",
2931                   __FUNCTION__, triple_str ? triple_str : "<null>");
2932     }
2933   }
2934 
2935   // We just attached.  If we have a platform, ask it for the process
2936   // architecture, and if it isn't the same as the one we've already set,
2937   // switch architectures.
2938   PlatformSP platform_sp(GetTarget().GetPlatform());
2939   assert(platform_sp);
2940   if (platform_sp) {
2941     const ArchSpec &target_arch = GetTarget().GetArchitecture();
2942     if (target_arch.IsValid() &&
2943         !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2944       ArchSpec platform_arch;
2945       platform_sp =
2946           platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2947       if (platform_sp) {
2948         GetTarget().SetPlatform(platform_sp);
2949         GetTarget().SetArchitecture(platform_arch);
2950         if (log)
2951           log->Printf("Process::%s switching platform to %s and architecture "
2952                       "to %s based on info from attach",
2953                       __FUNCTION__, platform_sp->GetName().AsCString(""),
2954                       platform_arch.GetTriple().getTriple().c_str());
2955       }
2956     } else if (!process_arch.IsValid()) {
2957       ProcessInstanceInfo process_info;
2958       GetProcessInfo(process_info);
2959       const ArchSpec &process_arch = process_info.GetArchitecture();
2960       if (process_arch.IsValid() &&
2961           !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2962         GetTarget().SetArchitecture(process_arch);
2963         if (log)
2964           log->Printf("Process::%s switching architecture to %s based on info "
2965                       "the platform retrieved for pid %" PRIu64,
2966                       __FUNCTION__,
2967                       process_arch.GetTriple().getTriple().c_str(), GetID());
2968       }
2969     }
2970   }
2971 
2972   // We have completed the attach, now it is time to find the dynamic loader
2973   // plug-in
2974   DynamicLoader *dyld = GetDynamicLoader();
2975   if (dyld) {
2976     dyld->DidAttach();
2977     if (log) {
2978       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2979       log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
2980                   "executable is %s (using %s plugin)",
2981                   __FUNCTION__,
2982                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2983                                 : "<none>",
2984                   dyld->GetPluginName().AsCString("<unnamed>"));
2985     }
2986   }
2987 
2988   GetJITLoaders().DidAttach();
2989 
2990   SystemRuntime *system_runtime = GetSystemRuntime();
2991   if (system_runtime) {
2992     system_runtime->DidAttach();
2993     if (log) {
2994       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2995       log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
2996                   "executable is %s (using %s plugin)",
2997                   __FUNCTION__,
2998                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2999                                 : "<none>",
3000                   system_runtime->GetPluginName().AsCString("<unnamed>"));
3001     }
3002   }
3003 
3004   if (!m_os_up)
3005     LoadOperatingSystemPlugin(false);
3006   // Figure out which one is the executable, and set that in our target:
3007   const ModuleList &target_modules = GetTarget().GetImages();
3008   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3009   size_t num_modules = target_modules.GetSize();
3010   ModuleSP new_executable_module_sp;
3011 
3012   for (size_t i = 0; i < num_modules; i++) {
3013     ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3014     if (module_sp && module_sp->IsExecutable()) {
3015       if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3016         new_executable_module_sp = module_sp;
3017       break;
3018     }
3019   }
3020   if (new_executable_module_sp) {
3021     GetTarget().SetExecutableModule(new_executable_module_sp,
3022                                     eLoadDependentsNo);
3023     if (log) {
3024       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3025       log->Printf(
3026           "Process::%s after looping through modules, target executable is %s",
3027           __FUNCTION__,
3028           exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3029                         : "<none>");
3030     }
3031   }
3032 }
3033 
3034 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3035   m_abi_sp.reset();
3036   m_process_input_reader.reset();
3037 
3038   // Find the process and its architecture.  Make sure it matches the
3039   // architecture of the current Target, and if not adjust it.
3040 
3041   Status error(DoConnectRemote(strm, remote_url));
3042   if (error.Success()) {
3043     if (GetID() != LLDB_INVALID_PROCESS_ID) {
3044       EventSP event_sp;
3045       StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3046 
3047       if (state == eStateStopped || state == eStateCrashed) {
3048         // If we attached and actually have a process on the other end, then
3049         // this ended up being the equivalent of an attach.
3050         CompleteAttach();
3051 
3052         // This delays passing the stopped event to listeners till
3053         // CompleteAttach gets a chance to complete...
3054         HandlePrivateEvent(event_sp);
3055       }
3056     }
3057 
3058     if (PrivateStateThreadIsValid())
3059       ResumePrivateStateThread();
3060     else
3061       StartPrivateStateThread();
3062   }
3063   return error;
3064 }
3065 
3066 Status Process::PrivateResume() {
3067   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3068                                                   LIBLLDB_LOG_STEP));
3069   if (log)
3070     log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3071                 "private state: %s",
3072                 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3073                 StateAsCString(m_private_state.GetValue()));
3074 
3075   // If signals handing status changed we might want to update our signal
3076   // filters before resuming.
3077   UpdateAutomaticSignalFiltering();
3078 
3079   Status error(WillResume());
3080   // Tell the process it is about to resume before the thread list
3081   if (error.Success()) {
3082     // Now let the thread list know we are about to resume so it can let all of
3083     // our threads know that they are about to be resumed. Threads will each be
3084     // called with Thread::WillResume(StateType) where StateType contains the
3085     // state that they are supposed to have when the process is resumed
3086     // (suspended/running/stepping). Threads should also check their resume
3087     // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3088     // start back up with a signal.
3089     if (m_thread_list.WillResume()) {
3090       // Last thing, do the PreResumeActions.
3091       if (!RunPreResumeActions()) {
3092         error.SetErrorStringWithFormat(
3093             "Process::PrivateResume PreResumeActions failed, not resuming.");
3094       } else {
3095         m_mod_id.BumpResumeID();
3096         error = DoResume();
3097         if (error.Success()) {
3098           DidResume();
3099           m_thread_list.DidResume();
3100           if (log)
3101             log->Printf("Process thinks the process has resumed.");
3102         } else {
3103           if (log)
3104             log->Printf(
3105                 "Process::PrivateResume() DoResume failed.");
3106           return error;
3107         }
3108       }
3109     } else {
3110       // Somebody wanted to run without running (e.g. we were faking a step
3111       // from one frame of a set of inlined frames that share the same PC to
3112       // another.)  So generate a continue & a stopped event, and let the world
3113       // handle them.
3114       if (log)
3115         log->Printf(
3116             "Process::PrivateResume() asked to simulate a start & stop.");
3117 
3118       SetPrivateState(eStateRunning);
3119       SetPrivateState(eStateStopped);
3120     }
3121   } else if (log)
3122     log->Printf("Process::PrivateResume() got an error \"%s\".",
3123                 error.AsCString("<unknown error>"));
3124   return error;
3125 }
3126 
3127 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3128   if (!StateIsRunningState(m_public_state.GetValue()))
3129     return Status("Process is not running.");
3130 
3131   // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3132   // case it was already set and some thread plan logic calls halt on its own.
3133   m_clear_thread_plans_on_stop |= clear_thread_plans;
3134 
3135   ListenerSP halt_listener_sp(
3136       Listener::MakeListener("lldb.process.halt_listener"));
3137   HijackProcessEvents(halt_listener_sp);
3138 
3139   EventSP event_sp;
3140 
3141   SendAsyncInterrupt();
3142 
3143   if (m_public_state.GetValue() == eStateAttaching) {
3144     // Don't hijack and eat the eStateExited as the code that was doing the
3145     // attach will be waiting for this event...
3146     RestoreProcessEvents();
3147     SetExitStatus(SIGKILL, "Cancelled async attach.");
3148     Destroy(false);
3149     return Status();
3150   }
3151 
3152   // Wait for 10 second for the process to stop.
3153   StateType state = WaitForProcessToStop(
3154       seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
3155   RestoreProcessEvents();
3156 
3157   if (state == eStateInvalid || !event_sp) {
3158     // We timed out and didn't get a stop event...
3159     return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3160   }
3161 
3162   BroadcastEvent(event_sp);
3163 
3164   return Status();
3165 }
3166 
3167 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3168   Status error;
3169 
3170   // Check both the public & private states here.  If we're hung evaluating an
3171   // expression, for instance, then the public state will be stopped, but we
3172   // still need to interrupt.
3173   if (m_public_state.GetValue() == eStateRunning ||
3174       m_private_state.GetValue() == eStateRunning) {
3175     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3176     if (log)
3177       log->Printf("Process::%s() About to stop.", __FUNCTION__);
3178 
3179     ListenerSP listener_sp(
3180         Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3181     HijackProcessEvents(listener_sp);
3182 
3183     SendAsyncInterrupt();
3184 
3185     // Consume the interrupt event.
3186     StateType state =
3187         WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
3188 
3189     RestoreProcessEvents();
3190 
3191     // If the process exited while we were waiting for it to stop, put the
3192     // exited event into the shared pointer passed in and return.  Our caller
3193     // doesn't need to do anything else, since they don't have a process
3194     // anymore...
3195 
3196     if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3197       if (log)
3198         log->Printf("Process::%s() Process exited while waiting to stop.",
3199                     __FUNCTION__);
3200       return error;
3201     } else
3202       exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3203 
3204     if (state != eStateStopped) {
3205       if (log)
3206         log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3207                     StateAsCString(state));
3208       // If we really couldn't stop the process then we should just error out
3209       // here, but if the lower levels just bobbled sending the event and we
3210       // really are stopped, then continue on.
3211       StateType private_state = m_private_state.GetValue();
3212       if (private_state != eStateStopped) {
3213         return Status(
3214             "Attempt to stop the target in order to detach timed out. "
3215             "State = %s",
3216             StateAsCString(GetState()));
3217       }
3218     }
3219   }
3220   return error;
3221 }
3222 
3223 Status Process::Detach(bool keep_stopped) {
3224   EventSP exit_event_sp;
3225   Status error;
3226   m_destroy_in_process = true;
3227 
3228   error = WillDetach();
3229 
3230   if (error.Success()) {
3231     if (DetachRequiresHalt()) {
3232       error = StopForDestroyOrDetach(exit_event_sp);
3233       if (!error.Success()) {
3234         m_destroy_in_process = false;
3235         return error;
3236       } else if (exit_event_sp) {
3237         // We shouldn't need to do anything else here.  There's no process left
3238         // to detach from...
3239         StopPrivateStateThread();
3240         m_destroy_in_process = false;
3241         return error;
3242       }
3243     }
3244 
3245     m_thread_list.DiscardThreadPlans();
3246     DisableAllBreakpointSites();
3247 
3248     error = DoDetach(keep_stopped);
3249     if (error.Success()) {
3250       DidDetach();
3251       StopPrivateStateThread();
3252     } else {
3253       return error;
3254     }
3255   }
3256   m_destroy_in_process = false;
3257 
3258   // If we exited when we were waiting for a process to stop, then forward the
3259   // event here so we don't lose the event
3260   if (exit_event_sp) {
3261     // Directly broadcast our exited event because we shut down our private
3262     // state thread above
3263     BroadcastEvent(exit_event_sp);
3264   }
3265 
3266   // If we have been interrupted (to kill us) in the middle of running, we may
3267   // not end up propagating the last events through the event system, in which
3268   // case we might strand the write lock.  Unlock it here so when we do to tear
3269   // down the process we don't get an error destroying the lock.
3270 
3271   m_public_run_lock.SetStopped();
3272   return error;
3273 }
3274 
3275 Status Process::Destroy(bool force_kill) {
3276 
3277   // Tell ourselves we are in the process of destroying the process, so that we
3278   // don't do any unnecessary work that might hinder the destruction.  Remember
3279   // to set this back to false when we are done.  That way if the attempt
3280   // failed and the process stays around for some reason it won't be in a
3281   // confused state.
3282 
3283   if (force_kill)
3284     m_should_detach = false;
3285 
3286   if (GetShouldDetach()) {
3287     // FIXME: This will have to be a process setting:
3288     bool keep_stopped = false;
3289     Detach(keep_stopped);
3290   }
3291 
3292   m_destroy_in_process = true;
3293 
3294   Status error(WillDestroy());
3295   if (error.Success()) {
3296     EventSP exit_event_sp;
3297     if (DestroyRequiresHalt()) {
3298       error = StopForDestroyOrDetach(exit_event_sp);
3299     }
3300 
3301     if (m_public_state.GetValue() != eStateRunning) {
3302       // Ditch all thread plans, and remove all our breakpoints: in case we
3303       // have to restart the target to kill it, we don't want it hitting a
3304       // breakpoint... Only do this if we've stopped, however, since if we
3305       // didn't manage to halt it above, then we're not going to have much luck
3306       // doing this now.
3307       m_thread_list.DiscardThreadPlans();
3308       DisableAllBreakpointSites();
3309     }
3310 
3311     error = DoDestroy();
3312     if (error.Success()) {
3313       DidDestroy();
3314       StopPrivateStateThread();
3315     }
3316     m_stdio_communication.Disconnect();
3317     m_stdio_communication.StopReadThread();
3318     m_stdin_forward = false;
3319 
3320     if (m_process_input_reader) {
3321       m_process_input_reader->SetIsDone(true);
3322       m_process_input_reader->Cancel();
3323       m_process_input_reader.reset();
3324     }
3325 
3326     // If we exited when we were waiting for a process to stop, then forward
3327     // the event here so we don't lose the event
3328     if (exit_event_sp) {
3329       // Directly broadcast our exited event because we shut down our private
3330       // state thread above
3331       BroadcastEvent(exit_event_sp);
3332     }
3333 
3334     // If we have been interrupted (to kill us) in the middle of running, we
3335     // may not end up propagating the last events through the event system, in
3336     // which case we might strand the write lock.  Unlock it here so when we do
3337     // to tear down the process we don't get an error destroying the lock.
3338     m_public_run_lock.SetStopped();
3339   }
3340 
3341   m_destroy_in_process = false;
3342 
3343   return error;
3344 }
3345 
3346 Status Process::Signal(int signal) {
3347   Status error(WillSignal());
3348   if (error.Success()) {
3349     error = DoSignal(signal);
3350     if (error.Success())
3351       DidSignal();
3352   }
3353   return error;
3354 }
3355 
3356 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3357   assert(signals_sp && "null signals_sp");
3358   m_unix_signals_sp = signals_sp;
3359 }
3360 
3361 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3362   assert(m_unix_signals_sp && "null m_unix_signals_sp");
3363   return m_unix_signals_sp;
3364 }
3365 
3366 lldb::ByteOrder Process::GetByteOrder() const {
3367   return GetTarget().GetArchitecture().GetByteOrder();
3368 }
3369 
3370 uint32_t Process::GetAddressByteSize() const {
3371   return GetTarget().GetArchitecture().GetAddressByteSize();
3372 }
3373 
3374 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3375   const StateType state =
3376       Process::ProcessEventData::GetStateFromEvent(event_ptr);
3377   bool return_value = true;
3378   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3379                                                   LIBLLDB_LOG_PROCESS));
3380 
3381   switch (state) {
3382   case eStateDetached:
3383   case eStateExited:
3384   case eStateUnloaded:
3385     m_stdio_communication.SynchronizeWithReadThread();
3386     m_stdio_communication.Disconnect();
3387     m_stdio_communication.StopReadThread();
3388     m_stdin_forward = false;
3389 
3390     LLVM_FALLTHROUGH;
3391   case eStateConnected:
3392   case eStateAttaching:
3393   case eStateLaunching:
3394     // These events indicate changes in the state of the debugging session,
3395     // always report them.
3396     return_value = true;
3397     break;
3398   case eStateInvalid:
3399     // We stopped for no apparent reason, don't report it.
3400     return_value = false;
3401     break;
3402   case eStateRunning:
3403   case eStateStepping:
3404     // If we've started the target running, we handle the cases where we are
3405     // already running and where there is a transition from stopped to running
3406     // differently. running -> running: Automatically suppress extra running
3407     // events stopped -> running: Report except when there is one or more no
3408     // votes
3409     //     and no yes votes.
3410     SynchronouslyNotifyStateChanged(state);
3411     if (m_force_next_event_delivery)
3412       return_value = true;
3413     else {
3414       switch (m_last_broadcast_state) {
3415       case eStateRunning:
3416       case eStateStepping:
3417         // We always suppress multiple runnings with no PUBLIC stop in between.
3418         return_value = false;
3419         break;
3420       default:
3421         // TODO: make this work correctly. For now always report
3422         // run if we aren't running so we don't miss any running events. If I
3423         // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3424         // and hit the breakpoints on multiple threads, then somehow during the
3425         // stepping over of all breakpoints no run gets reported.
3426 
3427         // This is a transition from stop to run.
3428         switch (m_thread_list.ShouldReportRun(event_ptr)) {
3429         case eVoteYes:
3430         case eVoteNoOpinion:
3431           return_value = true;
3432           break;
3433         case eVoteNo:
3434           return_value = false;
3435           break;
3436         }
3437         break;
3438       }
3439     }
3440     break;
3441   case eStateStopped:
3442   case eStateCrashed:
3443   case eStateSuspended:
3444     // We've stopped.  First see if we're going to restart the target. If we
3445     // are going to stop, then we always broadcast the event. If we aren't
3446     // going to stop, let the thread plans decide if we're going to report this
3447     // event. If no thread has an opinion, we don't report it.
3448 
3449     m_stdio_communication.SynchronizeWithReadThread();
3450     RefreshStateAfterStop();
3451     if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3452       if (log)
3453         log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3454                     "interrupt, state: %s",
3455                     static_cast<void *>(event_ptr), StateAsCString(state));
3456       // Even though we know we are going to stop, we should let the threads
3457       // have a look at the stop, so they can properly set their state.
3458       m_thread_list.ShouldStop(event_ptr);
3459       return_value = true;
3460     } else {
3461       bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3462       bool should_resume = false;
3463 
3464       // It makes no sense to ask "ShouldStop" if we've already been
3465       // restarted... Asking the thread list is also not likely to go well,
3466       // since we are running again. So in that case just report the event.
3467 
3468       if (!was_restarted)
3469         should_resume = !m_thread_list.ShouldStop(event_ptr);
3470 
3471       if (was_restarted || should_resume || m_resume_requested) {
3472         Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3473         if (log)
3474           log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3475                       "%s was_restarted: %i stop_vote: %d.",
3476                       should_resume, StateAsCString(state), was_restarted,
3477                       stop_vote);
3478 
3479         switch (stop_vote) {
3480         case eVoteYes:
3481           return_value = true;
3482           break;
3483         case eVoteNoOpinion:
3484         case eVoteNo:
3485           return_value = false;
3486           break;
3487         }
3488 
3489         if (!was_restarted) {
3490           if (log)
3491             log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3492                         "from state: %s",
3493                         static_cast<void *>(event_ptr), StateAsCString(state));
3494           ProcessEventData::SetRestartedInEvent(event_ptr, true);
3495           PrivateResume();
3496         }
3497       } else {
3498         return_value = true;
3499         SynchronouslyNotifyStateChanged(state);
3500       }
3501     }
3502     break;
3503   }
3504 
3505   // Forcing the next event delivery is a one shot deal.  So reset it here.
3506   m_force_next_event_delivery = false;
3507 
3508   // We do some coalescing of events (for instance two consecutive running
3509   // events get coalesced.) But we only coalesce against events we actually
3510   // broadcast.  So we use m_last_broadcast_state to track that.  NB - you
3511   // can't use "m_public_state.GetValue()" for that purpose, as was originally
3512   // done, because the PublicState reflects the last event pulled off the
3513   // queue, and there may be several events stacked up on the queue unserviced.
3514   // So the PublicState may not reflect the last broadcasted event yet.
3515   // m_last_broadcast_state gets updated here.
3516 
3517   if (return_value)
3518     m_last_broadcast_state = state;
3519 
3520   if (log)
3521     log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3522                 "broadcast state: %s - %s",
3523                 static_cast<void *>(event_ptr), StateAsCString(state),
3524                 StateAsCString(m_last_broadcast_state),
3525                 return_value ? "YES" : "NO");
3526   return return_value;
3527 }
3528 
3529 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3530   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3531 
3532   bool already_running = PrivateStateThreadIsValid();
3533   if (log)
3534     log->Printf("Process::%s()%s ", __FUNCTION__,
3535                 already_running ? " already running"
3536                                 : " starting private state thread");
3537 
3538   if (!is_secondary_thread && already_running)
3539     return true;
3540 
3541   // Create a thread that watches our internal state and controls which events
3542   // make it to clients (into the DCProcess event queue).
3543   char thread_name[1024];
3544   uint32_t max_len = llvm::get_max_thread_name_length();
3545   if (max_len > 0 && max_len <= 30) {
3546     // On platforms with abbreviated thread name lengths, choose thread names
3547     // that fit within the limit.
3548     if (already_running)
3549       snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3550     else
3551       snprintf(thread_name, sizeof(thread_name), "intern-state");
3552   } else {
3553     if (already_running)
3554       snprintf(thread_name, sizeof(thread_name),
3555                "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3556                GetID());
3557     else
3558       snprintf(thread_name, sizeof(thread_name),
3559                "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3560   }
3561 
3562   // Create the private state thread, and start it running.
3563   PrivateStateThreadArgs *args_ptr =
3564       new PrivateStateThreadArgs(this, is_secondary_thread);
3565   m_private_state_thread =
3566       ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3567                                    (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3568   if (m_private_state_thread.IsJoinable()) {
3569     ResumePrivateStateThread();
3570     return true;
3571   } else
3572     return false;
3573 }
3574 
3575 void Process::PausePrivateStateThread() {
3576   ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3577 }
3578 
3579 void Process::ResumePrivateStateThread() {
3580   ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3581 }
3582 
3583 void Process::StopPrivateStateThread() {
3584   if (m_private_state_thread.IsJoinable())
3585     ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3586   else {
3587     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3588     if (log)
3589       log->Printf(
3590           "Went to stop the private state thread, but it was already invalid.");
3591   }
3592 }
3593 
3594 void Process::ControlPrivateStateThread(uint32_t signal) {
3595   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3596 
3597   assert(signal == eBroadcastInternalStateControlStop ||
3598          signal == eBroadcastInternalStateControlPause ||
3599          signal == eBroadcastInternalStateControlResume);
3600 
3601   if (log)
3602     log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3603 
3604   // Signal the private state thread
3605   if (m_private_state_thread.IsJoinable()) {
3606     // Broadcast the event.
3607     // It is important to do this outside of the if below, because it's
3608     // possible that the thread state is invalid but that the thread is waiting
3609     // on a control event instead of simply being on its way out (this should
3610     // not happen, but it apparently can).
3611     if (log)
3612       log->Printf("Sending control event of type: %d.", signal);
3613     std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3614     m_private_state_control_broadcaster.BroadcastEvent(signal,
3615                                                        event_receipt_sp);
3616 
3617     // Wait for the event receipt or for the private state thread to exit
3618     bool receipt_received = false;
3619     if (PrivateStateThreadIsValid()) {
3620       while (!receipt_received) {
3621         // Check for a receipt for n seconds and then check if the private
3622         // state thread is still around.
3623         receipt_received =
3624           event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
3625         if (!receipt_received) {
3626           // Check if the private state thread is still around. If it isn't
3627           // then we are done waiting
3628           if (!PrivateStateThreadIsValid())
3629             break; // Private state thread exited or is exiting, we are done
3630         }
3631       }
3632     }
3633 
3634     if (signal == eBroadcastInternalStateControlStop) {
3635       thread_result_t result = NULL;
3636       m_private_state_thread.Join(&result);
3637       m_private_state_thread.Reset();
3638     }
3639   } else {
3640     if (log)
3641       log->Printf(
3642           "Private state thread already dead, no need to signal it to stop.");
3643   }
3644 }
3645 
3646 void Process::SendAsyncInterrupt() {
3647   if (PrivateStateThreadIsValid())
3648     m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3649                                                nullptr);
3650   else
3651     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3652 }
3653 
3654 void Process::HandlePrivateEvent(EventSP &event_sp) {
3655   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3656   m_resume_requested = false;
3657 
3658   const StateType new_state =
3659       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3660 
3661   // First check to see if anybody wants a shot at this event:
3662   if (m_next_event_action_up) {
3663     NextEventAction::EventActionResult action_result =
3664         m_next_event_action_up->PerformAction(event_sp);
3665     if (log)
3666       log->Printf("Ran next event action, result was %d.", action_result);
3667 
3668     switch (action_result) {
3669     case NextEventAction::eEventActionSuccess:
3670       SetNextEventAction(nullptr);
3671       break;
3672 
3673     case NextEventAction::eEventActionRetry:
3674       break;
3675 
3676     case NextEventAction::eEventActionExit:
3677       // Handle Exiting Here.  If we already got an exited event, we should
3678       // just propagate it.  Otherwise, swallow this event, and set our state
3679       // to exit so the next event will kill us.
3680       if (new_state != eStateExited) {
3681         // FIXME: should cons up an exited event, and discard this one.
3682         SetExitStatus(0, m_next_event_action_up->GetExitString());
3683         SetNextEventAction(nullptr);
3684         return;
3685       }
3686       SetNextEventAction(nullptr);
3687       break;
3688     }
3689   }
3690 
3691   // See if we should broadcast this state to external clients?
3692   const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3693 
3694   if (should_broadcast) {
3695     const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3696     if (log) {
3697       log->Printf("Process::%s (pid = %" PRIu64
3698                   ") broadcasting new state %s (old state %s) to %s",
3699                   __FUNCTION__, GetID(), StateAsCString(new_state),
3700                   StateAsCString(GetState()),
3701                   is_hijacked ? "hijacked" : "public");
3702     }
3703     Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3704     if (StateIsRunningState(new_state)) {
3705       // Only push the input handler if we aren't fowarding events, as this
3706       // means the curses GUI is in use... Or don't push it if we are launching
3707       // since it will come up stopped.
3708       if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3709           new_state != eStateLaunching && new_state != eStateAttaching) {
3710         PushProcessIOHandler();
3711         m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3712                                   eBroadcastAlways);
3713         if (log)
3714           log->Printf("Process::%s updated m_iohandler_sync to %d",
3715                       __FUNCTION__, m_iohandler_sync.GetValue());
3716       }
3717     } else if (StateIsStoppedState(new_state, false)) {
3718       if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3719         // If the lldb_private::Debugger is handling the events, we don't want
3720         // to pop the process IOHandler here, we want to do it when we receive
3721         // the stopped event so we can carefully control when the process
3722         // IOHandler is popped because when we stop we want to display some
3723         // text stating how and why we stopped, then maybe some
3724         // process/thread/frame info, and then we want the "(lldb) " prompt to
3725         // show up. If we pop the process IOHandler here, then we will cause
3726         // the command interpreter to become the top IOHandler after the
3727         // process pops off and it will update its prompt right away... See the
3728         // Debugger.cpp file where it calls the function as
3729         // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3730         // Otherwise we end up getting overlapping "(lldb) " prompts and
3731         // garbled output.
3732         //
3733         // If we aren't handling the events in the debugger (which is indicated
3734         // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3735         // we are hijacked, then we always pop the process IO handler manually.
3736         // Hijacking happens when the internal process state thread is running
3737         // thread plans, or when commands want to run in synchronous mode and
3738         // they call "process->WaitForProcessToStop()". An example of something
3739         // that will hijack the events is a simple expression:
3740         //
3741         //  (lldb) expr (int)puts("hello")
3742         //
3743         // This will cause the internal process state thread to resume and halt
3744         // the process (and _it_ will hijack the eBroadcastBitStateChanged
3745         // events) and we do need the IO handler to be pushed and popped
3746         // correctly.
3747 
3748         if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3749           PopProcessIOHandler();
3750       }
3751     }
3752 
3753     BroadcastEvent(event_sp);
3754   } else {
3755     if (log) {
3756       log->Printf(
3757           "Process::%s (pid = %" PRIu64
3758           ") suppressing state %s (old state %s): should_broadcast == false",
3759           __FUNCTION__, GetID(), StateAsCString(new_state),
3760           StateAsCString(GetState()));
3761     }
3762   }
3763 }
3764 
3765 Status Process::HaltPrivate() {
3766   EventSP event_sp;
3767   Status error(WillHalt());
3768   if (error.Fail())
3769     return error;
3770 
3771   // Ask the process subclass to actually halt our process
3772   bool caused_stop;
3773   error = DoHalt(caused_stop);
3774 
3775   DidHalt();
3776   return error;
3777 }
3778 
3779 thread_result_t Process::PrivateStateThread(void *arg) {
3780   std::unique_ptr<PrivateStateThreadArgs> args_up(
3781       static_cast<PrivateStateThreadArgs *>(arg));
3782   thread_result_t result =
3783       args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3784   return result;
3785 }
3786 
3787 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3788   bool control_only = true;
3789 
3790   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3791   if (log)
3792     log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3793                 __FUNCTION__, static_cast<void *>(this), GetID());
3794 
3795   bool exit_now = false;
3796   bool interrupt_requested = false;
3797   while (!exit_now) {
3798     EventSP event_sp;
3799     GetEventsPrivate(event_sp, llvm::None, control_only);
3800     if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3801       if (log)
3802         log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3803                     ") got a control event: %d",
3804                     __FUNCTION__, static_cast<void *>(this), GetID(),
3805                     event_sp->GetType());
3806 
3807       switch (event_sp->GetType()) {
3808       case eBroadcastInternalStateControlStop:
3809         exit_now = true;
3810         break; // doing any internal state management below
3811 
3812       case eBroadcastInternalStateControlPause:
3813         control_only = true;
3814         break;
3815 
3816       case eBroadcastInternalStateControlResume:
3817         control_only = false;
3818         break;
3819       }
3820 
3821       continue;
3822     } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3823       if (m_public_state.GetValue() == eStateAttaching) {
3824         if (log)
3825           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3826                       ") woke up with an interrupt while attaching - "
3827                       "forwarding interrupt.",
3828                       __FUNCTION__, static_cast<void *>(this), GetID());
3829         BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3830       } else if (StateIsRunningState(m_last_broadcast_state)) {
3831         if (log)
3832           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3833                       ") woke up with an interrupt - Halting.",
3834                       __FUNCTION__, static_cast<void *>(this), GetID());
3835         Status error = HaltPrivate();
3836         if (error.Fail() && log)
3837           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3838                       ") failed to halt the process: %s",
3839                       __FUNCTION__, static_cast<void *>(this), GetID(),
3840                       error.AsCString());
3841         // Halt should generate a stopped event. Make a note of the fact that
3842         // we were doing the interrupt, so we can set the interrupted flag
3843         // after we receive the event. We deliberately set this to true even if
3844         // HaltPrivate failed, so that we can interrupt on the next natural
3845         // stop.
3846         interrupt_requested = true;
3847       } else {
3848         // This can happen when someone (e.g. Process::Halt) sees that we are
3849         // running and sends an interrupt request, but the process actually
3850         // stops before we receive it. In that case, we can just ignore the
3851         // request. We use m_last_broadcast_state, because the Stopped event
3852         // may not have been popped of the event queue yet, which is when the
3853         // public state gets updated.
3854         if (log)
3855           log->Printf(
3856               "Process::%s ignoring interrupt as we have already stopped.",
3857               __FUNCTION__);
3858       }
3859       continue;
3860     }
3861 
3862     const StateType internal_state =
3863         Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3864 
3865     if (internal_state != eStateInvalid) {
3866       if (m_clear_thread_plans_on_stop &&
3867           StateIsStoppedState(internal_state, true)) {
3868         m_clear_thread_plans_on_stop = false;
3869         m_thread_list.DiscardThreadPlans();
3870       }
3871 
3872       if (interrupt_requested) {
3873         if (StateIsStoppedState(internal_state, true)) {
3874           // We requested the interrupt, so mark this as such in the stop event
3875           // so clients can tell an interrupted process from a natural stop
3876           ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3877           interrupt_requested = false;
3878         } else if (log) {
3879           log->Printf("Process::%s interrupt_requested, but a non-stopped "
3880                       "state '%s' received.",
3881                       __FUNCTION__, StateAsCString(internal_state));
3882         }
3883       }
3884 
3885       HandlePrivateEvent(event_sp);
3886     }
3887 
3888     if (internal_state == eStateInvalid || internal_state == eStateExited ||
3889         internal_state == eStateDetached) {
3890       if (log)
3891         log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3892                     ") about to exit with internal state %s...",
3893                     __FUNCTION__, static_cast<void *>(this), GetID(),
3894                     StateAsCString(internal_state));
3895 
3896       break;
3897     }
3898   }
3899 
3900   // Verify log is still enabled before attempting to write to it...
3901   if (log)
3902     log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3903                 __FUNCTION__, static_cast<void *>(this), GetID());
3904 
3905   // If we are a secondary thread, then the primary thread we are working for
3906   // will have already acquired the public_run_lock, and isn't done with what
3907   // it was doing yet, so don't try to change it on the way out.
3908   if (!is_secondary_thread)
3909     m_public_run_lock.SetStopped();
3910   return NULL;
3911 }
3912 
3913 // Process Event Data
3914 
3915 Process::ProcessEventData::ProcessEventData()
3916     : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3917       m_update_state(0), m_interrupted(false) {}
3918 
3919 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3920                                             StateType state)
3921     : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3922       m_update_state(0), m_interrupted(false) {
3923   if (process_sp)
3924     m_process_wp = process_sp;
3925 }
3926 
3927 Process::ProcessEventData::~ProcessEventData() = default;
3928 
3929 ConstString Process::ProcessEventData::GetFlavorString() {
3930   static ConstString g_flavor("Process::ProcessEventData");
3931   return g_flavor;
3932 }
3933 
3934 ConstString Process::ProcessEventData::GetFlavor() const {
3935   return ProcessEventData::GetFlavorString();
3936 }
3937 
3938 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3939   ProcessSP process_sp(m_process_wp.lock());
3940 
3941   if (!process_sp)
3942     return;
3943 
3944   // This function gets called twice for each event, once when the event gets
3945   // pulled off of the private process event queue, and then any number of
3946   // times, first when it gets pulled off of the public event queue, then other
3947   // times when we're pretending that this is where we stopped at the end of
3948   // expression evaluation.  m_update_state is used to distinguish these three
3949   // cases; it is 0 when we're just pulling it off for private handling, and >
3950   // 1 for expression evaluation, and we don't want to do the breakpoint
3951   // command handling then.
3952   if (m_update_state != 1)
3953     return;
3954 
3955   process_sp->SetPublicState(
3956       m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3957 
3958   if (m_state == eStateStopped && !m_restarted) {
3959     // Let process subclasses know we are about to do a public stop and do
3960     // anything they might need to in order to speed up register and memory
3961     // accesses.
3962     process_sp->WillPublicStop();
3963   }
3964 
3965   // If this is a halt event, even if the halt stopped with some reason other
3966   // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3967   // the halt request came through) don't do the StopInfo actions, as they may
3968   // end up restarting the process.
3969   if (m_interrupted)
3970     return;
3971 
3972   // If we're stopped and haven't restarted, then do the StopInfo actions here:
3973   if (m_state == eStateStopped && !m_restarted) {
3974     ThreadList &curr_thread_list = process_sp->GetThreadList();
3975     uint32_t num_threads = curr_thread_list.GetSize();
3976     uint32_t idx;
3977 
3978     // The actions might change one of the thread's stop_info's opinions about
3979     // whether we should stop the process, so we need to query that as we go.
3980 
3981     // One other complication here, is that we try to catch any case where the
3982     // target has run (except for expressions) and immediately exit, but if we
3983     // get that wrong (which is possible) then the thread list might have
3984     // changed, and that would cause our iteration here to crash.  We could
3985     // make a copy of the thread list, but we'd really like to also know if it
3986     // has changed at all, so we make up a vector of the thread ID's and check
3987     // what we get back against this list & bag out if anything differs.
3988     std::vector<uint32_t> thread_index_array(num_threads);
3989     for (idx = 0; idx < num_threads; ++idx)
3990       thread_index_array[idx] =
3991           curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3992 
3993     // Use this to track whether we should continue from here.  We will only
3994     // continue the target running if no thread says we should stop.  Of course
3995     // if some thread's PerformAction actually sets the target running, then it
3996     // doesn't matter what the other threads say...
3997 
3998     bool still_should_stop = false;
3999 
4000     // Sometimes - for instance if we have a bug in the stub we are talking to,
4001     // we stop but no thread has a valid stop reason.  In that case we should
4002     // just stop, because we have no way of telling what the right thing to do
4003     // is, and it's better to let the user decide than continue behind their
4004     // backs.
4005 
4006     bool does_anybody_have_an_opinion = false;
4007 
4008     for (idx = 0; idx < num_threads; ++idx) {
4009       curr_thread_list = process_sp->GetThreadList();
4010       if (curr_thread_list.GetSize() != num_threads) {
4011         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4012                                                         LIBLLDB_LOG_PROCESS));
4013         if (log)
4014           log->Printf(
4015               "Number of threads changed from %u to %u while processing event.",
4016               num_threads, curr_thread_list.GetSize());
4017         break;
4018       }
4019 
4020       lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4021 
4022       if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4023         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4024                                                         LIBLLDB_LOG_PROCESS));
4025         if (log)
4026           log->Printf("The thread at position %u changed from %u to %u while "
4027                       "processing event.",
4028                       idx, thread_index_array[idx], thread_sp->GetIndexID());
4029         break;
4030       }
4031 
4032       StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4033       if (stop_info_sp && stop_info_sp->IsValid()) {
4034         does_anybody_have_an_opinion = true;
4035         bool this_thread_wants_to_stop;
4036         if (stop_info_sp->GetOverrideShouldStop()) {
4037           this_thread_wants_to_stop =
4038               stop_info_sp->GetOverriddenShouldStopValue();
4039         } else {
4040           stop_info_sp->PerformAction(event_ptr);
4041           // The stop action might restart the target.  If it does, then we
4042           // want to mark that in the event so that whoever is receiving it
4043           // will know to wait for the running event and reflect that state
4044           // appropriately. We also need to stop processing actions, since they
4045           // aren't expecting the target to be running.
4046 
4047           // FIXME: we might have run.
4048           if (stop_info_sp->HasTargetRunSinceMe()) {
4049             SetRestarted(true);
4050             break;
4051           }
4052 
4053           this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4054         }
4055 
4056         if (!still_should_stop)
4057           still_should_stop = this_thread_wants_to_stop;
4058       }
4059     }
4060 
4061     if (!GetRestarted()) {
4062       if (!still_should_stop && does_anybody_have_an_opinion) {
4063         // We've been asked to continue, so do that here.
4064         SetRestarted(true);
4065         // Use the public resume method here, since this is just extending a
4066         // public resume.
4067         process_sp->PrivateResume();
4068       } else {
4069         bool hijacked =
4070           process_sp->IsHijackedForEvent(eBroadcastBitStateChanged)
4071           && !process_sp->StateChangedIsHijackedForSynchronousResume();
4072 
4073         if (!hijacked) {
4074           // If we didn't restart, run the Stop Hooks here.
4075           // Don't do that if state changed events aren't hooked up to the
4076           // public (or SyncResume) broadcasters.  StopHooks are just for
4077           // real public stops.  They might also restart the target,
4078           // so watch for that.
4079           process_sp->GetTarget().RunStopHooks();
4080           if (process_sp->GetPrivateState() == eStateRunning)
4081             SetRestarted(true);
4082       }
4083     }
4084   }
4085 }
4086 }
4087 
4088 void Process::ProcessEventData::Dump(Stream *s) const {
4089   ProcessSP process_sp(m_process_wp.lock());
4090 
4091   if (process_sp)
4092     s->Printf(" process = %p (pid = %" PRIu64 "), ",
4093               static_cast<void *>(process_sp.get()), process_sp->GetID());
4094   else
4095     s->PutCString(" process = NULL, ");
4096 
4097   s->Printf("state = %s", StateAsCString(GetState()));
4098 }
4099 
4100 const Process::ProcessEventData *
4101 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4102   if (event_ptr) {
4103     const EventData *event_data = event_ptr->GetData();
4104     if (event_data &&
4105         event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4106       return static_cast<const ProcessEventData *>(event_ptr->GetData());
4107   }
4108   return nullptr;
4109 }
4110 
4111 ProcessSP
4112 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4113   ProcessSP process_sp;
4114   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4115   if (data)
4116     process_sp = data->GetProcessSP();
4117   return process_sp;
4118 }
4119 
4120 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4121   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4122   if (data == nullptr)
4123     return eStateInvalid;
4124   else
4125     return data->GetState();
4126 }
4127 
4128 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4129   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4130   if (data == nullptr)
4131     return false;
4132   else
4133     return data->GetRestarted();
4134 }
4135 
4136 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4137                                                     bool new_value) {
4138   ProcessEventData *data =
4139       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4140   if (data != nullptr)
4141     data->SetRestarted(new_value);
4142 }
4143 
4144 size_t
4145 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4146   ProcessEventData *data =
4147       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4148   if (data != nullptr)
4149     return data->GetNumRestartedReasons();
4150   else
4151     return 0;
4152 }
4153 
4154 const char *
4155 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4156                                                      size_t idx) {
4157   ProcessEventData *data =
4158       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4159   if (data != nullptr)
4160     return data->GetRestartedReasonAtIndex(idx);
4161   else
4162     return nullptr;
4163 }
4164 
4165 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4166                                                    const char *reason) {
4167   ProcessEventData *data =
4168       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4169   if (data != nullptr)
4170     data->AddRestartedReason(reason);
4171 }
4172 
4173 bool Process::ProcessEventData::GetInterruptedFromEvent(
4174     const Event *event_ptr) {
4175   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4176   if (data == nullptr)
4177     return false;
4178   else
4179     return data->GetInterrupted();
4180 }
4181 
4182 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4183                                                       bool new_value) {
4184   ProcessEventData *data =
4185       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4186   if (data != nullptr)
4187     data->SetInterrupted(new_value);
4188 }
4189 
4190 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4191   ProcessEventData *data =
4192       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4193   if (data) {
4194     data->SetUpdateStateOnRemoval();
4195     return true;
4196   }
4197   return false;
4198 }
4199 
4200 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
4201 
4202 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4203   exe_ctx.SetTargetPtr(&GetTarget());
4204   exe_ctx.SetProcessPtr(this);
4205   exe_ctx.SetThreadPtr(nullptr);
4206   exe_ctx.SetFramePtr(nullptr);
4207 }
4208 
4209 // uint32_t
4210 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4211 // std::vector<lldb::pid_t> &pids)
4212 //{
4213 //    return 0;
4214 //}
4215 //
4216 // ArchSpec
4217 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4218 //{
4219 //    return Host::GetArchSpecForExistingProcess (pid);
4220 //}
4221 //
4222 // ArchSpec
4223 // Process::GetArchSpecForExistingProcess (const char *process_name)
4224 //{
4225 //    return Host::GetArchSpecForExistingProcess (process_name);
4226 //}
4227 
4228 void Process::AppendSTDOUT(const char *s, size_t len) {
4229   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4230   m_stdout_data.append(s, len);
4231   BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4232                          new ProcessEventData(shared_from_this(), GetState()));
4233 }
4234 
4235 void Process::AppendSTDERR(const char *s, size_t len) {
4236   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4237   m_stderr_data.append(s, len);
4238   BroadcastEventIfUnique(eBroadcastBitSTDERR,
4239                          new ProcessEventData(shared_from_this(), GetState()));
4240 }
4241 
4242 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4243   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4244   m_profile_data.push_back(one_profile_data);
4245   BroadcastEventIfUnique(eBroadcastBitProfileData,
4246                          new ProcessEventData(shared_from_this(), GetState()));
4247 }
4248 
4249 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4250                                       const StructuredDataPluginSP &plugin_sp) {
4251   BroadcastEvent(
4252       eBroadcastBitStructuredData,
4253       new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4254 }
4255 
4256 StructuredDataPluginSP
4257 Process::GetStructuredDataPlugin(ConstString type_name) const {
4258   auto find_it = m_structured_data_plugin_map.find(type_name);
4259   if (find_it != m_structured_data_plugin_map.end())
4260     return find_it->second;
4261   else
4262     return StructuredDataPluginSP();
4263 }
4264 
4265 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4266   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4267   if (m_profile_data.empty())
4268     return 0;
4269 
4270   std::string &one_profile_data = m_profile_data.front();
4271   size_t bytes_available = one_profile_data.size();
4272   if (bytes_available > 0) {
4273     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4274     if (log)
4275       log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4276                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4277     if (bytes_available > buf_size) {
4278       memcpy(buf, one_profile_data.c_str(), buf_size);
4279       one_profile_data.erase(0, buf_size);
4280       bytes_available = buf_size;
4281     } else {
4282       memcpy(buf, one_profile_data.c_str(), bytes_available);
4283       m_profile_data.erase(m_profile_data.begin());
4284     }
4285   }
4286   return bytes_available;
4287 }
4288 
4289 // Process STDIO
4290 
4291 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4292   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4293   size_t bytes_available = m_stdout_data.size();
4294   if (bytes_available > 0) {
4295     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4296     if (log)
4297       log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4298                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4299     if (bytes_available > buf_size) {
4300       memcpy(buf, m_stdout_data.c_str(), buf_size);
4301       m_stdout_data.erase(0, buf_size);
4302       bytes_available = buf_size;
4303     } else {
4304       memcpy(buf, m_stdout_data.c_str(), bytes_available);
4305       m_stdout_data.clear();
4306     }
4307   }
4308   return bytes_available;
4309 }
4310 
4311 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4312   std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4313   size_t bytes_available = m_stderr_data.size();
4314   if (bytes_available > 0) {
4315     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4316     if (log)
4317       log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4318                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4319     if (bytes_available > buf_size) {
4320       memcpy(buf, m_stderr_data.c_str(), buf_size);
4321       m_stderr_data.erase(0, buf_size);
4322       bytes_available = buf_size;
4323     } else {
4324       memcpy(buf, m_stderr_data.c_str(), bytes_available);
4325       m_stderr_data.clear();
4326     }
4327   }
4328   return bytes_available;
4329 }
4330 
4331 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4332                                            size_t src_len) {
4333   Process *process = (Process *)baton;
4334   process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4335 }
4336 
4337 class IOHandlerProcessSTDIO : public IOHandler {
4338 public:
4339   IOHandlerProcessSTDIO(Process *process, int write_fd)
4340       : IOHandler(process->GetTarget().GetDebugger(),
4341                   IOHandler::Type::ProcessIO),
4342         m_process(process), m_write_file(write_fd, false) {
4343     m_pipe.CreateNew(false);
4344     m_read_file.SetDescriptor(GetInputFD(), false);
4345   }
4346 
4347   ~IOHandlerProcessSTDIO() override = default;
4348 
4349   // Each IOHandler gets to run until it is done. It should read data from the
4350   // "in" and place output into "out" and "err and return when done.
4351   void Run() override {
4352     if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4353         !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4354       SetIsDone(true);
4355       return;
4356     }
4357 
4358     SetIsDone(false);
4359     const int read_fd = m_read_file.GetDescriptor();
4360     TerminalState terminal_state;
4361     terminal_state.Save(read_fd, false);
4362     Terminal terminal(read_fd);
4363     terminal.SetCanonical(false);
4364     terminal.SetEcho(false);
4365 // FD_ZERO, FD_SET are not supported on windows
4366 #ifndef _WIN32
4367     const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4368     m_is_running = true;
4369     while (!GetIsDone()) {
4370       SelectHelper select_helper;
4371       select_helper.FDSetRead(read_fd);
4372       select_helper.FDSetRead(pipe_read_fd);
4373       Status error = select_helper.Select();
4374 
4375       if (error.Fail()) {
4376         SetIsDone(true);
4377       } else {
4378         char ch = 0;
4379         size_t n;
4380         if (select_helper.FDIsSetRead(read_fd)) {
4381           n = 1;
4382           if (m_read_file.Read(&ch, n).Success() && n == 1) {
4383             if (m_write_file.Write(&ch, n).Fail() || n != 1)
4384               SetIsDone(true);
4385           } else
4386             SetIsDone(true);
4387         }
4388         if (select_helper.FDIsSetRead(pipe_read_fd)) {
4389           size_t bytes_read;
4390           // Consume the interrupt byte
4391           Status error = m_pipe.Read(&ch, 1, bytes_read);
4392           if (error.Success()) {
4393             switch (ch) {
4394             case 'q':
4395               SetIsDone(true);
4396               break;
4397             case 'i':
4398               if (StateIsRunningState(m_process->GetState()))
4399                 m_process->SendAsyncInterrupt();
4400               break;
4401             }
4402           }
4403         }
4404       }
4405     }
4406     m_is_running = false;
4407 #endif
4408     terminal_state.Restore();
4409   }
4410 
4411   void Cancel() override {
4412     SetIsDone(true);
4413     // Only write to our pipe to cancel if we are in
4414     // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4415     // is being run from the command interpreter:
4416     //
4417     // (lldb) step_process_thousands_of_times
4418     //
4419     // In this case the command interpreter will be in the middle of handling
4420     // the command and if the process pushes and pops the IOHandler thousands
4421     // of times, we can end up writing to m_pipe without ever consuming the
4422     // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4423     // deadlocking when the pipe gets fed up and blocks until data is consumed.
4424     if (m_is_running) {
4425       char ch = 'q'; // Send 'q' for quit
4426       size_t bytes_written = 0;
4427       m_pipe.Write(&ch, 1, bytes_written);
4428     }
4429   }
4430 
4431   bool Interrupt() override {
4432     // Do only things that are safe to do in an interrupt context (like in a
4433     // SIGINT handler), like write 1 byte to a file descriptor. This will
4434     // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4435     // that was written to the pipe and then call
4436     // m_process->SendAsyncInterrupt() from a much safer location in code.
4437     if (m_active) {
4438       char ch = 'i'; // Send 'i' for interrupt
4439       size_t bytes_written = 0;
4440       Status result = m_pipe.Write(&ch, 1, bytes_written);
4441       return result.Success();
4442     } else {
4443       // This IOHandler might be pushed on the stack, but not being run
4444       // currently so do the right thing if we aren't actively watching for
4445       // STDIN by sending the interrupt to the process. Otherwise the write to
4446       // the pipe above would do nothing. This can happen when the command
4447       // interpreter is running and gets a "expression ...". It will be on the
4448       // IOHandler thread and sending the input is complete to the delegate
4449       // which will cause the expression to run, which will push the process IO
4450       // handler, but not run it.
4451 
4452       if (StateIsRunningState(m_process->GetState())) {
4453         m_process->SendAsyncInterrupt();
4454         return true;
4455       }
4456     }
4457     return false;
4458   }
4459 
4460   void GotEOF() override {}
4461 
4462 protected:
4463   Process *m_process;
4464   File m_read_file;  // Read from this file (usually actual STDIN for LLDB
4465   File m_write_file; // Write to this file (usually the master pty for getting
4466                      // io to debuggee)
4467   Pipe m_pipe;
4468   std::atomic<bool> m_is_running{false};
4469 };
4470 
4471 void Process::SetSTDIOFileDescriptor(int fd) {
4472   // First set up the Read Thread for reading/handling process I/O
4473 
4474   std::unique_ptr<ConnectionFileDescriptor> conn_up(
4475       new ConnectionFileDescriptor(fd, true));
4476 
4477   if (conn_up) {
4478     m_stdio_communication.SetConnection(conn_up.release());
4479     if (m_stdio_communication.IsConnected()) {
4480       m_stdio_communication.SetReadThreadBytesReceivedCallback(
4481           STDIOReadThreadBytesReceived, this);
4482       m_stdio_communication.StartReadThread();
4483 
4484       // Now read thread is set up, set up input reader.
4485 
4486       if (!m_process_input_reader)
4487         m_process_input_reader =
4488             std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4489     }
4490   }
4491 }
4492 
4493 bool Process::ProcessIOHandlerIsActive() {
4494   IOHandlerSP io_handler_sp(m_process_input_reader);
4495   if (io_handler_sp)
4496     return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4497   return false;
4498 }
4499 bool Process::PushProcessIOHandler() {
4500   IOHandlerSP io_handler_sp(m_process_input_reader);
4501   if (io_handler_sp) {
4502     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4503     if (log)
4504       log->Printf("Process::%s pushing IO handler", __FUNCTION__);
4505 
4506     io_handler_sp->SetIsDone(false);
4507     // If we evaluate an utility function, then we don't cancel the current
4508     // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4509     // existing IOHandler that potentially provides the user interface (e.g.
4510     // the IOHandler for Editline).
4511     bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4512     GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
4513     return true;
4514   }
4515   return false;
4516 }
4517 
4518 bool Process::PopProcessIOHandler() {
4519   IOHandlerSP io_handler_sp(m_process_input_reader);
4520   if (io_handler_sp)
4521     return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4522   return false;
4523 }
4524 
4525 // The process needs to know about installed plug-ins
4526 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4527 
4528 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4529 
4530 namespace {
4531 // RestorePlanState is used to record the "is private", "is master" and "okay
4532 // to discard" fields of the plan we are running, and reset it on Clean or on
4533 // destruction. It will only reset the state once, so you can call Clean and
4534 // then monkey with the state and it won't get reset on you again.
4535 
4536 class RestorePlanState {
4537 public:
4538   RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4539       : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4540     if (m_thread_plan_sp) {
4541       m_private = m_thread_plan_sp->GetPrivate();
4542       m_is_master = m_thread_plan_sp->IsMasterPlan();
4543       m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4544     }
4545   }
4546 
4547   ~RestorePlanState() { Clean(); }
4548 
4549   void Clean() {
4550     if (!m_already_reset && m_thread_plan_sp) {
4551       m_already_reset = true;
4552       m_thread_plan_sp->SetPrivate(m_private);
4553       m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4554       m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4555     }
4556   }
4557 
4558 private:
4559   lldb::ThreadPlanSP m_thread_plan_sp;
4560   bool m_already_reset;
4561   bool m_private;
4562   bool m_is_master;
4563   bool m_okay_to_discard;
4564 };
4565 } // anonymous namespace
4566 
4567 static microseconds
4568 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4569   const milliseconds default_one_thread_timeout(250);
4570 
4571   // If the overall wait is forever, then we don't need to worry about it.
4572   if (!options.GetTimeout()) {
4573     return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4574                                          : default_one_thread_timeout;
4575   }
4576 
4577   // If the one thread timeout is set, use it.
4578   if (options.GetOneThreadTimeout())
4579     return *options.GetOneThreadTimeout();
4580 
4581   // Otherwise use half the total timeout, bounded by the
4582   // default_one_thread_timeout.
4583   return std::min<microseconds>(default_one_thread_timeout,
4584                                 *options.GetTimeout() / 2);
4585 }
4586 
4587 static Timeout<std::micro>
4588 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4589                      bool before_first_timeout) {
4590   // If we are going to run all threads the whole time, or if we are only going
4591   // to run one thread, we can just return the overall timeout.
4592   if (!options.GetStopOthers() || !options.GetTryAllThreads())
4593     return options.GetTimeout();
4594 
4595   if (before_first_timeout)
4596     return GetOneThreadExpressionTimeout(options);
4597 
4598   if (!options.GetTimeout())
4599     return llvm::None;
4600   else
4601     return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4602 }
4603 
4604 static llvm::Optional<ExpressionResults>
4605 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4606                    RestorePlanState &restorer, const EventSP &event_sp,
4607                    EventSP &event_to_broadcast_sp,
4608                    const EvaluateExpressionOptions &options, bool handle_interrupts) {
4609   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4610 
4611   ThreadPlanSP plan = thread.GetCompletedPlan();
4612   if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4613     LLDB_LOG(log, "execution completed successfully");
4614 
4615     // Restore the plan state so it will get reported as intended when we are
4616     // done.
4617     restorer.Clean();
4618     return eExpressionCompleted;
4619   }
4620 
4621   StopInfoSP stop_info_sp = thread.GetStopInfo();
4622   if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4623       stop_info_sp->ShouldNotify(event_sp.get())) {
4624     LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4625     if (!options.DoesIgnoreBreakpoints()) {
4626       // Restore the plan state and then force Private to false.  We are going
4627       // to stop because of this plan so we need it to become a public plan or
4628       // it won't report correctly when we continue to its termination later
4629       // on.
4630       restorer.Clean();
4631       thread_plan_sp->SetPrivate(false);
4632       event_to_broadcast_sp = event_sp;
4633     }
4634     return eExpressionHitBreakpoint;
4635   }
4636 
4637   if (!handle_interrupts &&
4638       Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4639     return llvm::None;
4640 
4641   LLDB_LOG(log, "thread plan did not successfully complete");
4642   if (!options.DoesUnwindOnError())
4643     event_to_broadcast_sp = event_sp;
4644   return eExpressionInterrupted;
4645 }
4646 
4647 ExpressionResults
4648 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4649                        lldb::ThreadPlanSP &thread_plan_sp,
4650                        const EvaluateExpressionOptions &options,
4651                        DiagnosticManager &diagnostic_manager) {
4652   ExpressionResults return_value = eExpressionSetupError;
4653 
4654   std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4655 
4656   if (!thread_plan_sp) {
4657     diagnostic_manager.PutString(
4658         eDiagnosticSeverityError,
4659         "RunThreadPlan called with empty thread plan.");
4660     return eExpressionSetupError;
4661   }
4662 
4663   if (!thread_plan_sp->ValidatePlan(nullptr)) {
4664     diagnostic_manager.PutString(
4665         eDiagnosticSeverityError,
4666         "RunThreadPlan called with an invalid thread plan.");
4667     return eExpressionSetupError;
4668   }
4669 
4670   if (exe_ctx.GetProcessPtr() != this) {
4671     diagnostic_manager.PutString(eDiagnosticSeverityError,
4672                                  "RunThreadPlan called on wrong process.");
4673     return eExpressionSetupError;
4674   }
4675 
4676   Thread *thread = exe_ctx.GetThreadPtr();
4677   if (thread == nullptr) {
4678     diagnostic_manager.PutString(eDiagnosticSeverityError,
4679                                  "RunThreadPlan called with invalid thread.");
4680     return eExpressionSetupError;
4681   }
4682 
4683   // We need to change some of the thread plan attributes for the thread plan
4684   // runner.  This will restore them when we are done:
4685 
4686   RestorePlanState thread_plan_restorer(thread_plan_sp);
4687 
4688   // We rely on the thread plan we are running returning "PlanCompleted" if
4689   // when it successfully completes. For that to be true the plan can't be
4690   // private - since private plans suppress themselves in the GetCompletedPlan
4691   // call.
4692 
4693   thread_plan_sp->SetPrivate(false);
4694 
4695   // The plans run with RunThreadPlan also need to be terminal master plans or
4696   // when they are done we will end up asking the plan above us whether we
4697   // should stop, which may give the wrong answer.
4698 
4699   thread_plan_sp->SetIsMasterPlan(true);
4700   thread_plan_sp->SetOkayToDiscard(false);
4701 
4702   // If we are running some utility expression for LLDB, we now have to mark
4703   // this in the ProcesModID of this process. This RAII takes care of marking
4704   // and reverting the mark it once we are done running the expression.
4705   UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4706 
4707   if (m_private_state.GetValue() != eStateStopped) {
4708     diagnostic_manager.PutString(
4709         eDiagnosticSeverityError,
4710         "RunThreadPlan called while the private state was not stopped.");
4711     return eExpressionSetupError;
4712   }
4713 
4714   // Save the thread & frame from the exe_ctx for restoration after we run
4715   const uint32_t thread_idx_id = thread->GetIndexID();
4716   StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4717   if (!selected_frame_sp) {
4718     thread->SetSelectedFrame(nullptr);
4719     selected_frame_sp = thread->GetSelectedFrame();
4720     if (!selected_frame_sp) {
4721       diagnostic_manager.Printf(
4722           eDiagnosticSeverityError,
4723           "RunThreadPlan called without a selected frame on thread %d",
4724           thread_idx_id);
4725       return eExpressionSetupError;
4726     }
4727   }
4728 
4729   // Make sure the timeout values make sense. The one thread timeout needs to
4730   // be smaller than the overall timeout.
4731   if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4732       *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4733     diagnostic_manager.PutString(eDiagnosticSeverityError,
4734                                  "RunThreadPlan called with one thread "
4735                                  "timeout greater than total timeout");
4736     return eExpressionSetupError;
4737   }
4738 
4739   StackID ctx_frame_id = selected_frame_sp->GetStackID();
4740 
4741   // N.B. Running the target may unset the currently selected thread and frame.
4742   // We don't want to do that either, so we should arrange to reset them as
4743   // well.
4744 
4745   lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4746 
4747   uint32_t selected_tid;
4748   StackID selected_stack_id;
4749   if (selected_thread_sp) {
4750     selected_tid = selected_thread_sp->GetIndexID();
4751     selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4752   } else {
4753     selected_tid = LLDB_INVALID_THREAD_ID;
4754   }
4755 
4756   HostThread backup_private_state_thread;
4757   lldb::StateType old_state = eStateInvalid;
4758   lldb::ThreadPlanSP stopper_base_plan_sp;
4759 
4760   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4761                                                   LIBLLDB_LOG_PROCESS));
4762   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4763     // Yikes, we are running on the private state thread!  So we can't wait for
4764     // public events on this thread, since we are the thread that is generating
4765     // public events. The simplest thing to do is to spin up a temporary thread
4766     // to handle private state thread events while we are fielding public
4767     // events here.
4768     if (log)
4769       log->Printf("Running thread plan on private state thread, spinning up "
4770                   "another state thread to handle the events.");
4771 
4772     backup_private_state_thread = m_private_state_thread;
4773 
4774     // One other bit of business: we want to run just this thread plan and
4775     // anything it pushes, and then stop, returning control here. But in the
4776     // normal course of things, the plan above us on the stack would be given a
4777     // shot at the stop event before deciding to stop, and we don't want that.
4778     // So we insert a "stopper" base plan on the stack before the plan we want
4779     // to run.  Since base plans always stop and return control to the user,
4780     // that will do just what we want.
4781     stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4782     thread->QueueThreadPlan(stopper_base_plan_sp, false);
4783     // Have to make sure our public state is stopped, since otherwise the
4784     // reporting logic below doesn't work correctly.
4785     old_state = m_public_state.GetValue();
4786     m_public_state.SetValueNoLock(eStateStopped);
4787 
4788     // Now spin up the private state thread:
4789     StartPrivateStateThread(true);
4790   }
4791 
4792   thread->QueueThreadPlan(
4793       thread_plan_sp, false); // This used to pass "true" does that make sense?
4794 
4795   if (options.GetDebug()) {
4796     // In this case, we aren't actually going to run, we just want to stop
4797     // right away. Flush this thread so we will refetch the stacks and show the
4798     // correct backtrace.
4799     // FIXME: To make this prettier we should invent some stop reason for this,
4800     // but that
4801     // is only cosmetic, and this functionality is only of use to lldb
4802     // developers who can live with not pretty...
4803     thread->Flush();
4804     return eExpressionStoppedForDebug;
4805   }
4806 
4807   ListenerSP listener_sp(
4808       Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4809 
4810   lldb::EventSP event_to_broadcast_sp;
4811 
4812   {
4813     // This process event hijacker Hijacks the Public events and its destructor
4814     // makes sure that the process events get restored on exit to the function.
4815     //
4816     // If the event needs to propagate beyond the hijacker (e.g., the process
4817     // exits during execution), then the event is put into
4818     // event_to_broadcast_sp for rebroadcasting.
4819 
4820     ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4821 
4822     if (log) {
4823       StreamString s;
4824       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4825       log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4826                   " to run thread plan \"%s\".",
4827                   thread->GetIndexID(), thread->GetID(), s.GetData());
4828     }
4829 
4830     bool got_event;
4831     lldb::EventSP event_sp;
4832     lldb::StateType stop_state = lldb::eStateInvalid;
4833 
4834     bool before_first_timeout = true; // This is set to false the first time
4835                                       // that we have to halt the target.
4836     bool do_resume = true;
4837     bool handle_running_event = true;
4838 
4839     // This is just for accounting:
4840     uint32_t num_resumes = 0;
4841 
4842     // If we are going to run all threads the whole time, or if we are only
4843     // going to run one thread, then we don't need the first timeout.  So we
4844     // pretend we are after the first timeout already.
4845     if (!options.GetStopOthers() || !options.GetTryAllThreads())
4846       before_first_timeout = false;
4847 
4848     if (log)
4849       log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
4850                   options.GetStopOthers(), options.GetTryAllThreads(),
4851                   before_first_timeout);
4852 
4853     // This isn't going to work if there are unfetched events on the queue. Are
4854     // there cases where we might want to run the remaining events here, and
4855     // then try to call the function?  That's probably being too tricky for our
4856     // own good.
4857 
4858     Event *other_events = listener_sp->PeekAtNextEvent();
4859     if (other_events != nullptr) {
4860       diagnostic_manager.PutString(
4861           eDiagnosticSeverityError,
4862           "RunThreadPlan called with pending events on the queue.");
4863       return eExpressionSetupError;
4864     }
4865 
4866     // We also need to make sure that the next event is delivered.  We might be
4867     // calling a function as part of a thread plan, in which case the last
4868     // delivered event could be the running event, and we don't want event
4869     // coalescing to cause us to lose OUR running event...
4870     ForceNextEventDelivery();
4871 
4872 // This while loop must exit out the bottom, there's cleanup that we need to do
4873 // when we are done. So don't call return anywhere within it.
4874 
4875 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4876     // It's pretty much impossible to write test cases for things like: One
4877     // thread timeout expires, I go to halt, but the process already stopped on
4878     // the function call stop breakpoint.  Turning on this define will make us
4879     // not fetch the first event till after the halt.  So if you run a quick
4880     // function, it will have completed, and the completion event will be
4881     // waiting, when you interrupt for halt. The expression evaluation should
4882     // still succeed.
4883     bool miss_first_event = true;
4884 #endif
4885     while (true) {
4886       // We usually want to resume the process if we get to the top of the
4887       // loop. The only exception is if we get two running events with no
4888       // intervening stop, which can happen, we will just wait for then next
4889       // stop event.
4890       if (log)
4891         log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
4892                     "before_first_timeout: %i.",
4893                     do_resume, handle_running_event, before_first_timeout);
4894 
4895       if (do_resume || handle_running_event) {
4896         // Do the initial resume and wait for the running event before going
4897         // further.
4898 
4899         if (do_resume) {
4900           num_resumes++;
4901           Status resume_error = PrivateResume();
4902           if (!resume_error.Success()) {
4903             diagnostic_manager.Printf(
4904                 eDiagnosticSeverityError,
4905                 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4906                 resume_error.AsCString());
4907             return_value = eExpressionSetupError;
4908             break;
4909           }
4910         }
4911 
4912         got_event =
4913             listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
4914         if (!got_event) {
4915           if (log)
4916             log->Printf("Process::RunThreadPlan(): didn't get any event after "
4917                         "resume %" PRIu32 ", exiting.",
4918                         num_resumes);
4919 
4920           diagnostic_manager.Printf(eDiagnosticSeverityError,
4921                                     "didn't get any event after resume %" PRIu32
4922                                     ", exiting.",
4923                                     num_resumes);
4924           return_value = eExpressionSetupError;
4925           break;
4926         }
4927 
4928         stop_state =
4929             Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4930 
4931         if (stop_state != eStateRunning) {
4932           bool restarted = false;
4933 
4934           if (stop_state == eStateStopped) {
4935             restarted = Process::ProcessEventData::GetRestartedFromEvent(
4936                 event_sp.get());
4937             if (log)
4938               log->Printf(
4939                   "Process::RunThreadPlan(): didn't get running event after "
4940                   "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4941                   "handle_running_event: %i).",
4942                   num_resumes, StateAsCString(stop_state), restarted, do_resume,
4943                   handle_running_event);
4944           }
4945 
4946           if (restarted) {
4947             // This is probably an overabundance of caution, I don't think I
4948             // should ever get a stopped & restarted event here.  But if I do,
4949             // the best thing is to Halt and then get out of here.
4950             const bool clear_thread_plans = false;
4951             const bool use_run_lock = false;
4952             Halt(clear_thread_plans, use_run_lock);
4953           }
4954 
4955           diagnostic_manager.Printf(
4956               eDiagnosticSeverityError,
4957               "didn't get running event after initial resume, got %s instead.",
4958               StateAsCString(stop_state));
4959           return_value = eExpressionSetupError;
4960           break;
4961         }
4962 
4963         if (log)
4964           log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
4965         // We need to call the function synchronously, so spin waiting for it
4966         // to return. If we get interrupted while executing, we're going to
4967         // lose our context, and won't be able to gather the result at this
4968         // point. We set the timeout AFTER the resume, since the resume takes
4969         // some time and we don't want to charge that to the timeout.
4970       } else {
4971         if (log)
4972           log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4973       }
4974 
4975       do_resume = true;
4976       handle_running_event = true;
4977 
4978       // Now wait for the process to stop again:
4979       event_sp.reset();
4980 
4981       Timeout<std::micro> timeout =
4982           GetExpressionTimeout(options, before_first_timeout);
4983       if (log) {
4984         if (timeout) {
4985           auto now = system_clock::now();
4986           log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
4987                       "endpoint is %s",
4988                       llvm::to_string(now).c_str(),
4989                       llvm::to_string(now + *timeout).c_str());
4990         } else {
4991           log->Printf("Process::RunThreadPlan(): about to wait forever.");
4992         }
4993       }
4994 
4995 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4996       // See comment above...
4997       if (miss_first_event) {
4998         usleep(1000);
4999         miss_first_event = false;
5000         got_event = false;
5001       } else
5002 #endif
5003         got_event = listener_sp->GetEvent(event_sp, timeout);
5004 
5005       if (got_event) {
5006         if (event_sp) {
5007           bool keep_going = false;
5008           if (event_sp->GetType() == eBroadcastBitInterrupt) {
5009             const bool clear_thread_plans = false;
5010             const bool use_run_lock = false;
5011             Halt(clear_thread_plans, use_run_lock);
5012             return_value = eExpressionInterrupted;
5013             diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5014                                          "execution halted by user interrupt.");
5015             if (log)
5016               log->Printf("Process::RunThreadPlan(): Got  interrupted by "
5017                           "eBroadcastBitInterrupted, exiting.");
5018             break;
5019           } else {
5020             stop_state =
5021                 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5022             if (log)
5023               log->Printf(
5024                   "Process::RunThreadPlan(): in while loop, got event: %s.",
5025                   StateAsCString(stop_state));
5026 
5027             switch (stop_state) {
5028             case lldb::eStateStopped: {
5029               // We stopped, figure out what we are going to do now.
5030               ThreadSP thread_sp =
5031                   GetThreadList().FindThreadByIndexID(thread_idx_id);
5032               if (!thread_sp) {
5033                 // Ooh, our thread has vanished.  Unlikely that this was
5034                 // successful execution...
5035                 if (log)
5036                   log->Printf("Process::RunThreadPlan(): execution completed "
5037                               "but our thread (index-id=%u) has vanished.",
5038                               thread_idx_id);
5039                 return_value = eExpressionInterrupted;
5040               } else if (Process::ProcessEventData::GetRestartedFromEvent(
5041                              event_sp.get())) {
5042                 // If we were restarted, we just need to go back up to fetch
5043                 // another event.
5044                 if (log) {
5045                   log->Printf("Process::RunThreadPlan(): Got a stop and "
5046                               "restart, so we'll continue waiting.");
5047                 }
5048                 keep_going = true;
5049                 do_resume = false;
5050                 handle_running_event = true;
5051               } else {
5052                 const bool handle_interrupts = true;
5053                 return_value = *HandleStoppedEvent(
5054                     *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5055                     event_to_broadcast_sp, options, handle_interrupts);
5056               }
5057             } break;
5058 
5059             case lldb::eStateRunning:
5060               // This shouldn't really happen, but sometimes we do get two
5061               // running events without an intervening stop, and in that case
5062               // we should just go back to waiting for the stop.
5063               do_resume = false;
5064               keep_going = true;
5065               handle_running_event = false;
5066               break;
5067 
5068             default:
5069               if (log)
5070                 log->Printf("Process::RunThreadPlan(): execution stopped with "
5071                             "unexpected state: %s.",
5072                             StateAsCString(stop_state));
5073 
5074               if (stop_state == eStateExited)
5075                 event_to_broadcast_sp = event_sp;
5076 
5077               diagnostic_manager.PutString(
5078                   eDiagnosticSeverityError,
5079                   "execution stopped with unexpected state.");
5080               return_value = eExpressionInterrupted;
5081               break;
5082             }
5083           }
5084 
5085           if (keep_going)
5086             continue;
5087           else
5088             break;
5089         } else {
5090           if (log)
5091             log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5092                             "the event pointer was null.  How odd...");
5093           return_value = eExpressionInterrupted;
5094           break;
5095         }
5096       } else {
5097         // If we didn't get an event that means we've timed out... We will
5098         // interrupt the process here.  Depending on what we were asked to do
5099         // we will either exit, or try with all threads running for the same
5100         // timeout.
5101 
5102         if (log) {
5103           if (options.GetTryAllThreads()) {
5104             if (before_first_timeout) {
5105               LLDB_LOG(log,
5106                        "Running function with one thread timeout timed out.");
5107             } else
5108               LLDB_LOG(log, "Restarting function with all threads enabled and "
5109                             "timeout: {0} timed out, abandoning execution.",
5110                        timeout);
5111           } else
5112             LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5113                           "abandoning execution.",
5114                      timeout);
5115         }
5116 
5117         // It is possible that between the time we issued the Halt, and we get
5118         // around to calling Halt the target could have stopped.  That's fine,
5119         // Halt will figure that out and send the appropriate Stopped event.
5120         // BUT it is also possible that we stopped & restarted (e.g. hit a
5121         // signal with "stop" set to false.)  In
5122         // that case, we'll get the stopped & restarted event, and we should go
5123         // back to waiting for the Halt's stopped event.  That's what this
5124         // while loop does.
5125 
5126         bool back_to_top = true;
5127         uint32_t try_halt_again = 0;
5128         bool do_halt = true;
5129         const uint32_t num_retries = 5;
5130         while (try_halt_again < num_retries) {
5131           Status halt_error;
5132           if (do_halt) {
5133             if (log)
5134               log->Printf("Process::RunThreadPlan(): Running Halt.");
5135             const bool clear_thread_plans = false;
5136             const bool use_run_lock = false;
5137             Halt(clear_thread_plans, use_run_lock);
5138           }
5139           if (halt_error.Success()) {
5140             if (log)
5141               log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5142 
5143             got_event =
5144                 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5145 
5146             if (got_event) {
5147               stop_state =
5148                   Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5149               if (log) {
5150                 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5151                             StateAsCString(stop_state));
5152                 if (stop_state == lldb::eStateStopped &&
5153                     Process::ProcessEventData::GetInterruptedFromEvent(
5154                         event_sp.get()))
5155                   log->PutCString("    Event was the Halt interruption event.");
5156               }
5157 
5158               if (stop_state == lldb::eStateStopped) {
5159                 if (Process::ProcessEventData::GetRestartedFromEvent(
5160                         event_sp.get())) {
5161                   if (log)
5162                     log->PutCString("Process::RunThreadPlan(): Went to halt "
5163                                     "but got a restarted event, there must be "
5164                                     "an un-restarted stopped event so try "
5165                                     "again...  "
5166                                     "Exiting wait loop.");
5167                   try_halt_again++;
5168                   do_halt = false;
5169                   continue;
5170                 }
5171 
5172                 // Between the time we initiated the Halt and the time we
5173                 // delivered it, the process could have already finished its
5174                 // job.  Check that here:
5175                 const bool handle_interrupts = false;
5176                 if (auto result = HandleStoppedEvent(
5177                         *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5178                         event_to_broadcast_sp, options, handle_interrupts)) {
5179                   return_value = *result;
5180                   back_to_top = false;
5181                   break;
5182                 }
5183 
5184                 if (!options.GetTryAllThreads()) {
5185                   if (log)
5186                     log->PutCString("Process::RunThreadPlan(): try_all_threads "
5187                                     "was false, we stopped so now we're "
5188                                     "quitting.");
5189                   return_value = eExpressionInterrupted;
5190                   back_to_top = false;
5191                   break;
5192                 }
5193 
5194                 if (before_first_timeout) {
5195                   // Set all the other threads to run, and return to the top of
5196                   // the loop, which will continue;
5197                   before_first_timeout = false;
5198                   thread_plan_sp->SetStopOthers(false);
5199                   if (log)
5200                     log->PutCString(
5201                         "Process::RunThreadPlan(): about to resume.");
5202 
5203                   back_to_top = true;
5204                   break;
5205                 } else {
5206                   // Running all threads failed, so return Interrupted.
5207                   if (log)
5208                     log->PutCString("Process::RunThreadPlan(): running all "
5209                                     "threads timed out.");
5210                   return_value = eExpressionInterrupted;
5211                   back_to_top = false;
5212                   break;
5213                 }
5214               }
5215             } else {
5216               if (log)
5217                 log->PutCString("Process::RunThreadPlan(): halt said it "
5218                                 "succeeded, but I got no event.  "
5219                                 "I'm getting out of here passing Interrupted.");
5220               return_value = eExpressionInterrupted;
5221               back_to_top = false;
5222               break;
5223             }
5224           } else {
5225             try_halt_again++;
5226             continue;
5227           }
5228         }
5229 
5230         if (!back_to_top || try_halt_again > num_retries)
5231           break;
5232         else
5233           continue;
5234       }
5235     } // END WAIT LOOP
5236 
5237     // If we had to start up a temporary private state thread to run this
5238     // thread plan, shut it down now.
5239     if (backup_private_state_thread.IsJoinable()) {
5240       StopPrivateStateThread();
5241       Status error;
5242       m_private_state_thread = backup_private_state_thread;
5243       if (stopper_base_plan_sp) {
5244         thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5245       }
5246       if (old_state != eStateInvalid)
5247         m_public_state.SetValueNoLock(old_state);
5248     }
5249 
5250     if (return_value != eExpressionCompleted && log) {
5251       // Print a backtrace into the log so we can figure out where we are:
5252       StreamString s;
5253       s.PutCString("Thread state after unsuccessful completion: \n");
5254       thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5255       log->PutString(s.GetString());
5256     }
5257     // Restore the thread state if we are going to discard the plan execution.
5258     // There are three cases where this could happen: 1) The execution
5259     // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5260     // was true 3) We got some other error, and discard_on_error was true
5261     bool should_unwind = (return_value == eExpressionInterrupted &&
5262                           options.DoesUnwindOnError()) ||
5263                          (return_value == eExpressionHitBreakpoint &&
5264                           options.DoesIgnoreBreakpoints());
5265 
5266     if (return_value == eExpressionCompleted || should_unwind) {
5267       thread_plan_sp->RestoreThreadState();
5268     }
5269 
5270     // Now do some processing on the results of the run:
5271     if (return_value == eExpressionInterrupted ||
5272         return_value == eExpressionHitBreakpoint) {
5273       if (log) {
5274         StreamString s;
5275         if (event_sp)
5276           event_sp->Dump(&s);
5277         else {
5278           log->PutCString("Process::RunThreadPlan(): Stop event that "
5279                           "interrupted us is NULL.");
5280         }
5281 
5282         StreamString ts;
5283 
5284         const char *event_explanation = nullptr;
5285 
5286         do {
5287           if (!event_sp) {
5288             event_explanation = "<no event>";
5289             break;
5290           } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5291             event_explanation = "<user interrupt>";
5292             break;
5293           } else {
5294             const Process::ProcessEventData *event_data =
5295                 Process::ProcessEventData::GetEventDataFromEvent(
5296                     event_sp.get());
5297 
5298             if (!event_data) {
5299               event_explanation = "<no event data>";
5300               break;
5301             }
5302 
5303             Process *process = event_data->GetProcessSP().get();
5304 
5305             if (!process) {
5306               event_explanation = "<no process>";
5307               break;
5308             }
5309 
5310             ThreadList &thread_list = process->GetThreadList();
5311 
5312             uint32_t num_threads = thread_list.GetSize();
5313             uint32_t thread_index;
5314 
5315             ts.Printf("<%u threads> ", num_threads);
5316 
5317             for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5318               Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5319 
5320               if (!thread) {
5321                 ts.Printf("<?> ");
5322                 continue;
5323               }
5324 
5325               ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5326               RegisterContext *register_context =
5327                   thread->GetRegisterContext().get();
5328 
5329               if (register_context)
5330                 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5331               else
5332                 ts.Printf("[ip unknown] ");
5333 
5334               // Show the private stop info here, the public stop info will be
5335               // from the last natural stop.
5336               lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5337               if (stop_info_sp) {
5338                 const char *stop_desc = stop_info_sp->GetDescription();
5339                 if (stop_desc)
5340                   ts.PutCString(stop_desc);
5341               }
5342               ts.Printf(">");
5343             }
5344 
5345             event_explanation = ts.GetData();
5346           }
5347         } while (0);
5348 
5349         if (event_explanation)
5350           log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5351                       s.GetData(), event_explanation);
5352         else
5353           log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5354                       s.GetData());
5355       }
5356 
5357       if (should_unwind) {
5358         if (log)
5359           log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5360                       "discarding thread plans up to %p.",
5361                       static_cast<void *>(thread_plan_sp.get()));
5362         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5363       } else {
5364         if (log)
5365           log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5366                       "plan: %p not discarding.",
5367                       static_cast<void *>(thread_plan_sp.get()));
5368       }
5369     } else if (return_value == eExpressionSetupError) {
5370       if (log)
5371         log->PutCString("Process::RunThreadPlan(): execution set up error.");
5372 
5373       if (options.DoesUnwindOnError()) {
5374         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5375       }
5376     } else {
5377       if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5378         if (log)
5379           log->PutCString("Process::RunThreadPlan(): thread plan is done");
5380         return_value = eExpressionCompleted;
5381       } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5382         if (log)
5383           log->PutCString(
5384               "Process::RunThreadPlan(): thread plan was discarded");
5385         return_value = eExpressionDiscarded;
5386       } else {
5387         if (log)
5388           log->PutCString(
5389               "Process::RunThreadPlan(): thread plan stopped in mid course");
5390         if (options.DoesUnwindOnError() && thread_plan_sp) {
5391           if (log)
5392             log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5393                             "'cause unwind_on_error is set.");
5394           thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5395         }
5396       }
5397     }
5398 
5399     // Thread we ran the function in may have gone away because we ran the
5400     // target Check that it's still there, and if it is put it back in the
5401     // context. Also restore the frame in the context if it is still present.
5402     thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5403     if (thread) {
5404       exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5405     }
5406 
5407     // Also restore the current process'es selected frame & thread, since this
5408     // function calling may be done behind the user's back.
5409 
5410     if (selected_tid != LLDB_INVALID_THREAD_ID) {
5411       if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5412           selected_stack_id.IsValid()) {
5413         // We were able to restore the selected thread, now restore the frame:
5414         std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5415         StackFrameSP old_frame_sp =
5416             GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5417                 selected_stack_id);
5418         if (old_frame_sp)
5419           GetThreadList().GetSelectedThread()->SetSelectedFrame(
5420               old_frame_sp.get());
5421       }
5422     }
5423   }
5424 
5425   // If the process exited during the run of the thread plan, notify everyone.
5426 
5427   if (event_to_broadcast_sp) {
5428     if (log)
5429       log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5430     BroadcastEvent(event_to_broadcast_sp);
5431   }
5432 
5433   return return_value;
5434 }
5435 
5436 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5437   const char *result_name;
5438 
5439   switch (result) {
5440   case eExpressionCompleted:
5441     result_name = "eExpressionCompleted";
5442     break;
5443   case eExpressionDiscarded:
5444     result_name = "eExpressionDiscarded";
5445     break;
5446   case eExpressionInterrupted:
5447     result_name = "eExpressionInterrupted";
5448     break;
5449   case eExpressionHitBreakpoint:
5450     result_name = "eExpressionHitBreakpoint";
5451     break;
5452   case eExpressionSetupError:
5453     result_name = "eExpressionSetupError";
5454     break;
5455   case eExpressionParseError:
5456     result_name = "eExpressionParseError";
5457     break;
5458   case eExpressionResultUnavailable:
5459     result_name = "eExpressionResultUnavailable";
5460     break;
5461   case eExpressionTimedOut:
5462     result_name = "eExpressionTimedOut";
5463     break;
5464   case eExpressionStoppedForDebug:
5465     result_name = "eExpressionStoppedForDebug";
5466     break;
5467   }
5468   return result_name;
5469 }
5470 
5471 void Process::GetStatus(Stream &strm) {
5472   const StateType state = GetState();
5473   if (StateIsStoppedState(state, false)) {
5474     if (state == eStateExited) {
5475       int exit_status = GetExitStatus();
5476       const char *exit_description = GetExitDescription();
5477       strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5478                   GetID(), exit_status, exit_status,
5479                   exit_description ? exit_description : "");
5480     } else {
5481       if (state == eStateConnected)
5482         strm.Printf("Connected to remote target.\n");
5483       else
5484         strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5485     }
5486   } else {
5487     strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5488   }
5489 }
5490 
5491 size_t Process::GetThreadStatus(Stream &strm,
5492                                 bool only_threads_with_stop_reason,
5493                                 uint32_t start_frame, uint32_t num_frames,
5494                                 uint32_t num_frames_with_source,
5495                                 bool stop_format) {
5496   size_t num_thread_infos_dumped = 0;
5497 
5498   // You can't hold the thread list lock while calling Thread::GetStatus.  That
5499   // very well might run code (e.g. if we need it to get return values or
5500   // arguments.)  For that to work the process has to be able to acquire it.
5501   // So instead copy the thread ID's, and look them up one by one:
5502 
5503   uint32_t num_threads;
5504   std::vector<lldb::tid_t> thread_id_array;
5505   // Scope for thread list locker;
5506   {
5507     std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5508     ThreadList &curr_thread_list = GetThreadList();
5509     num_threads = curr_thread_list.GetSize();
5510     uint32_t idx;
5511     thread_id_array.resize(num_threads);
5512     for (idx = 0; idx < num_threads; ++idx)
5513       thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5514   }
5515 
5516   for (uint32_t i = 0; i < num_threads; i++) {
5517     ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5518     if (thread_sp) {
5519       if (only_threads_with_stop_reason) {
5520         StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5521         if (!stop_info_sp || !stop_info_sp->IsValid())
5522           continue;
5523       }
5524       thread_sp->GetStatus(strm, start_frame, num_frames,
5525                            num_frames_with_source,
5526                            stop_format);
5527       ++num_thread_infos_dumped;
5528     } else {
5529       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5530       if (log)
5531         log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5532                     " vanished while running Thread::GetStatus.");
5533     }
5534   }
5535   return num_thread_infos_dumped;
5536 }
5537 
5538 void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5539   m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5540 }
5541 
5542 bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5543   return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5544                                            region.GetByteSize());
5545 }
5546 
5547 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5548                                  void *baton) {
5549   m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5550 }
5551 
5552 bool Process::RunPreResumeActions() {
5553   bool result = true;
5554   while (!m_pre_resume_actions.empty()) {
5555     struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5556     m_pre_resume_actions.pop_back();
5557     bool this_result = action.callback(action.baton);
5558     if (result)
5559       result = this_result;
5560   }
5561   return result;
5562 }
5563 
5564 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5565 
5566 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5567 {
5568     PreResumeCallbackAndBaton element(callback, baton);
5569     auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5570     if (found_iter != m_pre_resume_actions.end())
5571     {
5572         m_pre_resume_actions.erase(found_iter);
5573     }
5574 }
5575 
5576 ProcessRunLock &Process::GetRunLock() {
5577   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5578     return m_private_run_lock;
5579   else
5580     return m_public_run_lock;
5581 }
5582 
5583 void Process::Flush() {
5584   m_thread_list.Flush();
5585   m_extended_thread_list.Flush();
5586   m_extended_thread_stop_id = 0;
5587   m_queue_list.Clear();
5588   m_queue_list_stop_id = 0;
5589 }
5590 
5591 void Process::DidExec() {
5592   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5593   if (log)
5594     log->Printf("Process::%s()", __FUNCTION__);
5595 
5596   Target &target = GetTarget();
5597   target.CleanupProcess();
5598   target.ClearModules(false);
5599   m_dynamic_checkers_up.reset();
5600   m_abi_sp.reset();
5601   m_system_runtime_up.reset();
5602   m_os_up.reset();
5603   m_dyld_up.reset();
5604   m_jit_loaders_up.reset();
5605   m_image_tokens.clear();
5606   m_allocated_memory_cache.Clear();
5607   m_language_runtimes.clear();
5608   m_instrumentation_runtimes.clear();
5609   m_thread_list.DiscardThreadPlans();
5610   m_memory_cache.Clear(true);
5611   DoDidExec();
5612   CompleteAttach();
5613   // Flush the process (threads and all stack frames) after running
5614   // CompleteAttach() in case the dynamic loader loaded things in new
5615   // locations.
5616   Flush();
5617 
5618   // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5619   // let the target know so it can do any cleanup it needs to.
5620   target.DidExec();
5621 }
5622 
5623 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
5624   if (address == nullptr) {
5625     error.SetErrorString("Invalid address argument");
5626     return LLDB_INVALID_ADDRESS;
5627   }
5628 
5629   addr_t function_addr = LLDB_INVALID_ADDRESS;
5630 
5631   addr_t addr = address->GetLoadAddress(&GetTarget());
5632   std::map<addr_t, addr_t>::const_iterator iter =
5633       m_resolved_indirect_addresses.find(addr);
5634   if (iter != m_resolved_indirect_addresses.end()) {
5635     function_addr = (*iter).second;
5636   } else {
5637     if (!InferiorCall(this, address, function_addr)) {
5638       Symbol *symbol = address->CalculateSymbolContextSymbol();
5639       error.SetErrorStringWithFormat(
5640           "Unable to call resolver for indirect function %s",
5641           symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5642       function_addr = LLDB_INVALID_ADDRESS;
5643     } else {
5644       m_resolved_indirect_addresses.insert(
5645           std::pair<addr_t, addr_t>(addr, function_addr));
5646     }
5647   }
5648   return function_addr;
5649 }
5650 
5651 void Process::ModulesDidLoad(ModuleList &module_list) {
5652   SystemRuntime *sys_runtime = GetSystemRuntime();
5653   if (sys_runtime) {
5654     sys_runtime->ModulesDidLoad(module_list);
5655   }
5656 
5657   GetJITLoaders().ModulesDidLoad(module_list);
5658 
5659   // Give runtimes a chance to be created.
5660   InstrumentationRuntime::ModulesDidLoad(module_list, this,
5661                                          m_instrumentation_runtimes);
5662 
5663   // Tell runtimes about new modules.
5664   for (auto pos = m_instrumentation_runtimes.begin();
5665        pos != m_instrumentation_runtimes.end(); ++pos) {
5666     InstrumentationRuntimeSP runtime = pos->second;
5667     runtime->ModulesDidLoad(module_list);
5668   }
5669 
5670   // Let any language runtimes we have already created know about the modules
5671   // that loaded.
5672 
5673   // Iterate over a copy of this language runtime list in case the language
5674   // runtime ModulesDidLoad somehow causes the language runtime to be
5675   // unloaded.
5676   LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5677   for (const auto &pair : language_runtimes) {
5678     // We must check language_runtime_sp to make sure it is not nullptr as we
5679     // might cache the fact that we didn't have a language runtime for a
5680     // language.
5681     LanguageRuntimeSP language_runtime_sp = pair.second;
5682     if (language_runtime_sp)
5683       language_runtime_sp->ModulesDidLoad(module_list);
5684   }
5685 
5686   // If we don't have an operating system plug-in, try to load one since
5687   // loading shared libraries might cause a new one to try and load
5688   if (!m_os_up)
5689     LoadOperatingSystemPlugin(false);
5690 
5691   // Give structured-data plugins a chance to see the modified modules.
5692   for (auto pair : m_structured_data_plugin_map) {
5693     if (pair.second)
5694       pair.second->ModulesDidLoad(*this, module_list);
5695   }
5696 }
5697 
5698 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5699                            const char *fmt, ...) {
5700   bool print_warning = true;
5701 
5702   StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5703   if (!stream_sp)
5704     return;
5705   if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5706     return;
5707   }
5708 
5709   if (repeat_key != nullptr) {
5710     WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5711     if (it == m_warnings_issued.end()) {
5712       m_warnings_issued[warning_type] = WarningsPointerSet();
5713       m_warnings_issued[warning_type].insert(repeat_key);
5714     } else {
5715       if (it->second.find(repeat_key) != it->second.end()) {
5716         print_warning = false;
5717       } else {
5718         it->second.insert(repeat_key);
5719       }
5720     }
5721   }
5722 
5723   if (print_warning) {
5724     va_list args;
5725     va_start(args, fmt);
5726     stream_sp->PrintfVarArg(fmt, args);
5727     va_end(args);
5728   }
5729 }
5730 
5731 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5732   if (GetWarningsOptimization() && sc.module_sp &&
5733       !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5734       sc.function->GetIsOptimized()) {
5735     PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5736                  "%s was compiled with optimization - stepping may behave "
5737                  "oddly; variables may not be available.\n",
5738                  sc.module_sp->GetFileSpec().GetFilename().GetCString());
5739   }
5740 }
5741 
5742 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5743   info.Clear();
5744 
5745   PlatformSP platform_sp = GetTarget().GetPlatform();
5746   if (!platform_sp)
5747     return false;
5748 
5749   return platform_sp->GetProcessInfo(GetID(), info);
5750 }
5751 
5752 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5753   ThreadCollectionSP threads;
5754 
5755   const MemoryHistorySP &memory_history =
5756       MemoryHistory::FindPlugin(shared_from_this());
5757 
5758   if (!memory_history) {
5759     return threads;
5760   }
5761 
5762   threads = std::make_shared<ThreadCollection>(
5763       memory_history->GetHistoryThreads(addr));
5764 
5765   return threads;
5766 }
5767 
5768 InstrumentationRuntimeSP
5769 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5770   InstrumentationRuntimeCollection::iterator pos;
5771   pos = m_instrumentation_runtimes.find(type);
5772   if (pos == m_instrumentation_runtimes.end()) {
5773     return InstrumentationRuntimeSP();
5774   } else
5775     return (*pos).second;
5776 }
5777 
5778 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5779                             const ArchSpec &arch, ModuleSpec &module_spec) {
5780   module_spec.Clear();
5781   return false;
5782 }
5783 
5784 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5785   m_image_tokens.push_back(image_ptr);
5786   return m_image_tokens.size() - 1;
5787 }
5788 
5789 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5790   if (token < m_image_tokens.size())
5791     return m_image_tokens[token];
5792   return LLDB_INVALID_IMAGE_TOKEN;
5793 }
5794 
5795 void Process::ResetImageToken(size_t token) {
5796   if (token < m_image_tokens.size())
5797     m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
5798 }
5799 
5800 Address
5801 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5802                                                AddressRange range_bounds) {
5803   Target &target = GetTarget();
5804   DisassemblerSP disassembler_sp;
5805   InstructionList *insn_list = nullptr;
5806 
5807   Address retval = default_stop_addr;
5808 
5809   if (!target.GetUseFastStepping())
5810     return retval;
5811   if (!default_stop_addr.IsValid())
5812     return retval;
5813 
5814   ExecutionContext exe_ctx(this);
5815   const char *plugin_name = nullptr;
5816   const char *flavor = nullptr;
5817   const bool prefer_file_cache = true;
5818   disassembler_sp = Disassembler::DisassembleRange(
5819       target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5820       prefer_file_cache);
5821   if (disassembler_sp)
5822     insn_list = &disassembler_sp->GetInstructionList();
5823 
5824   if (insn_list == nullptr) {
5825     return retval;
5826   }
5827 
5828   size_t insn_offset =
5829       insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5830   if (insn_offset == UINT32_MAX) {
5831     return retval;
5832   }
5833 
5834   uint32_t branch_index =
5835       insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
5836   if (branch_index == UINT32_MAX) {
5837     return retval;
5838   }
5839 
5840   if (branch_index > insn_offset) {
5841     Address next_branch_insn_address =
5842         insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5843     if (next_branch_insn_address.IsValid() &&
5844         range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5845       retval = next_branch_insn_address;
5846     }
5847   }
5848 
5849   return retval;
5850 }
5851 
5852 Status
5853 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
5854 
5855   Status error;
5856 
5857   lldb::addr_t range_end = 0;
5858 
5859   region_list.clear();
5860   do {
5861     lldb_private::MemoryRegionInfo region_info;
5862     error = GetMemoryRegionInfo(range_end, region_info);
5863     // GetMemoryRegionInfo should only return an error if it is unimplemented.
5864     if (error.Fail()) {
5865       region_list.clear();
5866       break;
5867     }
5868 
5869     range_end = region_info.GetRange().GetRangeEnd();
5870     if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5871       region_list.push_back(std::move(region_info));
5872     }
5873   } while (range_end != LLDB_INVALID_ADDRESS);
5874 
5875   return error;
5876 }
5877 
5878 Status
5879 Process::ConfigureStructuredData(ConstString type_name,
5880                                  const StructuredData::ObjectSP &config_sp) {
5881   // If you get this, the Process-derived class needs to implement a method to
5882   // enable an already-reported asynchronous structured data feature. See
5883   // ProcessGDBRemote for an example implementation over gdb-remote.
5884   return Status("unimplemented");
5885 }
5886 
5887 void Process::MapSupportedStructuredDataPlugins(
5888     const StructuredData::Array &supported_type_names) {
5889   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5890 
5891   // Bail out early if there are no type names to map.
5892   if (supported_type_names.GetSize() == 0) {
5893     if (log)
5894       log->Printf("Process::%s(): no structured data types supported",
5895                   __FUNCTION__);
5896     return;
5897   }
5898 
5899   // Convert StructuredData type names to ConstString instances.
5900   std::set<ConstString> const_type_names;
5901 
5902   if (log)
5903     log->Printf("Process::%s(): the process supports the following async "
5904                 "structured data types:",
5905                 __FUNCTION__);
5906 
5907   supported_type_names.ForEach(
5908       [&const_type_names, &log](StructuredData::Object *object) {
5909         if (!object) {
5910           // Invalid - shouldn't be null objects in the array.
5911           return false;
5912         }
5913 
5914         auto type_name = object->GetAsString();
5915         if (!type_name) {
5916           // Invalid format - all type names should be strings.
5917           return false;
5918         }
5919 
5920         const_type_names.insert(ConstString(type_name->GetValue()));
5921         LLDB_LOG(log, "- {0}", type_name->GetValue());
5922         return true;
5923       });
5924 
5925   // For each StructuredDataPlugin, if the plugin handles any of the types in
5926   // the supported_type_names, map that type name to that plugin. Stop when
5927   // we've consumed all the type names.
5928   // FIXME: should we return an error if there are type names nobody
5929   // supports?
5930   for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5931     auto create_instance =
5932            PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5933                plugin_index);
5934     if (!create_instance)
5935       break;
5936 
5937     // Create the plugin.
5938     StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5939     if (!plugin_sp) {
5940       // This plugin doesn't think it can work with the process. Move on to the
5941       // next.
5942       continue;
5943     }
5944 
5945     // For any of the remaining type names, map any that this plugin supports.
5946     std::vector<ConstString> names_to_remove;
5947     for (auto &type_name : const_type_names) {
5948       if (plugin_sp->SupportsStructuredDataType(type_name)) {
5949         m_structured_data_plugin_map.insert(
5950             std::make_pair(type_name, plugin_sp));
5951         names_to_remove.push_back(type_name);
5952         if (log)
5953           log->Printf("Process::%s(): using plugin %s for type name "
5954                       "%s",
5955                       __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5956                       type_name.GetCString());
5957       }
5958     }
5959 
5960     // Remove the type names that were consumed by this plugin.
5961     for (auto &type_name : names_to_remove)
5962       const_type_names.erase(type_name);
5963   }
5964 }
5965 
5966 bool Process::RouteAsyncStructuredData(
5967     const StructuredData::ObjectSP object_sp) {
5968   // Nothing to do if there's no data.
5969   if (!object_sp)
5970     return false;
5971 
5972   // The contract is this must be a dictionary, so we can look up the routing
5973   // key via the top-level 'type' string value within the dictionary.
5974   StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5975   if (!dictionary)
5976     return false;
5977 
5978   // Grab the async structured type name (i.e. the feature/plugin name).
5979   ConstString type_name;
5980   if (!dictionary->GetValueForKeyAsString("type", type_name))
5981     return false;
5982 
5983   // Check if there's a plugin registered for this type name.
5984   auto find_it = m_structured_data_plugin_map.find(type_name);
5985   if (find_it == m_structured_data_plugin_map.end()) {
5986     // We don't have a mapping for this structured data type.
5987     return false;
5988   }
5989 
5990   // Route the structured data to the plugin.
5991   find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5992   return true;
5993 }
5994 
5995 Status Process::UpdateAutomaticSignalFiltering() {
5996   // Default implementation does nothign.
5997   // No automatic signal filtering to speak of.
5998   return Status();
5999 }
6000 
6001 UtilityFunction *Process::GetLoadImageUtilityFunction(
6002     Platform *platform,
6003     llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
6004   if (platform != GetTarget().GetPlatform().get())
6005     return nullptr;
6006   std::call_once(m_dlopen_utility_func_flag_once,
6007                  [&] { m_dlopen_utility_func_up = factory(); });
6008   return m_dlopen_utility_func_up.get();
6009 }
6010