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