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