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   if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2213     return WriteMemoryPrivate(addr, buf, size, error);
2214 
2215   // No breakpoint sites overlap
2216   if (bp_sites_in_range.IsEmpty())
2217     return WriteMemoryPrivate(addr, buf, size, error);
2218 
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     if (error.Fail())
2225       return;
2226 
2227     addr_t intersect_addr;
2228     size_t intersect_size;
2229     size_t opcode_offset;
2230     const bool intersects = bp->IntersectsRange(
2231         addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2232     UNUSED_IF_ASSERT_DISABLED(intersects);
2233     assert(intersects);
2234     assert(addr <= intersect_addr && intersect_addr < addr + size);
2235     assert(addr < intersect_addr + intersect_size &&
2236            intersect_addr + intersect_size <= addr + size);
2237     assert(opcode_offset + intersect_size <= bp->GetByteSize());
2238 
2239     // Check for bytes before this breakpoint
2240     const addr_t curr_addr = addr + bytes_written;
2241     if (intersect_addr > curr_addr) {
2242       // There are some bytes before this breakpoint that we need to just
2243       // write to memory
2244       size_t curr_size = intersect_addr - curr_addr;
2245       size_t curr_bytes_written =
2246           WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2247       bytes_written += curr_bytes_written;
2248       if (curr_bytes_written != curr_size) {
2249         // We weren't able to write all of the requested bytes, we are
2250         // done looping and will return the number of bytes that we have
2251         // written so far.
2252         if (error.Success())
2253           error.SetErrorToGenericError();
2254       }
2255     }
2256     // Now write any bytes that would cover up any software breakpoints
2257     // directly into the breakpoint opcode buffer
2258     ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2259              intersect_size);
2260     bytes_written += intersect_size;
2261   });
2262 
2263   // Write any remaining bytes after the last breakpoint if we have any left
2264   if (bytes_written < size)
2265     bytes_written +=
2266         WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2267                            size - bytes_written, error);
2268 
2269   return bytes_written;
2270 }
2271 
2272 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2273                                     size_t byte_size, Status &error) {
2274   if (byte_size == UINT32_MAX)
2275     byte_size = scalar.GetByteSize();
2276   if (byte_size > 0) {
2277     uint8_t buf[32];
2278     const size_t mem_size =
2279         scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2280     if (mem_size > 0)
2281       return WriteMemory(addr, buf, mem_size, error);
2282     else
2283       error.SetErrorString("failed to get scalar as memory data");
2284   } else {
2285     error.SetErrorString("invalid scalar value");
2286   }
2287   return 0;
2288 }
2289 
2290 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2291                                             bool is_signed, Scalar &scalar,
2292                                             Status &error) {
2293   uint64_t uval = 0;
2294   if (byte_size == 0) {
2295     error.SetErrorString("byte size is zero");
2296   } else if (byte_size & (byte_size - 1)) {
2297     error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2298                                    byte_size);
2299   } else if (byte_size <= sizeof(uval)) {
2300     const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2301     if (bytes_read == byte_size) {
2302       DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2303                          GetAddressByteSize());
2304       lldb::offset_t offset = 0;
2305       if (byte_size <= 4)
2306         scalar = data.GetMaxU32(&offset, byte_size);
2307       else
2308         scalar = data.GetMaxU64(&offset, byte_size);
2309       if (is_signed)
2310         scalar.SignExtend(byte_size * 8);
2311       return bytes_read;
2312     }
2313   } else {
2314     error.SetErrorStringWithFormat(
2315         "byte size of %u is too large for integer scalar type", byte_size);
2316   }
2317   return 0;
2318 }
2319 
2320 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2321   Status error;
2322   for (const auto &Entry : entries) {
2323     WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2324                 error);
2325     if (!error.Success())
2326       break;
2327   }
2328   return error;
2329 }
2330 
2331 #define USE_ALLOCATE_MEMORY_CACHE 1
2332 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2333                                Status &error) {
2334   if (GetPrivateState() != eStateStopped) {
2335     error.SetErrorToGenericError();
2336     return LLDB_INVALID_ADDRESS;
2337   }
2338 
2339 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2340   return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2341 #else
2342   addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2343   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2344   if (log)
2345     log->Printf("Process::AllocateMemory(size=%" PRIu64
2346                 ", permissions=%s) => 0x%16.16" PRIx64
2347                 " (m_stop_id = %u m_memory_id = %u)",
2348                 (uint64_t)size, GetPermissionsAsCString(permissions),
2349                 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2350                 m_mod_id.GetMemoryID());
2351   return allocated_addr;
2352 #endif
2353 }
2354 
2355 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2356                                 Status &error) {
2357   addr_t return_addr = AllocateMemory(size, permissions, error);
2358   if (error.Success()) {
2359     std::string buffer(size, 0);
2360     WriteMemory(return_addr, buffer.c_str(), size, error);
2361   }
2362   return return_addr;
2363 }
2364 
2365 bool Process::CanJIT() {
2366   if (m_can_jit == eCanJITDontKnow) {
2367     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2368     Status err;
2369 
2370     uint64_t allocated_memory = AllocateMemory(
2371         8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2372         err);
2373 
2374     if (err.Success()) {
2375       m_can_jit = eCanJITYes;
2376       if (log)
2377         log->Printf("Process::%s pid %" PRIu64
2378                     " allocation test passed, CanJIT () is true",
2379                     __FUNCTION__, GetID());
2380     } else {
2381       m_can_jit = eCanJITNo;
2382       if (log)
2383         log->Printf("Process::%s pid %" PRIu64
2384                     " allocation test failed, CanJIT () is false: %s",
2385                     __FUNCTION__, GetID(), err.AsCString());
2386     }
2387 
2388     DeallocateMemory(allocated_memory);
2389   }
2390 
2391   return m_can_jit == eCanJITYes;
2392 }
2393 
2394 void Process::SetCanJIT(bool can_jit) {
2395   m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2396 }
2397 
2398 void Process::SetCanRunCode(bool can_run_code) {
2399   SetCanJIT(can_run_code);
2400   m_can_interpret_function_calls = can_run_code;
2401 }
2402 
2403 Status Process::DeallocateMemory(addr_t ptr) {
2404   Status error;
2405 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2406   if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2407     error.SetErrorStringWithFormat(
2408         "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2409   }
2410 #else
2411   error = DoDeallocateMemory(ptr);
2412 
2413   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2414   if (log)
2415     log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2416                 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2417                 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2418                 m_mod_id.GetMemoryID());
2419 #endif
2420   return error;
2421 }
2422 
2423 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2424                                        lldb::addr_t header_addr,
2425                                        size_t size_to_read) {
2426   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2427   if (log) {
2428     log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2429                 file_spec.GetPath().c_str());
2430   }
2431   ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2432   if (module_sp) {
2433     Status error;
2434     ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2435         shared_from_this(), header_addr, error, size_to_read);
2436     if (objfile)
2437       return module_sp;
2438   }
2439   return ModuleSP();
2440 }
2441 
2442 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2443                                         uint32_t &permissions) {
2444   MemoryRegionInfo range_info;
2445   permissions = 0;
2446   Status error(GetMemoryRegionInfo(load_addr, range_info));
2447   if (!error.Success())
2448     return false;
2449   if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2450       range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2451       range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2452     return false;
2453   }
2454 
2455   if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2456     permissions |= lldb::ePermissionsReadable;
2457 
2458   if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2459     permissions |= lldb::ePermissionsWritable;
2460 
2461   if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2462     permissions |= lldb::ePermissionsExecutable;
2463 
2464   return true;
2465 }
2466 
2467 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2468   Status error;
2469   error.SetErrorString("watchpoints are not supported");
2470   return error;
2471 }
2472 
2473 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2474   Status error;
2475   error.SetErrorString("watchpoints are not supported");
2476   return error;
2477 }
2478 
2479 StateType
2480 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2481                                    const Timeout<std::micro> &timeout) {
2482   StateType state;
2483 
2484   while (true) {
2485     event_sp.reset();
2486     state = GetStateChangedEventsPrivate(event_sp, timeout);
2487 
2488     if (StateIsStoppedState(state, false))
2489       break;
2490 
2491     // If state is invalid, then we timed out
2492     if (state == eStateInvalid)
2493       break;
2494 
2495     if (event_sp)
2496       HandlePrivateEvent(event_sp);
2497   }
2498   return state;
2499 }
2500 
2501 void Process::LoadOperatingSystemPlugin(bool flush) {
2502   if (flush)
2503     m_thread_list.Clear();
2504   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2505   if (flush)
2506     Flush();
2507 }
2508 
2509 Status Process::Launch(ProcessLaunchInfo &launch_info) {
2510   Status error;
2511   m_abi_sp.reset();
2512   m_dyld_up.reset();
2513   m_jit_loaders_up.reset();
2514   m_system_runtime_up.reset();
2515   m_os_up.reset();
2516   m_process_input_reader.reset();
2517 
2518   Module *exe_module = GetTarget().GetExecutableModulePointer();
2519   if (!exe_module) {
2520     error.SetErrorString("executable module does not exist");
2521     return error;
2522   }
2523 
2524   char local_exec_file_path[PATH_MAX];
2525   char platform_exec_file_path[PATH_MAX];
2526   exe_module->GetFileSpec().GetPath(local_exec_file_path,
2527                                     sizeof(local_exec_file_path));
2528   exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2529                                             sizeof(platform_exec_file_path));
2530   if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2531     // Install anything that might need to be installed prior to launching.
2532     // For host systems, this will do nothing, but if we are connected to a
2533     // remote platform it will install any needed binaries
2534     error = GetTarget().Install(&launch_info);
2535     if (error.Fail())
2536       return error;
2537 
2538     if (PrivateStateThreadIsValid())
2539       PausePrivateStateThread();
2540 
2541     error = WillLaunch(exe_module);
2542     if (error.Success()) {
2543       const bool restarted = false;
2544       SetPublicState(eStateLaunching, restarted);
2545       m_should_detach = false;
2546 
2547       if (m_public_run_lock.TrySetRunning()) {
2548         // Now launch using these arguments.
2549         error = DoLaunch(exe_module, launch_info);
2550       } else {
2551         // This shouldn't happen
2552         error.SetErrorString("failed to acquire process run lock");
2553       }
2554 
2555       if (error.Fail()) {
2556         if (GetID() != LLDB_INVALID_PROCESS_ID) {
2557           SetID(LLDB_INVALID_PROCESS_ID);
2558           const char *error_string = error.AsCString();
2559           if (error_string == nullptr)
2560             error_string = "launch failed";
2561           SetExitStatus(-1, error_string);
2562         }
2563       } else {
2564         EventSP event_sp;
2565 
2566         // Now wait for the process to launch and return control to us, and then
2567         // call DidLaunch:
2568         StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2569 
2570         if (state == eStateInvalid || !event_sp) {
2571           // We were able to launch the process, but we failed to catch the
2572           // initial stop.
2573           error.SetErrorString("failed to catch stop after launch");
2574           SetExitStatus(0, "failed to catch stop after launch");
2575           Destroy(false);
2576         } else if (state == eStateStopped || state == eStateCrashed) {
2577           DidLaunch();
2578 
2579           DynamicLoader *dyld = GetDynamicLoader();
2580           if (dyld)
2581             dyld->DidLaunch();
2582 
2583           GetJITLoaders().DidLaunch();
2584 
2585           SystemRuntime *system_runtime = GetSystemRuntime();
2586           if (system_runtime)
2587             system_runtime->DidLaunch();
2588 
2589           if (!m_os_up)
2590             LoadOperatingSystemPlugin(false);
2591 
2592           // We successfully launched the process and stopped, now it the
2593           // right time to set up signal filters before resuming.
2594           UpdateAutomaticSignalFiltering();
2595 
2596           // Note, the stop event was consumed above, but not handled. This
2597           // was done to give DidLaunch a chance to run. The target is either
2598           // stopped or crashed. Directly set the state.  This is done to
2599           // prevent a stop message with a bunch of spurious output on thread
2600           // status, as well as not pop a ProcessIOHandler.
2601           SetPublicState(state, false);
2602 
2603           if (PrivateStateThreadIsValid())
2604             ResumePrivateStateThread();
2605           else
2606             StartPrivateStateThread();
2607 
2608           // Target was stopped at entry as was intended. Need to notify the
2609           // listeners about it.
2610           if (state == eStateStopped &&
2611               launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2612             HandlePrivateEvent(event_sp);
2613         } else if (state == eStateExited) {
2614           // We exited while trying to launch somehow.  Don't call DidLaunch
2615           // as that's not likely to work, and return an invalid pid.
2616           HandlePrivateEvent(event_sp);
2617         }
2618       }
2619     }
2620   } else {
2621     error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2622                                    local_exec_file_path);
2623   }
2624 
2625   return error;
2626 }
2627 
2628 Status Process::LoadCore() {
2629   Status error = DoLoadCore();
2630   if (error.Success()) {
2631     ListenerSP listener_sp(
2632         Listener::MakeListener("lldb.process.load_core_listener"));
2633     HijackProcessEvents(listener_sp);
2634 
2635     if (PrivateStateThreadIsValid())
2636       ResumePrivateStateThread();
2637     else
2638       StartPrivateStateThread();
2639 
2640     DynamicLoader *dyld = GetDynamicLoader();
2641     if (dyld)
2642       dyld->DidAttach();
2643 
2644     GetJITLoaders().DidAttach();
2645 
2646     SystemRuntime *system_runtime = GetSystemRuntime();
2647     if (system_runtime)
2648       system_runtime->DidAttach();
2649 
2650     if (!m_os_up)
2651       LoadOperatingSystemPlugin(false);
2652 
2653     // We successfully loaded a core file, now pretend we stopped so we can
2654     // show all of the threads in the core file and explore the crashed state.
2655     SetPrivateState(eStateStopped);
2656 
2657     // Wait for a stopped event since we just posted one above...
2658     lldb::EventSP event_sp;
2659     StateType state =
2660         WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
2661 
2662     if (!StateIsStoppedState(state, false)) {
2663       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2664       if (log)
2665         log->Printf("Process::Halt() failed to stop, state is: %s",
2666                     StateAsCString(state));
2667       error.SetErrorString(
2668           "Did not get stopped event after loading the core file.");
2669     }
2670     RestoreProcessEvents();
2671   }
2672   return error;
2673 }
2674 
2675 DynamicLoader *Process::GetDynamicLoader() {
2676   if (!m_dyld_up)
2677     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2678   return m_dyld_up.get();
2679 }
2680 
2681 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2682 
2683 JITLoaderList &Process::GetJITLoaders() {
2684   if (!m_jit_loaders_up) {
2685     m_jit_loaders_up.reset(new JITLoaderList());
2686     JITLoader::LoadPlugins(this, *m_jit_loaders_up);
2687   }
2688   return *m_jit_loaders_up;
2689 }
2690 
2691 SystemRuntime *Process::GetSystemRuntime() {
2692   if (!m_system_runtime_up)
2693     m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2694   return m_system_runtime_up.get();
2695 }
2696 
2697 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2698                                                           uint32_t exec_count)
2699     : NextEventAction(process), m_exec_count(exec_count) {
2700   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2701   if (log)
2702     log->Printf(
2703         "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2704         __FUNCTION__, static_cast<void *>(process), exec_count);
2705 }
2706 
2707 Process::NextEventAction::EventActionResult
2708 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2709   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2710 
2711   StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2712   if (log)
2713     log->Printf(
2714         "Process::AttachCompletionHandler::%s called with state %s (%d)",
2715         __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2716 
2717   switch (state) {
2718   case eStateAttaching:
2719     return eEventActionSuccess;
2720 
2721   case eStateRunning:
2722   case eStateConnected:
2723     return eEventActionRetry;
2724 
2725   case eStateStopped:
2726   case eStateCrashed:
2727     // During attach, prior to sending the eStateStopped event,
2728     // lldb_private::Process subclasses must set the new process ID.
2729     assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2730     // We don't want these events to be reported, so go set the
2731     // ShouldReportStop here:
2732     m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2733 
2734     if (m_exec_count > 0) {
2735       --m_exec_count;
2736 
2737       if (log)
2738         log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2739                     "remaining exec count to %" PRIu32 ", requesting resume",
2740                     __FUNCTION__, StateAsCString(state), m_exec_count);
2741 
2742       RequestResume();
2743       return eEventActionRetry;
2744     } else {
2745       if (log)
2746         log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2747                     "execs expected to start, continuing with attach",
2748                     __FUNCTION__, StateAsCString(state));
2749 
2750       m_process->CompleteAttach();
2751       return eEventActionSuccess;
2752     }
2753     break;
2754 
2755   default:
2756   case eStateExited:
2757   case eStateInvalid:
2758     break;
2759   }
2760 
2761   m_exit_string.assign("No valid Process");
2762   return eEventActionExit;
2763 }
2764 
2765 Process::NextEventAction::EventActionResult
2766 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2767   return eEventActionSuccess;
2768 }
2769 
2770 const char *Process::AttachCompletionHandler::GetExitString() {
2771   return m_exit_string.c_str();
2772 }
2773 
2774 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2775   if (m_listener_sp)
2776     return m_listener_sp;
2777   else
2778     return debugger.GetListener();
2779 }
2780 
2781 Status Process::Attach(ProcessAttachInfo &attach_info) {
2782   m_abi_sp.reset();
2783   m_process_input_reader.reset();
2784   m_dyld_up.reset();
2785   m_jit_loaders_up.reset();
2786   m_system_runtime_up.reset();
2787   m_os_up.reset();
2788 
2789   lldb::pid_t attach_pid = attach_info.GetProcessID();
2790   Status error;
2791   if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2792     char process_name[PATH_MAX];
2793 
2794     if (attach_info.GetExecutableFile().GetPath(process_name,
2795                                                 sizeof(process_name))) {
2796       const bool wait_for_launch = attach_info.GetWaitForLaunch();
2797 
2798       if (wait_for_launch) {
2799         error = WillAttachToProcessWithName(process_name, wait_for_launch);
2800         if (error.Success()) {
2801           if (m_public_run_lock.TrySetRunning()) {
2802             m_should_detach = true;
2803             const bool restarted = false;
2804             SetPublicState(eStateAttaching, restarted);
2805             // Now attach using these arguments.
2806             error = DoAttachToProcessWithName(process_name, attach_info);
2807           } else {
2808             // This shouldn't happen
2809             error.SetErrorString("failed to acquire process run lock");
2810           }
2811 
2812           if (error.Fail()) {
2813             if (GetID() != LLDB_INVALID_PROCESS_ID) {
2814               SetID(LLDB_INVALID_PROCESS_ID);
2815               if (error.AsCString() == nullptr)
2816                 error.SetErrorString("attach failed");
2817 
2818               SetExitStatus(-1, error.AsCString());
2819             }
2820           } else {
2821             SetNextEventAction(new Process::AttachCompletionHandler(
2822                 this, attach_info.GetResumeCount()));
2823             StartPrivateStateThread();
2824           }
2825           return error;
2826         }
2827       } else {
2828         ProcessInstanceInfoList process_infos;
2829         PlatformSP platform_sp(GetTarget().GetPlatform());
2830 
2831         if (platform_sp) {
2832           ProcessInstanceInfoMatch match_info;
2833           match_info.GetProcessInfo() = attach_info;
2834           match_info.SetNameMatchType(NameMatch::Equals);
2835           platform_sp->FindProcesses(match_info, process_infos);
2836           const uint32_t num_matches = process_infos.GetSize();
2837           if (num_matches == 1) {
2838             attach_pid = process_infos.GetProcessIDAtIndex(0);
2839             // Fall through and attach using the above process ID
2840           } else {
2841             match_info.GetProcessInfo().GetExecutableFile().GetPath(
2842                 process_name, sizeof(process_name));
2843             if (num_matches > 1) {
2844               StreamString s;
2845               ProcessInstanceInfo::DumpTableHeader(s, true, false);
2846               for (size_t i = 0; i < num_matches; i++) {
2847                 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
2848                     s, platform_sp->GetUserIDResolver(), true, false);
2849               }
2850               error.SetErrorStringWithFormat(
2851                   "more than one process named %s:\n%s", process_name,
2852                   s.GetData());
2853             } else
2854               error.SetErrorStringWithFormat(
2855                   "could not find a process named %s", process_name);
2856           }
2857         } else {
2858           error.SetErrorString(
2859               "invalid platform, can't find processes by name");
2860           return error;
2861         }
2862       }
2863     } else {
2864       error.SetErrorString("invalid process name");
2865     }
2866   }
2867 
2868   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2869     error = WillAttachToProcessWithID(attach_pid);
2870     if (error.Success()) {
2871 
2872       if (m_public_run_lock.TrySetRunning()) {
2873         // Now attach using these arguments.
2874         m_should_detach = true;
2875         const bool restarted = false;
2876         SetPublicState(eStateAttaching, restarted);
2877         error = DoAttachToProcessWithID(attach_pid, attach_info);
2878       } else {
2879         // This shouldn't happen
2880         error.SetErrorString("failed to acquire process run lock");
2881       }
2882 
2883       if (error.Success()) {
2884         SetNextEventAction(new Process::AttachCompletionHandler(
2885             this, attach_info.GetResumeCount()));
2886         StartPrivateStateThread();
2887       } else {
2888         if (GetID() != LLDB_INVALID_PROCESS_ID)
2889           SetID(LLDB_INVALID_PROCESS_ID);
2890 
2891         const char *error_string = error.AsCString();
2892         if (error_string == nullptr)
2893           error_string = "attach failed";
2894 
2895         SetExitStatus(-1, error_string);
2896       }
2897     }
2898   }
2899   return error;
2900 }
2901 
2902 void Process::CompleteAttach() {
2903   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2904                                                   LIBLLDB_LOG_TARGET));
2905   if (log)
2906     log->Printf("Process::%s()", __FUNCTION__);
2907 
2908   // Let the process subclass figure out at much as it can about the process
2909   // before we go looking for a dynamic loader plug-in.
2910   ArchSpec process_arch;
2911   DidAttach(process_arch);
2912 
2913   if (process_arch.IsValid()) {
2914     GetTarget().SetArchitecture(process_arch);
2915     if (log) {
2916       const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2917       log->Printf("Process::%s replacing process architecture with DidAttach() "
2918                   "architecture: %s",
2919                   __FUNCTION__, triple_str ? triple_str : "<null>");
2920     }
2921   }
2922 
2923   // We just attached.  If we have a platform, ask it for the process
2924   // architecture, and if it isn't the same as the one we've already set,
2925   // switch architectures.
2926   PlatformSP platform_sp(GetTarget().GetPlatform());
2927   assert(platform_sp);
2928   if (platform_sp) {
2929     const ArchSpec &target_arch = GetTarget().GetArchitecture();
2930     if (target_arch.IsValid() &&
2931         !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2932       ArchSpec platform_arch;
2933       platform_sp =
2934           platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2935       if (platform_sp) {
2936         GetTarget().SetPlatform(platform_sp);
2937         GetTarget().SetArchitecture(platform_arch);
2938         if (log)
2939           log->Printf("Process::%s switching platform to %s and architecture "
2940                       "to %s based on info from attach",
2941                       __FUNCTION__, platform_sp->GetName().AsCString(""),
2942                       platform_arch.GetTriple().getTriple().c_str());
2943       }
2944     } else if (!process_arch.IsValid()) {
2945       ProcessInstanceInfo process_info;
2946       GetProcessInfo(process_info);
2947       const ArchSpec &process_arch = process_info.GetArchitecture();
2948       if (process_arch.IsValid() &&
2949           !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2950         GetTarget().SetArchitecture(process_arch);
2951         if (log)
2952           log->Printf("Process::%s switching architecture to %s based on info "
2953                       "the platform retrieved for pid %" PRIu64,
2954                       __FUNCTION__,
2955                       process_arch.GetTriple().getTriple().c_str(), GetID());
2956       }
2957     }
2958   }
2959 
2960   // We have completed the attach, now it is time to find the dynamic loader
2961   // plug-in
2962   DynamicLoader *dyld = GetDynamicLoader();
2963   if (dyld) {
2964     dyld->DidAttach();
2965     if (log) {
2966       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2967       log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
2968                   "executable is %s (using %s plugin)",
2969                   __FUNCTION__,
2970                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2971                                 : "<none>",
2972                   dyld->GetPluginName().AsCString("<unnamed>"));
2973     }
2974   }
2975 
2976   GetJITLoaders().DidAttach();
2977 
2978   SystemRuntime *system_runtime = GetSystemRuntime();
2979   if (system_runtime) {
2980     system_runtime->DidAttach();
2981     if (log) {
2982       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2983       log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
2984                   "executable is %s (using %s plugin)",
2985                   __FUNCTION__,
2986                   exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2987                                 : "<none>",
2988                   system_runtime->GetPluginName().AsCString("<unnamed>"));
2989     }
2990   }
2991 
2992   if (!m_os_up)
2993     LoadOperatingSystemPlugin(false);
2994   // Figure out which one is the executable, and set that in our target:
2995   const ModuleList &target_modules = GetTarget().GetImages();
2996   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2997   size_t num_modules = target_modules.GetSize();
2998   ModuleSP new_executable_module_sp;
2999 
3000   for (size_t i = 0; i < num_modules; i++) {
3001     ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3002     if (module_sp && module_sp->IsExecutable()) {
3003       if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3004         new_executable_module_sp = module_sp;
3005       break;
3006     }
3007   }
3008   if (new_executable_module_sp) {
3009     GetTarget().SetExecutableModule(new_executable_module_sp,
3010                                     eLoadDependentsNo);
3011     if (log) {
3012       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3013       log->Printf(
3014           "Process::%s after looping through modules, target executable is %s",
3015           __FUNCTION__,
3016           exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3017                         : "<none>");
3018     }
3019   }
3020 }
3021 
3022 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3023   m_abi_sp.reset();
3024   m_process_input_reader.reset();
3025 
3026   // Find the process and its architecture.  Make sure it matches the
3027   // architecture of the current Target, and if not adjust it.
3028 
3029   Status error(DoConnectRemote(strm, remote_url));
3030   if (error.Success()) {
3031     if (GetID() != LLDB_INVALID_PROCESS_ID) {
3032       EventSP event_sp;
3033       StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3034 
3035       if (state == eStateStopped || state == eStateCrashed) {
3036         // If we attached and actually have a process on the other end, then
3037         // this ended up being the equivalent of an attach.
3038         CompleteAttach();
3039 
3040         // This delays passing the stopped event to listeners till
3041         // CompleteAttach gets a chance to complete...
3042         HandlePrivateEvent(event_sp);
3043       }
3044     }
3045 
3046     if (PrivateStateThreadIsValid())
3047       ResumePrivateStateThread();
3048     else
3049       StartPrivateStateThread();
3050   }
3051   return error;
3052 }
3053 
3054 Status Process::PrivateResume() {
3055   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3056                                                   LIBLLDB_LOG_STEP));
3057   if (log)
3058     log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3059                 "private state: %s",
3060                 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3061                 StateAsCString(m_private_state.GetValue()));
3062 
3063   // If signals handing status changed we might want to update our signal
3064   // filters before resuming.
3065   UpdateAutomaticSignalFiltering();
3066 
3067   Status error(WillResume());
3068   // Tell the process it is about to resume before the thread list
3069   if (error.Success()) {
3070     // Now let the thread list know we are about to resume so it can let all of
3071     // our threads know that they are about to be resumed. Threads will each be
3072     // called with Thread::WillResume(StateType) where StateType contains the
3073     // state that they are supposed to have when the process is resumed
3074     // (suspended/running/stepping). Threads should also check their resume
3075     // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3076     // start back up with a signal.
3077     if (m_thread_list.WillResume()) {
3078       // Last thing, do the PreResumeActions.
3079       if (!RunPreResumeActions()) {
3080         error.SetErrorStringWithFormat(
3081             "Process::PrivateResume PreResumeActions failed, not resuming.");
3082       } else {
3083         m_mod_id.BumpResumeID();
3084         error = DoResume();
3085         if (error.Success()) {
3086           DidResume();
3087           m_thread_list.DidResume();
3088           if (log)
3089             log->Printf("Process thinks the process has resumed.");
3090         } else {
3091           if (log)
3092             log->Printf(
3093                 "Process::PrivateResume() DoResume failed.");
3094           return error;
3095         }
3096       }
3097     } else {
3098       // Somebody wanted to run without running (e.g. we were faking a step
3099       // from one frame of a set of inlined frames that share the same PC to
3100       // another.)  So generate a continue & a stopped event, and let the world
3101       // handle them.
3102       if (log)
3103         log->Printf(
3104             "Process::PrivateResume() asked to simulate a start & stop.");
3105 
3106       SetPrivateState(eStateRunning);
3107       SetPrivateState(eStateStopped);
3108     }
3109   } else if (log)
3110     log->Printf("Process::PrivateResume() got an error \"%s\".",
3111                 error.AsCString("<unknown error>"));
3112   return error;
3113 }
3114 
3115 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3116   if (!StateIsRunningState(m_public_state.GetValue()))
3117     return Status("Process is not running.");
3118 
3119   // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3120   // case it was already set and some thread plan logic calls halt on its own.
3121   m_clear_thread_plans_on_stop |= clear_thread_plans;
3122 
3123   ListenerSP halt_listener_sp(
3124       Listener::MakeListener("lldb.process.halt_listener"));
3125   HijackProcessEvents(halt_listener_sp);
3126 
3127   EventSP event_sp;
3128 
3129   SendAsyncInterrupt();
3130 
3131   if (m_public_state.GetValue() == eStateAttaching) {
3132     // Don't hijack and eat the eStateExited as the code that was doing the
3133     // attach will be waiting for this event...
3134     RestoreProcessEvents();
3135     SetExitStatus(SIGKILL, "Cancelled async attach.");
3136     Destroy(false);
3137     return Status();
3138   }
3139 
3140   // Wait for 10 second for the process to stop.
3141   StateType state = WaitForProcessToStop(
3142       seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
3143   RestoreProcessEvents();
3144 
3145   if (state == eStateInvalid || !event_sp) {
3146     // We timed out and didn't get a stop event...
3147     return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3148   }
3149 
3150   BroadcastEvent(event_sp);
3151 
3152   return Status();
3153 }
3154 
3155 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3156   Status error;
3157 
3158   // Check both the public & private states here.  If we're hung evaluating an
3159   // expression, for instance, then the public state will be stopped, but we
3160   // still need to interrupt.
3161   if (m_public_state.GetValue() == eStateRunning ||
3162       m_private_state.GetValue() == eStateRunning) {
3163     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3164     if (log)
3165       log->Printf("Process::%s() About to stop.", __FUNCTION__);
3166 
3167     ListenerSP listener_sp(
3168         Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3169     HijackProcessEvents(listener_sp);
3170 
3171     SendAsyncInterrupt();
3172 
3173     // Consume the interrupt event.
3174     StateType state =
3175         WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
3176 
3177     RestoreProcessEvents();
3178 
3179     // If the process exited while we were waiting for it to stop, put the
3180     // exited event into the shared pointer passed in and return.  Our caller
3181     // doesn't need to do anything else, since they don't have a process
3182     // anymore...
3183 
3184     if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3185       if (log)
3186         log->Printf("Process::%s() Process exited while waiting to stop.",
3187                     __FUNCTION__);
3188       return error;
3189     } else
3190       exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3191 
3192     if (state != eStateStopped) {
3193       if (log)
3194         log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3195                     StateAsCString(state));
3196       // If we really couldn't stop the process then we should just error out
3197       // here, but if the lower levels just bobbled sending the event and we
3198       // really are stopped, then continue on.
3199       StateType private_state = m_private_state.GetValue();
3200       if (private_state != eStateStopped) {
3201         return Status(
3202             "Attempt to stop the target in order to detach timed out. "
3203             "State = %s",
3204             StateAsCString(GetState()));
3205       }
3206     }
3207   }
3208   return error;
3209 }
3210 
3211 Status Process::Detach(bool keep_stopped) {
3212   EventSP exit_event_sp;
3213   Status error;
3214   m_destroy_in_process = true;
3215 
3216   error = WillDetach();
3217 
3218   if (error.Success()) {
3219     if (DetachRequiresHalt()) {
3220       error = StopForDestroyOrDetach(exit_event_sp);
3221       if (!error.Success()) {
3222         m_destroy_in_process = false;
3223         return error;
3224       } else if (exit_event_sp) {
3225         // We shouldn't need to do anything else here.  There's no process left
3226         // to detach from...
3227         StopPrivateStateThread();
3228         m_destroy_in_process = false;
3229         return error;
3230       }
3231     }
3232 
3233     m_thread_list.DiscardThreadPlans();
3234     DisableAllBreakpointSites();
3235 
3236     error = DoDetach(keep_stopped);
3237     if (error.Success()) {
3238       DidDetach();
3239       StopPrivateStateThread();
3240     } else {
3241       return error;
3242     }
3243   }
3244   m_destroy_in_process = false;
3245 
3246   // If we exited when we were waiting for a process to stop, then forward the
3247   // event here so we don't lose the event
3248   if (exit_event_sp) {
3249     // Directly broadcast our exited event because we shut down our private
3250     // state thread above
3251     BroadcastEvent(exit_event_sp);
3252   }
3253 
3254   // If we have been interrupted (to kill us) in the middle of running, we may
3255   // not end up propagating the last events through the event system, in which
3256   // case we might strand the write lock.  Unlock it here so when we do to tear
3257   // down the process we don't get an error destroying the lock.
3258 
3259   m_public_run_lock.SetStopped();
3260   return error;
3261 }
3262 
3263 Status Process::Destroy(bool force_kill) {
3264 
3265   // Tell ourselves we are in the process of destroying the process, so that we
3266   // don't do any unnecessary work that might hinder the destruction.  Remember
3267   // to set this back to false when we are done.  That way if the attempt
3268   // failed and the process stays around for some reason it won't be in a
3269   // confused state.
3270 
3271   if (force_kill)
3272     m_should_detach = false;
3273 
3274   if (GetShouldDetach()) {
3275     // FIXME: This will have to be a process setting:
3276     bool keep_stopped = false;
3277     Detach(keep_stopped);
3278   }
3279 
3280   m_destroy_in_process = true;
3281 
3282   Status error(WillDestroy());
3283   if (error.Success()) {
3284     EventSP exit_event_sp;
3285     if (DestroyRequiresHalt()) {
3286       error = StopForDestroyOrDetach(exit_event_sp);
3287     }
3288 
3289     if (m_public_state.GetValue() != eStateRunning) {
3290       // Ditch all thread plans, and remove all our breakpoints: in case we
3291       // have to restart the target to kill it, we don't want it hitting a
3292       // breakpoint... Only do this if we've stopped, however, since if we
3293       // didn't manage to halt it above, then we're not going to have much luck
3294       // doing this now.
3295       m_thread_list.DiscardThreadPlans();
3296       DisableAllBreakpointSites();
3297     }
3298 
3299     error = DoDestroy();
3300     if (error.Success()) {
3301       DidDestroy();
3302       StopPrivateStateThread();
3303     }
3304     m_stdio_communication.Disconnect();
3305     m_stdio_communication.StopReadThread();
3306     m_stdin_forward = false;
3307 
3308     if (m_process_input_reader) {
3309       m_process_input_reader->SetIsDone(true);
3310       m_process_input_reader->Cancel();
3311       m_process_input_reader.reset();
3312     }
3313 
3314     // If we exited when we were waiting for a process to stop, then forward
3315     // the event here so we don't lose the event
3316     if (exit_event_sp) {
3317       // Directly broadcast our exited event because we shut down our private
3318       // state thread above
3319       BroadcastEvent(exit_event_sp);
3320     }
3321 
3322     // If we have been interrupted (to kill us) in the middle of running, we
3323     // may not end up propagating the last events through the event system, in
3324     // which case we might strand the write lock.  Unlock it here so when we do
3325     // to tear down the process we don't get an error destroying the lock.
3326     m_public_run_lock.SetStopped();
3327   }
3328 
3329   m_destroy_in_process = false;
3330 
3331   return error;
3332 }
3333 
3334 Status Process::Signal(int signal) {
3335   Status error(WillSignal());
3336   if (error.Success()) {
3337     error = DoSignal(signal);
3338     if (error.Success())
3339       DidSignal();
3340   }
3341   return error;
3342 }
3343 
3344 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3345   assert(signals_sp && "null signals_sp");
3346   m_unix_signals_sp = signals_sp;
3347 }
3348 
3349 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3350   assert(m_unix_signals_sp && "null m_unix_signals_sp");
3351   return m_unix_signals_sp;
3352 }
3353 
3354 lldb::ByteOrder Process::GetByteOrder() const {
3355   return GetTarget().GetArchitecture().GetByteOrder();
3356 }
3357 
3358 uint32_t Process::GetAddressByteSize() const {
3359   return GetTarget().GetArchitecture().GetAddressByteSize();
3360 }
3361 
3362 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3363   const StateType state =
3364       Process::ProcessEventData::GetStateFromEvent(event_ptr);
3365   bool return_value = true;
3366   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3367                                                   LIBLLDB_LOG_PROCESS));
3368 
3369   switch (state) {
3370   case eStateDetached:
3371   case eStateExited:
3372   case eStateUnloaded:
3373     m_stdio_communication.SynchronizeWithReadThread();
3374     m_stdio_communication.Disconnect();
3375     m_stdio_communication.StopReadThread();
3376     m_stdin_forward = false;
3377 
3378     LLVM_FALLTHROUGH;
3379   case eStateConnected:
3380   case eStateAttaching:
3381   case eStateLaunching:
3382     // These events indicate changes in the state of the debugging session,
3383     // always report them.
3384     return_value = true;
3385     break;
3386   case eStateInvalid:
3387     // We stopped for no apparent reason, don't report it.
3388     return_value = false;
3389     break;
3390   case eStateRunning:
3391   case eStateStepping:
3392     // If we've started the target running, we handle the cases where we are
3393     // already running and where there is a transition from stopped to running
3394     // differently. running -> running: Automatically suppress extra running
3395     // events stopped -> running: Report except when there is one or more no
3396     // votes
3397     //     and no yes votes.
3398     SynchronouslyNotifyStateChanged(state);
3399     if (m_force_next_event_delivery)
3400       return_value = true;
3401     else {
3402       switch (m_last_broadcast_state) {
3403       case eStateRunning:
3404       case eStateStepping:
3405         // We always suppress multiple runnings with no PUBLIC stop in between.
3406         return_value = false;
3407         break;
3408       default:
3409         // TODO: make this work correctly. For now always report
3410         // run if we aren't running so we don't miss any running events. If I
3411         // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3412         // and hit the breakpoints on multiple threads, then somehow during the
3413         // stepping over of all breakpoints no run gets reported.
3414 
3415         // This is a transition from stop to run.
3416         switch (m_thread_list.ShouldReportRun(event_ptr)) {
3417         case eVoteYes:
3418         case eVoteNoOpinion:
3419           return_value = true;
3420           break;
3421         case eVoteNo:
3422           return_value = false;
3423           break;
3424         }
3425         break;
3426       }
3427     }
3428     break;
3429   case eStateStopped:
3430   case eStateCrashed:
3431   case eStateSuspended:
3432     // We've stopped.  First see if we're going to restart the target. If we
3433     // are going to stop, then we always broadcast the event. If we aren't
3434     // going to stop, let the thread plans decide if we're going to report this
3435     // event. If no thread has an opinion, we don't report it.
3436 
3437     m_stdio_communication.SynchronizeWithReadThread();
3438     RefreshStateAfterStop();
3439     if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3440       if (log)
3441         log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3442                     "interrupt, state: %s",
3443                     static_cast<void *>(event_ptr), StateAsCString(state));
3444       // Even though we know we are going to stop, we should let the threads
3445       // have a look at the stop, so they can properly set their state.
3446       m_thread_list.ShouldStop(event_ptr);
3447       return_value = true;
3448     } else {
3449       bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3450       bool should_resume = false;
3451 
3452       // It makes no sense to ask "ShouldStop" if we've already been
3453       // restarted... Asking the thread list is also not likely to go well,
3454       // since we are running again. So in that case just report the event.
3455 
3456       if (!was_restarted)
3457         should_resume = !m_thread_list.ShouldStop(event_ptr);
3458 
3459       if (was_restarted || should_resume || m_resume_requested) {
3460         Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3461         if (log)
3462           log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3463                       "%s was_restarted: %i stop_vote: %d.",
3464                       should_resume, StateAsCString(state), was_restarted,
3465                       stop_vote);
3466 
3467         switch (stop_vote) {
3468         case eVoteYes:
3469           return_value = true;
3470           break;
3471         case eVoteNoOpinion:
3472         case eVoteNo:
3473           return_value = false;
3474           break;
3475         }
3476 
3477         if (!was_restarted) {
3478           if (log)
3479             log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3480                         "from state: %s",
3481                         static_cast<void *>(event_ptr), StateAsCString(state));
3482           ProcessEventData::SetRestartedInEvent(event_ptr, true);
3483           PrivateResume();
3484         }
3485       } else {
3486         return_value = true;
3487         SynchronouslyNotifyStateChanged(state);
3488       }
3489     }
3490     break;
3491   }
3492 
3493   // Forcing the next event delivery is a one shot deal.  So reset it here.
3494   m_force_next_event_delivery = false;
3495 
3496   // We do some coalescing of events (for instance two consecutive running
3497   // events get coalesced.) But we only coalesce against events we actually
3498   // broadcast.  So we use m_last_broadcast_state to track that.  NB - you
3499   // can't use "m_public_state.GetValue()" for that purpose, as was originally
3500   // done, because the PublicState reflects the last event pulled off the
3501   // queue, and there may be several events stacked up on the queue unserviced.
3502   // So the PublicState may not reflect the last broadcasted event yet.
3503   // m_last_broadcast_state gets updated here.
3504 
3505   if (return_value)
3506     m_last_broadcast_state = state;
3507 
3508   if (log)
3509     log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3510                 "broadcast state: %s - %s",
3511                 static_cast<void *>(event_ptr), StateAsCString(state),
3512                 StateAsCString(m_last_broadcast_state),
3513                 return_value ? "YES" : "NO");
3514   return return_value;
3515 }
3516 
3517 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3518   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3519 
3520   bool already_running = PrivateStateThreadIsValid();
3521   if (log)
3522     log->Printf("Process::%s()%s ", __FUNCTION__,
3523                 already_running ? " already running"
3524                                 : " starting private state thread");
3525 
3526   if (!is_secondary_thread && already_running)
3527     return true;
3528 
3529   // Create a thread that watches our internal state and controls which events
3530   // make it to clients (into the DCProcess event queue).
3531   char thread_name[1024];
3532   uint32_t max_len = llvm::get_max_thread_name_length();
3533   if (max_len > 0 && max_len <= 30) {
3534     // On platforms with abbreviated thread name lengths, choose thread names
3535     // that fit within the limit.
3536     if (already_running)
3537       snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3538     else
3539       snprintf(thread_name, sizeof(thread_name), "intern-state");
3540   } else {
3541     if (already_running)
3542       snprintf(thread_name, sizeof(thread_name),
3543                "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3544                GetID());
3545     else
3546       snprintf(thread_name, sizeof(thread_name),
3547                "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3548   }
3549 
3550   // Create the private state thread, and start it running.
3551   PrivateStateThreadArgs *args_ptr =
3552       new PrivateStateThreadArgs(this, is_secondary_thread);
3553   m_private_state_thread =
3554       ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3555                                    (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3556   if (m_private_state_thread.IsJoinable()) {
3557     ResumePrivateStateThread();
3558     return true;
3559   } else
3560     return false;
3561 }
3562 
3563 void Process::PausePrivateStateThread() {
3564   ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3565 }
3566 
3567 void Process::ResumePrivateStateThread() {
3568   ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3569 }
3570 
3571 void Process::StopPrivateStateThread() {
3572   if (m_private_state_thread.IsJoinable())
3573     ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3574   else {
3575     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3576     if (log)
3577       log->Printf(
3578           "Went to stop the private state thread, but it was already invalid.");
3579   }
3580 }
3581 
3582 void Process::ControlPrivateStateThread(uint32_t signal) {
3583   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3584 
3585   assert(signal == eBroadcastInternalStateControlStop ||
3586          signal == eBroadcastInternalStateControlPause ||
3587          signal == eBroadcastInternalStateControlResume);
3588 
3589   if (log)
3590     log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3591 
3592   // Signal the private state thread
3593   if (m_private_state_thread.IsJoinable()) {
3594     // Broadcast the event.
3595     // It is important to do this outside of the if below, because it's
3596     // possible that the thread state is invalid but that the thread is waiting
3597     // on a control event instead of simply being on its way out (this should
3598     // not happen, but it apparently can).
3599     if (log)
3600       log->Printf("Sending control event of type: %d.", signal);
3601     std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3602     m_private_state_control_broadcaster.BroadcastEvent(signal,
3603                                                        event_receipt_sp);
3604 
3605     // Wait for the event receipt or for the private state thread to exit
3606     bool receipt_received = false;
3607     if (PrivateStateThreadIsValid()) {
3608       while (!receipt_received) {
3609         // Check for a receipt for 2 seconds and then check if the private
3610         // state thread is still around.
3611         receipt_received =
3612             event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2));
3613         if (!receipt_received) {
3614           // Check if the private state thread is still around. If it isn't
3615           // then we are done waiting
3616           if (!PrivateStateThreadIsValid())
3617             break; // Private state thread exited or is exiting, we are done
3618         }
3619       }
3620     }
3621 
3622     if (signal == eBroadcastInternalStateControlStop) {
3623       thread_result_t result = NULL;
3624       m_private_state_thread.Join(&result);
3625       m_private_state_thread.Reset();
3626     }
3627   } else {
3628     if (log)
3629       log->Printf(
3630           "Private state thread already dead, no need to signal it to stop.");
3631   }
3632 }
3633 
3634 void Process::SendAsyncInterrupt() {
3635   if (PrivateStateThreadIsValid())
3636     m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3637                                                nullptr);
3638   else
3639     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3640 }
3641 
3642 void Process::HandlePrivateEvent(EventSP &event_sp) {
3643   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3644   m_resume_requested = false;
3645 
3646   const StateType new_state =
3647       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3648 
3649   // First check to see if anybody wants a shot at this event:
3650   if (m_next_event_action_up) {
3651     NextEventAction::EventActionResult action_result =
3652         m_next_event_action_up->PerformAction(event_sp);
3653     if (log)
3654       log->Printf("Ran next event action, result was %d.", action_result);
3655 
3656     switch (action_result) {
3657     case NextEventAction::eEventActionSuccess:
3658       SetNextEventAction(nullptr);
3659       break;
3660 
3661     case NextEventAction::eEventActionRetry:
3662       break;
3663 
3664     case NextEventAction::eEventActionExit:
3665       // Handle Exiting Here.  If we already got an exited event, we should
3666       // just propagate it.  Otherwise, swallow this event, and set our state
3667       // to exit so the next event will kill us.
3668       if (new_state != eStateExited) {
3669         // FIXME: should cons up an exited event, and discard this one.
3670         SetExitStatus(0, m_next_event_action_up->GetExitString());
3671         SetNextEventAction(nullptr);
3672         return;
3673       }
3674       SetNextEventAction(nullptr);
3675       break;
3676     }
3677   }
3678 
3679   // See if we should broadcast this state to external clients?
3680   const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3681 
3682   if (should_broadcast) {
3683     const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3684     if (log) {
3685       log->Printf("Process::%s (pid = %" PRIu64
3686                   ") broadcasting new state %s (old state %s) to %s",
3687                   __FUNCTION__, GetID(), StateAsCString(new_state),
3688                   StateAsCString(GetState()),
3689                   is_hijacked ? "hijacked" : "public");
3690     }
3691     Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3692     if (StateIsRunningState(new_state)) {
3693       // Only push the input handler if we aren't fowarding events, as this
3694       // means the curses GUI is in use... Or don't push it if we are launching
3695       // since it will come up stopped.
3696       if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3697           new_state != eStateLaunching && new_state != eStateAttaching) {
3698         PushProcessIOHandler();
3699         m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3700                                   eBroadcastAlways);
3701         if (log)
3702           log->Printf("Process::%s updated m_iohandler_sync to %d",
3703                       __FUNCTION__, m_iohandler_sync.GetValue());
3704       }
3705     } else if (StateIsStoppedState(new_state, false)) {
3706       if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3707         // If the lldb_private::Debugger is handling the events, we don't want
3708         // to pop the process IOHandler here, we want to do it when we receive
3709         // the stopped event so we can carefully control when the process
3710         // IOHandler is popped because when we stop we want to display some
3711         // text stating how and why we stopped, then maybe some
3712         // process/thread/frame info, and then we want the "(lldb) " prompt to
3713         // show up. If we pop the process IOHandler here, then we will cause
3714         // the command interpreter to become the top IOHandler after the
3715         // process pops off and it will update its prompt right away... See the
3716         // Debugger.cpp file where it calls the function as
3717         // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3718         // Otherwise we end up getting overlapping "(lldb) " prompts and
3719         // garbled output.
3720         //
3721         // If we aren't handling the events in the debugger (which is indicated
3722         // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3723         // we are hijacked, then we always pop the process IO handler manually.
3724         // Hijacking happens when the internal process state thread is running
3725         // thread plans, or when commands want to run in synchronous mode and
3726         // they call "process->WaitForProcessToStop()". An example of something
3727         // that will hijack the events is a simple expression:
3728         //
3729         //  (lldb) expr (int)puts("hello")
3730         //
3731         // This will cause the internal process state thread to resume and halt
3732         // the process (and _it_ will hijack the eBroadcastBitStateChanged
3733         // events) and we do need the IO handler to be pushed and popped
3734         // correctly.
3735 
3736         if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3737           PopProcessIOHandler();
3738       }
3739     }
3740 
3741     BroadcastEvent(event_sp);
3742   } else {
3743     if (log) {
3744       log->Printf(
3745           "Process::%s (pid = %" PRIu64
3746           ") suppressing state %s (old state %s): should_broadcast == false",
3747           __FUNCTION__, GetID(), StateAsCString(new_state),
3748           StateAsCString(GetState()));
3749     }
3750   }
3751 }
3752 
3753 Status Process::HaltPrivate() {
3754   EventSP event_sp;
3755   Status error(WillHalt());
3756   if (error.Fail())
3757     return error;
3758 
3759   // Ask the process subclass to actually halt our process
3760   bool caused_stop;
3761   error = DoHalt(caused_stop);
3762 
3763   DidHalt();
3764   return error;
3765 }
3766 
3767 thread_result_t Process::PrivateStateThread(void *arg) {
3768   std::unique_ptr<PrivateStateThreadArgs> args_up(
3769       static_cast<PrivateStateThreadArgs *>(arg));
3770   thread_result_t result =
3771       args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3772   return result;
3773 }
3774 
3775 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3776   bool control_only = true;
3777 
3778   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3779   if (log)
3780     log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3781                 __FUNCTION__, static_cast<void *>(this), GetID());
3782 
3783   bool exit_now = false;
3784   bool interrupt_requested = false;
3785   while (!exit_now) {
3786     EventSP event_sp;
3787     GetEventsPrivate(event_sp, llvm::None, control_only);
3788     if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3789       if (log)
3790         log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3791                     ") got a control event: %d",
3792                     __FUNCTION__, static_cast<void *>(this), GetID(),
3793                     event_sp->GetType());
3794 
3795       switch (event_sp->GetType()) {
3796       case eBroadcastInternalStateControlStop:
3797         exit_now = true;
3798         break; // doing any internal state management below
3799 
3800       case eBroadcastInternalStateControlPause:
3801         control_only = true;
3802         break;
3803 
3804       case eBroadcastInternalStateControlResume:
3805         control_only = false;
3806         break;
3807       }
3808 
3809       continue;
3810     } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3811       if (m_public_state.GetValue() == eStateAttaching) {
3812         if (log)
3813           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3814                       ") woke up with an interrupt while attaching - "
3815                       "forwarding interrupt.",
3816                       __FUNCTION__, static_cast<void *>(this), GetID());
3817         BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3818       } else if (StateIsRunningState(m_last_broadcast_state)) {
3819         if (log)
3820           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3821                       ") woke up with an interrupt - Halting.",
3822                       __FUNCTION__, static_cast<void *>(this), GetID());
3823         Status error = HaltPrivate();
3824         if (error.Fail() && log)
3825           log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3826                       ") failed to halt the process: %s",
3827                       __FUNCTION__, static_cast<void *>(this), GetID(),
3828                       error.AsCString());
3829         // Halt should generate a stopped event. Make a note of the fact that
3830         // we were doing the interrupt, so we can set the interrupted flag
3831         // after we receive the event. We deliberately set this to true even if
3832         // HaltPrivate failed, so that we can interrupt on the next natural
3833         // stop.
3834         interrupt_requested = true;
3835       } else {
3836         // This can happen when someone (e.g. Process::Halt) sees that we are
3837         // running and sends an interrupt request, but the process actually
3838         // stops before we receive it. In that case, we can just ignore the
3839         // request. We use m_last_broadcast_state, because the Stopped event
3840         // may not have been popped of the event queue yet, which is when the
3841         // public state gets updated.
3842         if (log)
3843           log->Printf(
3844               "Process::%s ignoring interrupt as we have already stopped.",
3845               __FUNCTION__);
3846       }
3847       continue;
3848     }
3849 
3850     const StateType internal_state =
3851         Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3852 
3853     if (internal_state != eStateInvalid) {
3854       if (m_clear_thread_plans_on_stop &&
3855           StateIsStoppedState(internal_state, true)) {
3856         m_clear_thread_plans_on_stop = false;
3857         m_thread_list.DiscardThreadPlans();
3858       }
3859 
3860       if (interrupt_requested) {
3861         if (StateIsStoppedState(internal_state, true)) {
3862           // We requested the interrupt, so mark this as such in the stop event
3863           // so clients can tell an interrupted process from a natural stop
3864           ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3865           interrupt_requested = false;
3866         } else if (log) {
3867           log->Printf("Process::%s interrupt_requested, but a non-stopped "
3868                       "state '%s' received.",
3869                       __FUNCTION__, StateAsCString(internal_state));
3870         }
3871       }
3872 
3873       HandlePrivateEvent(event_sp);
3874     }
3875 
3876     if (internal_state == eStateInvalid || internal_state == eStateExited ||
3877         internal_state == eStateDetached) {
3878       if (log)
3879         log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3880                     ") about to exit with internal state %s...",
3881                     __FUNCTION__, static_cast<void *>(this), GetID(),
3882                     StateAsCString(internal_state));
3883 
3884       break;
3885     }
3886   }
3887 
3888   // Verify log is still enabled before attempting to write to it...
3889   if (log)
3890     log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3891                 __FUNCTION__, static_cast<void *>(this), GetID());
3892 
3893   // If we are a secondary thread, then the primary thread we are working for
3894   // will have already acquired the public_run_lock, and isn't done with what
3895   // it was doing yet, so don't try to change it on the way out.
3896   if (!is_secondary_thread)
3897     m_public_run_lock.SetStopped();
3898   return NULL;
3899 }
3900 
3901 //------------------------------------------------------------------
3902 // Process Event Data
3903 //------------------------------------------------------------------
3904 
3905 Process::ProcessEventData::ProcessEventData()
3906     : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3907       m_update_state(0), m_interrupted(false) {}
3908 
3909 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3910                                             StateType state)
3911     : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3912       m_update_state(0), m_interrupted(false) {
3913   if (process_sp)
3914     m_process_wp = process_sp;
3915 }
3916 
3917 Process::ProcessEventData::~ProcessEventData() = default;
3918 
3919 ConstString Process::ProcessEventData::GetFlavorString() {
3920   static ConstString g_flavor("Process::ProcessEventData");
3921   return g_flavor;
3922 }
3923 
3924 ConstString Process::ProcessEventData::GetFlavor() const {
3925   return ProcessEventData::GetFlavorString();
3926 }
3927 
3928 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3929   ProcessSP process_sp(m_process_wp.lock());
3930 
3931   if (!process_sp)
3932     return;
3933 
3934   // This function gets called twice for each event, once when the event gets
3935   // pulled off of the private process event queue, and then any number of
3936   // times, first when it gets pulled off of the public event queue, then other
3937   // times when we're pretending that this is where we stopped at the end of
3938   // expression evaluation.  m_update_state is used to distinguish these three
3939   // cases; it is 0 when we're just pulling it off for private handling, and >
3940   // 1 for expression evaluation, and we don't want to do the breakpoint
3941   // command handling then.
3942   if (m_update_state != 1)
3943     return;
3944 
3945   process_sp->SetPublicState(
3946       m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3947 
3948   if (m_state == eStateStopped && !m_restarted) {
3949     // Let process subclasses know we are about to do a public stop and do
3950     // anything they might need to in order to speed up register and memory
3951     // accesses.
3952     process_sp->WillPublicStop();
3953   }
3954 
3955   // If this is a halt event, even if the halt stopped with some reason other
3956   // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3957   // the halt request came through) don't do the StopInfo actions, as they may
3958   // end up restarting the process.
3959   if (m_interrupted)
3960     return;
3961 
3962   // If we're stopped and haven't restarted, then do the StopInfo actions here:
3963   if (m_state == eStateStopped && !m_restarted) {
3964     ThreadList &curr_thread_list = process_sp->GetThreadList();
3965     uint32_t num_threads = curr_thread_list.GetSize();
3966     uint32_t idx;
3967 
3968     // The actions might change one of the thread's stop_info's opinions about
3969     // whether we should stop the process, so we need to query that as we go.
3970 
3971     // One other complication here, is that we try to catch any case where the
3972     // target has run (except for expressions) and immediately exit, but if we
3973     // get that wrong (which is possible) then the thread list might have
3974     // changed, and that would cause our iteration here to crash.  We could
3975     // make a copy of the thread list, but we'd really like to also know if it
3976     // has changed at all, so we make up a vector of the thread ID's and check
3977     // what we get back against this list & bag out if anything differs.
3978     std::vector<uint32_t> thread_index_array(num_threads);
3979     for (idx = 0; idx < num_threads; ++idx)
3980       thread_index_array[idx] =
3981           curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3982 
3983     // Use this to track whether we should continue from here.  We will only
3984     // continue the target running if no thread says we should stop.  Of course
3985     // if some thread's PerformAction actually sets the target running, then it
3986     // doesn't matter what the other threads say...
3987 
3988     bool still_should_stop = false;
3989 
3990     // Sometimes - for instance if we have a bug in the stub we are talking to,
3991     // we stop but no thread has a valid stop reason.  In that case we should
3992     // just stop, because we have no way of telling what the right thing to do
3993     // is, and it's better to let the user decide than continue behind their
3994     // backs.
3995 
3996     bool does_anybody_have_an_opinion = false;
3997 
3998     for (idx = 0; idx < num_threads; ++idx) {
3999       curr_thread_list = process_sp->GetThreadList();
4000       if (curr_thread_list.GetSize() != num_threads) {
4001         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4002                                                         LIBLLDB_LOG_PROCESS));
4003         if (log)
4004           log->Printf(
4005               "Number of threads changed from %u to %u while processing event.",
4006               num_threads, curr_thread_list.GetSize());
4007         break;
4008       }
4009 
4010       lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4011 
4012       if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4013         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4014                                                         LIBLLDB_LOG_PROCESS));
4015         if (log)
4016           log->Printf("The thread at position %u changed from %u to %u while "
4017                       "processing event.",
4018                       idx, thread_index_array[idx], thread_sp->GetIndexID());
4019         break;
4020       }
4021 
4022       StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4023       if (stop_info_sp && stop_info_sp->IsValid()) {
4024         does_anybody_have_an_opinion = true;
4025         bool this_thread_wants_to_stop;
4026         if (stop_info_sp->GetOverrideShouldStop()) {
4027           this_thread_wants_to_stop =
4028               stop_info_sp->GetOverriddenShouldStopValue();
4029         } else {
4030           stop_info_sp->PerformAction(event_ptr);
4031           // The stop action might restart the target.  If it does, then we
4032           // want to mark that in the event so that whoever is receiving it
4033           // will know to wait for the running event and reflect that state
4034           // appropriately. We also need to stop processing actions, since they
4035           // aren't expecting the target to be running.
4036 
4037           // FIXME: we might have run.
4038           if (stop_info_sp->HasTargetRunSinceMe()) {
4039             SetRestarted(true);
4040             break;
4041           }
4042 
4043           this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4044         }
4045 
4046         if (!still_should_stop)
4047           still_should_stop = this_thread_wants_to_stop;
4048       }
4049     }
4050 
4051     if (!GetRestarted()) {
4052       if (!still_should_stop && does_anybody_have_an_opinion) {
4053         // We've been asked to continue, so do that here.
4054         SetRestarted(true);
4055         // Use the public resume method here, since this is just extending a
4056         // public resume.
4057         process_sp->PrivateResume();
4058       } else {
4059         bool hijacked =
4060           process_sp->IsHijackedForEvent(eBroadcastBitStateChanged)
4061           && !process_sp->StateChangedIsHijackedForSynchronousResume();
4062 
4063         if (!hijacked) {
4064           // If we didn't restart, run the Stop Hooks here.
4065           // Don't do that if state changed events aren't hooked up to the
4066           // public (or SyncResume) broadcasters.  StopHooks are just for
4067           // real public stops.  They might also restart the target,
4068           // so watch for that.
4069           process_sp->GetTarget().RunStopHooks();
4070           if (process_sp->GetPrivateState() == eStateRunning)
4071             SetRestarted(true);
4072       }
4073     }
4074   }
4075 }
4076 }
4077 
4078 void Process::ProcessEventData::Dump(Stream *s) const {
4079   ProcessSP process_sp(m_process_wp.lock());
4080 
4081   if (process_sp)
4082     s->Printf(" process = %p (pid = %" PRIu64 "), ",
4083               static_cast<void *>(process_sp.get()), process_sp->GetID());
4084   else
4085     s->PutCString(" process = NULL, ");
4086 
4087   s->Printf("state = %s", StateAsCString(GetState()));
4088 }
4089 
4090 const Process::ProcessEventData *
4091 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4092   if (event_ptr) {
4093     const EventData *event_data = event_ptr->GetData();
4094     if (event_data &&
4095         event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4096       return static_cast<const ProcessEventData *>(event_ptr->GetData());
4097   }
4098   return nullptr;
4099 }
4100 
4101 ProcessSP
4102 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4103   ProcessSP process_sp;
4104   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4105   if (data)
4106     process_sp = data->GetProcessSP();
4107   return process_sp;
4108 }
4109 
4110 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4111   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4112   if (data == nullptr)
4113     return eStateInvalid;
4114   else
4115     return data->GetState();
4116 }
4117 
4118 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4119   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4120   if (data == nullptr)
4121     return false;
4122   else
4123     return data->GetRestarted();
4124 }
4125 
4126 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4127                                                     bool new_value) {
4128   ProcessEventData *data =
4129       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4130   if (data != nullptr)
4131     data->SetRestarted(new_value);
4132 }
4133 
4134 size_t
4135 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4136   ProcessEventData *data =
4137       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4138   if (data != nullptr)
4139     return data->GetNumRestartedReasons();
4140   else
4141     return 0;
4142 }
4143 
4144 const char *
4145 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4146                                                      size_t idx) {
4147   ProcessEventData *data =
4148       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4149   if (data != nullptr)
4150     return data->GetRestartedReasonAtIndex(idx);
4151   else
4152     return nullptr;
4153 }
4154 
4155 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4156                                                    const char *reason) {
4157   ProcessEventData *data =
4158       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4159   if (data != nullptr)
4160     data->AddRestartedReason(reason);
4161 }
4162 
4163 bool Process::ProcessEventData::GetInterruptedFromEvent(
4164     const Event *event_ptr) {
4165   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4166   if (data == nullptr)
4167     return false;
4168   else
4169     return data->GetInterrupted();
4170 }
4171 
4172 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4173                                                       bool new_value) {
4174   ProcessEventData *data =
4175       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4176   if (data != nullptr)
4177     data->SetInterrupted(new_value);
4178 }
4179 
4180 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4181   ProcessEventData *data =
4182       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4183   if (data) {
4184     data->SetUpdateStateOnRemoval();
4185     return true;
4186   }
4187   return false;
4188 }
4189 
4190 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
4191 
4192 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4193   exe_ctx.SetTargetPtr(&GetTarget());
4194   exe_ctx.SetProcessPtr(this);
4195   exe_ctx.SetThreadPtr(nullptr);
4196   exe_ctx.SetFramePtr(nullptr);
4197 }
4198 
4199 // uint32_t
4200 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4201 // std::vector<lldb::pid_t> &pids)
4202 //{
4203 //    return 0;
4204 //}
4205 //
4206 // ArchSpec
4207 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4208 //{
4209 //    return Host::GetArchSpecForExistingProcess (pid);
4210 //}
4211 //
4212 // ArchSpec
4213 // Process::GetArchSpecForExistingProcess (const char *process_name)
4214 //{
4215 //    return Host::GetArchSpecForExistingProcess (process_name);
4216 //}
4217 
4218 void Process::AppendSTDOUT(const char *s, size_t len) {
4219   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4220   m_stdout_data.append(s, len);
4221   BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4222                          new ProcessEventData(shared_from_this(), GetState()));
4223 }
4224 
4225 void Process::AppendSTDERR(const char *s, size_t len) {
4226   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4227   m_stderr_data.append(s, len);
4228   BroadcastEventIfUnique(eBroadcastBitSTDERR,
4229                          new ProcessEventData(shared_from_this(), GetState()));
4230 }
4231 
4232 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4233   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4234   m_profile_data.push_back(one_profile_data);
4235   BroadcastEventIfUnique(eBroadcastBitProfileData,
4236                          new ProcessEventData(shared_from_this(), GetState()));
4237 }
4238 
4239 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4240                                       const StructuredDataPluginSP &plugin_sp) {
4241   BroadcastEvent(
4242       eBroadcastBitStructuredData,
4243       new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4244 }
4245 
4246 StructuredDataPluginSP
4247 Process::GetStructuredDataPlugin(ConstString type_name) const {
4248   auto find_it = m_structured_data_plugin_map.find(type_name);
4249   if (find_it != m_structured_data_plugin_map.end())
4250     return find_it->second;
4251   else
4252     return StructuredDataPluginSP();
4253 }
4254 
4255 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4256   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4257   if (m_profile_data.empty())
4258     return 0;
4259 
4260   std::string &one_profile_data = m_profile_data.front();
4261   size_t bytes_available = one_profile_data.size();
4262   if (bytes_available > 0) {
4263     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4264     if (log)
4265       log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4266                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4267     if (bytes_available > buf_size) {
4268       memcpy(buf, one_profile_data.c_str(), buf_size);
4269       one_profile_data.erase(0, buf_size);
4270       bytes_available = buf_size;
4271     } else {
4272       memcpy(buf, one_profile_data.c_str(), bytes_available);
4273       m_profile_data.erase(m_profile_data.begin());
4274     }
4275   }
4276   return bytes_available;
4277 }
4278 
4279 //------------------------------------------------------------------
4280 // Process STDIO
4281 //------------------------------------------------------------------
4282 
4283 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4284   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4285   size_t bytes_available = m_stdout_data.size();
4286   if (bytes_available > 0) {
4287     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4288     if (log)
4289       log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4290                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4291     if (bytes_available > buf_size) {
4292       memcpy(buf, m_stdout_data.c_str(), buf_size);
4293       m_stdout_data.erase(0, buf_size);
4294       bytes_available = buf_size;
4295     } else {
4296       memcpy(buf, m_stdout_data.c_str(), bytes_available);
4297       m_stdout_data.clear();
4298     }
4299   }
4300   return bytes_available;
4301 }
4302 
4303 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4304   std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4305   size_t bytes_available = m_stderr_data.size();
4306   if (bytes_available > 0) {
4307     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4308     if (log)
4309       log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4310                   static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4311     if (bytes_available > buf_size) {
4312       memcpy(buf, m_stderr_data.c_str(), buf_size);
4313       m_stderr_data.erase(0, buf_size);
4314       bytes_available = buf_size;
4315     } else {
4316       memcpy(buf, m_stderr_data.c_str(), bytes_available);
4317       m_stderr_data.clear();
4318     }
4319   }
4320   return bytes_available;
4321 }
4322 
4323 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4324                                            size_t src_len) {
4325   Process *process = (Process *)baton;
4326   process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4327 }
4328 
4329 class IOHandlerProcessSTDIO : public IOHandler {
4330 public:
4331   IOHandlerProcessSTDIO(Process *process, int write_fd)
4332       : IOHandler(process->GetTarget().GetDebugger(),
4333                   IOHandler::Type::ProcessIO),
4334         m_process(process), m_write_file(write_fd, false) {
4335     m_pipe.CreateNew(false);
4336     m_read_file.SetDescriptor(GetInputFD(), false);
4337   }
4338 
4339   ~IOHandlerProcessSTDIO() override = default;
4340 
4341   // Each IOHandler gets to run until it is done. It should read data from the
4342   // "in" and place output into "out" and "err and return when done.
4343   void Run() override {
4344     if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4345         !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4346       SetIsDone(true);
4347       return;
4348     }
4349 
4350     SetIsDone(false);
4351     const int read_fd = m_read_file.GetDescriptor();
4352     TerminalState terminal_state;
4353     terminal_state.Save(read_fd, false);
4354     Terminal terminal(read_fd);
4355     terminal.SetCanonical(false);
4356     terminal.SetEcho(false);
4357 // FD_ZERO, FD_SET are not supported on windows
4358 #ifndef _WIN32
4359     const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4360     m_is_running = true;
4361     while (!GetIsDone()) {
4362       SelectHelper select_helper;
4363       select_helper.FDSetRead(read_fd);
4364       select_helper.FDSetRead(pipe_read_fd);
4365       Status error = select_helper.Select();
4366 
4367       if (error.Fail()) {
4368         SetIsDone(true);
4369       } else {
4370         char ch = 0;
4371         size_t n;
4372         if (select_helper.FDIsSetRead(read_fd)) {
4373           n = 1;
4374           if (m_read_file.Read(&ch, n).Success() && n == 1) {
4375             if (m_write_file.Write(&ch, n).Fail() || n != 1)
4376               SetIsDone(true);
4377           } else
4378             SetIsDone(true);
4379         }
4380         if (select_helper.FDIsSetRead(pipe_read_fd)) {
4381           size_t bytes_read;
4382           // Consume the interrupt byte
4383           Status error = m_pipe.Read(&ch, 1, bytes_read);
4384           if (error.Success()) {
4385             switch (ch) {
4386             case 'q':
4387               SetIsDone(true);
4388               break;
4389             case 'i':
4390               if (StateIsRunningState(m_process->GetState()))
4391                 m_process->SendAsyncInterrupt();
4392               break;
4393             }
4394           }
4395         }
4396       }
4397     }
4398     m_is_running = false;
4399 #endif
4400     terminal_state.Restore();
4401   }
4402 
4403   void Cancel() override {
4404     SetIsDone(true);
4405     // Only write to our pipe to cancel if we are in
4406     // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4407     // is being run from the command interpreter:
4408     //
4409     // (lldb) step_process_thousands_of_times
4410     //
4411     // In this case the command interpreter will be in the middle of handling
4412     // the command and if the process pushes and pops the IOHandler thousands
4413     // of times, we can end up writing to m_pipe without ever consuming the
4414     // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4415     // deadlocking when the pipe gets fed up and blocks until data is consumed.
4416     if (m_is_running) {
4417       char ch = 'q'; // Send 'q' for quit
4418       size_t bytes_written = 0;
4419       m_pipe.Write(&ch, 1, bytes_written);
4420     }
4421   }
4422 
4423   bool Interrupt() override {
4424     // Do only things that are safe to do in an interrupt context (like in a
4425     // SIGINT handler), like write 1 byte to a file descriptor. This will
4426     // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4427     // that was written to the pipe and then call
4428     // m_process->SendAsyncInterrupt() from a much safer location in code.
4429     if (m_active) {
4430       char ch = 'i'; // Send 'i' for interrupt
4431       size_t bytes_written = 0;
4432       Status result = m_pipe.Write(&ch, 1, bytes_written);
4433       return result.Success();
4434     } else {
4435       // This IOHandler might be pushed on the stack, but not being run
4436       // currently so do the right thing if we aren't actively watching for
4437       // STDIN by sending the interrupt to the process. Otherwise the write to
4438       // the pipe above would do nothing. This can happen when the command
4439       // interpreter is running and gets a "expression ...". It will be on the
4440       // IOHandler thread and sending the input is complete to the delegate
4441       // which will cause the expression to run, which will push the process IO
4442       // handler, but not run it.
4443 
4444       if (StateIsRunningState(m_process->GetState())) {
4445         m_process->SendAsyncInterrupt();
4446         return true;
4447       }
4448     }
4449     return false;
4450   }
4451 
4452   void GotEOF() override {}
4453 
4454 protected:
4455   Process *m_process;
4456   File m_read_file;  // Read from this file (usually actual STDIN for LLDB
4457   File m_write_file; // Write to this file (usually the master pty for getting
4458                      // io to debuggee)
4459   Pipe m_pipe;
4460   std::atomic<bool> m_is_running{false};
4461 };
4462 
4463 void Process::SetSTDIOFileDescriptor(int fd) {
4464   // First set up the Read Thread for reading/handling process I/O
4465 
4466   std::unique_ptr<ConnectionFileDescriptor> conn_up(
4467       new ConnectionFileDescriptor(fd, true));
4468 
4469   if (conn_up) {
4470     m_stdio_communication.SetConnection(conn_up.release());
4471     if (m_stdio_communication.IsConnected()) {
4472       m_stdio_communication.SetReadThreadBytesReceivedCallback(
4473           STDIOReadThreadBytesReceived, this);
4474       m_stdio_communication.StartReadThread();
4475 
4476       // Now read thread is set up, set up input reader.
4477 
4478       if (!m_process_input_reader)
4479         m_process_input_reader =
4480             std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4481     }
4482   }
4483 }
4484 
4485 bool Process::ProcessIOHandlerIsActive() {
4486   IOHandlerSP io_handler_sp(m_process_input_reader);
4487   if (io_handler_sp)
4488     return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4489   return false;
4490 }
4491 bool Process::PushProcessIOHandler() {
4492   IOHandlerSP io_handler_sp(m_process_input_reader);
4493   if (io_handler_sp) {
4494     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4495     if (log)
4496       log->Printf("Process::%s pushing IO handler", __FUNCTION__);
4497 
4498     io_handler_sp->SetIsDone(false);
4499     // If we evaluate an utility function, then we don't cancel the current
4500     // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4501     // existing IOHandler that potentially provides the user interface (e.g.
4502     // the IOHandler for Editline).
4503     bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4504     GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
4505     return true;
4506   }
4507   return false;
4508 }
4509 
4510 bool Process::PopProcessIOHandler() {
4511   IOHandlerSP io_handler_sp(m_process_input_reader);
4512   if (io_handler_sp)
4513     return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4514   return false;
4515 }
4516 
4517 // The process needs to know about installed plug-ins
4518 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4519 
4520 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4521 
4522 namespace {
4523 // RestorePlanState is used to record the "is private", "is master" and "okay
4524 // to discard" fields of the plan we are running, and reset it on Clean or on
4525 // destruction. It will only reset the state once, so you can call Clean and
4526 // then monkey with the state and it won't get reset on you again.
4527 
4528 class RestorePlanState {
4529 public:
4530   RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4531       : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4532     if (m_thread_plan_sp) {
4533       m_private = m_thread_plan_sp->GetPrivate();
4534       m_is_master = m_thread_plan_sp->IsMasterPlan();
4535       m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4536     }
4537   }
4538 
4539   ~RestorePlanState() { Clean(); }
4540 
4541   void Clean() {
4542     if (!m_already_reset && m_thread_plan_sp) {
4543       m_already_reset = true;
4544       m_thread_plan_sp->SetPrivate(m_private);
4545       m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4546       m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4547     }
4548   }
4549 
4550 private:
4551   lldb::ThreadPlanSP m_thread_plan_sp;
4552   bool m_already_reset;
4553   bool m_private;
4554   bool m_is_master;
4555   bool m_okay_to_discard;
4556 };
4557 } // anonymous namespace
4558 
4559 static microseconds
4560 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4561   const milliseconds default_one_thread_timeout(250);
4562 
4563   // If the overall wait is forever, then we don't need to worry about it.
4564   if (!options.GetTimeout()) {
4565     return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4566                                          : default_one_thread_timeout;
4567   }
4568 
4569   // If the one thread timeout is set, use it.
4570   if (options.GetOneThreadTimeout())
4571     return *options.GetOneThreadTimeout();
4572 
4573   // Otherwise use half the total timeout, bounded by the
4574   // default_one_thread_timeout.
4575   return std::min<microseconds>(default_one_thread_timeout,
4576                                 *options.GetTimeout() / 2);
4577 }
4578 
4579 static Timeout<std::micro>
4580 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4581                      bool before_first_timeout) {
4582   // If we are going to run all threads the whole time, or if we are only going
4583   // to run one thread, we can just return the overall timeout.
4584   if (!options.GetStopOthers() || !options.GetTryAllThreads())
4585     return options.GetTimeout();
4586 
4587   if (before_first_timeout)
4588     return GetOneThreadExpressionTimeout(options);
4589 
4590   if (!options.GetTimeout())
4591     return llvm::None;
4592   else
4593     return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4594 }
4595 
4596 static llvm::Optional<ExpressionResults>
4597 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4598                    RestorePlanState &restorer, const EventSP &event_sp,
4599                    EventSP &event_to_broadcast_sp,
4600                    const EvaluateExpressionOptions &options, bool handle_interrupts) {
4601   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4602 
4603   ThreadPlanSP plan = thread.GetCompletedPlan();
4604   if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4605     LLDB_LOG(log, "execution completed successfully");
4606 
4607     // Restore the plan state so it will get reported as intended when we are
4608     // done.
4609     restorer.Clean();
4610     return eExpressionCompleted;
4611   }
4612 
4613   StopInfoSP stop_info_sp = thread.GetStopInfo();
4614   if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4615       stop_info_sp->ShouldNotify(event_sp.get())) {
4616     LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4617     if (!options.DoesIgnoreBreakpoints()) {
4618       // Restore the plan state and then force Private to false.  We are going
4619       // to stop because of this plan so we need it to become a public plan or
4620       // it won't report correctly when we continue to its termination later
4621       // on.
4622       restorer.Clean();
4623       thread_plan_sp->SetPrivate(false);
4624       event_to_broadcast_sp = event_sp;
4625     }
4626     return eExpressionHitBreakpoint;
4627   }
4628 
4629   if (!handle_interrupts &&
4630       Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4631     return llvm::None;
4632 
4633   LLDB_LOG(log, "thread plan did not successfully complete");
4634   if (!options.DoesUnwindOnError())
4635     event_to_broadcast_sp = event_sp;
4636   return eExpressionInterrupted;
4637 }
4638 
4639 ExpressionResults
4640 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4641                        lldb::ThreadPlanSP &thread_plan_sp,
4642                        const EvaluateExpressionOptions &options,
4643                        DiagnosticManager &diagnostic_manager) {
4644   ExpressionResults return_value = eExpressionSetupError;
4645 
4646   std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4647 
4648   if (!thread_plan_sp) {
4649     diagnostic_manager.PutString(
4650         eDiagnosticSeverityError,
4651         "RunThreadPlan called with empty thread plan.");
4652     return eExpressionSetupError;
4653   }
4654 
4655   if (!thread_plan_sp->ValidatePlan(nullptr)) {
4656     diagnostic_manager.PutString(
4657         eDiagnosticSeverityError,
4658         "RunThreadPlan called with an invalid thread plan.");
4659     return eExpressionSetupError;
4660   }
4661 
4662   if (exe_ctx.GetProcessPtr() != this) {
4663     diagnostic_manager.PutString(eDiagnosticSeverityError,
4664                                  "RunThreadPlan called on wrong process.");
4665     return eExpressionSetupError;
4666   }
4667 
4668   Thread *thread = exe_ctx.GetThreadPtr();
4669   if (thread == nullptr) {
4670     diagnostic_manager.PutString(eDiagnosticSeverityError,
4671                                  "RunThreadPlan called with invalid thread.");
4672     return eExpressionSetupError;
4673   }
4674 
4675   // We need to change some of the thread plan attributes for the thread plan
4676   // runner.  This will restore them when we are done:
4677 
4678   RestorePlanState thread_plan_restorer(thread_plan_sp);
4679 
4680   // We rely on the thread plan we are running returning "PlanCompleted" if
4681   // when it successfully completes. For that to be true the plan can't be
4682   // private - since private plans suppress themselves in the GetCompletedPlan
4683   // call.
4684 
4685   thread_plan_sp->SetPrivate(false);
4686 
4687   // The plans run with RunThreadPlan also need to be terminal master plans or
4688   // when they are done we will end up asking the plan above us whether we
4689   // should stop, which may give the wrong answer.
4690 
4691   thread_plan_sp->SetIsMasterPlan(true);
4692   thread_plan_sp->SetOkayToDiscard(false);
4693 
4694   // If we are running some utility expression for LLDB, we now have to mark
4695   // this in the ProcesModID of this process. This RAII takes care of marking
4696   // and reverting the mark it once we are done running the expression.
4697   UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4698 
4699   if (m_private_state.GetValue() != eStateStopped) {
4700     diagnostic_manager.PutString(
4701         eDiagnosticSeverityError,
4702         "RunThreadPlan called while the private state was not stopped.");
4703     return eExpressionSetupError;
4704   }
4705 
4706   // Save the thread & frame from the exe_ctx for restoration after we run
4707   const uint32_t thread_idx_id = thread->GetIndexID();
4708   StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4709   if (!selected_frame_sp) {
4710     thread->SetSelectedFrame(nullptr);
4711     selected_frame_sp = thread->GetSelectedFrame();
4712     if (!selected_frame_sp) {
4713       diagnostic_manager.Printf(
4714           eDiagnosticSeverityError,
4715           "RunThreadPlan called without a selected frame on thread %d",
4716           thread_idx_id);
4717       return eExpressionSetupError;
4718     }
4719   }
4720 
4721   // Make sure the timeout values make sense. The one thread timeout needs to
4722   // be smaller than the overall timeout.
4723   if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4724       *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4725     diagnostic_manager.PutString(eDiagnosticSeverityError,
4726                                  "RunThreadPlan called with one thread "
4727                                  "timeout greater than total timeout");
4728     return eExpressionSetupError;
4729   }
4730 
4731   StackID ctx_frame_id = selected_frame_sp->GetStackID();
4732 
4733   // N.B. Running the target may unset the currently selected thread and frame.
4734   // We don't want to do that either, so we should arrange to reset them as
4735   // well.
4736 
4737   lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4738 
4739   uint32_t selected_tid;
4740   StackID selected_stack_id;
4741   if (selected_thread_sp) {
4742     selected_tid = selected_thread_sp->GetIndexID();
4743     selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4744   } else {
4745     selected_tid = LLDB_INVALID_THREAD_ID;
4746   }
4747 
4748   HostThread backup_private_state_thread;
4749   lldb::StateType old_state = eStateInvalid;
4750   lldb::ThreadPlanSP stopper_base_plan_sp;
4751 
4752   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4753                                                   LIBLLDB_LOG_PROCESS));
4754   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4755     // Yikes, we are running on the private state thread!  So we can't wait for
4756     // public events on this thread, since we are the thread that is generating
4757     // public events. The simplest thing to do is to spin up a temporary thread
4758     // to handle private state thread events while we are fielding public
4759     // events here.
4760     if (log)
4761       log->Printf("Running thread plan on private state thread, spinning up "
4762                   "another state thread to handle the events.");
4763 
4764     backup_private_state_thread = m_private_state_thread;
4765 
4766     // One other bit of business: we want to run just this thread plan and
4767     // anything it pushes, and then stop, returning control here. But in the
4768     // normal course of things, the plan above us on the stack would be given a
4769     // shot at the stop event before deciding to stop, and we don't want that.
4770     // So we insert a "stopper" base plan on the stack before the plan we want
4771     // to run.  Since base plans always stop and return control to the user,
4772     // that will do just what we want.
4773     stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4774     thread->QueueThreadPlan(stopper_base_plan_sp, false);
4775     // Have to make sure our public state is stopped, since otherwise the
4776     // reporting logic below doesn't work correctly.
4777     old_state = m_public_state.GetValue();
4778     m_public_state.SetValueNoLock(eStateStopped);
4779 
4780     // Now spin up the private state thread:
4781     StartPrivateStateThread(true);
4782   }
4783 
4784   thread->QueueThreadPlan(
4785       thread_plan_sp, false); // This used to pass "true" does that make sense?
4786 
4787   if (options.GetDebug()) {
4788     // In this case, we aren't actually going to run, we just want to stop
4789     // right away. Flush this thread so we will refetch the stacks and show the
4790     // correct backtrace.
4791     // FIXME: To make this prettier we should invent some stop reason for this,
4792     // but that
4793     // is only cosmetic, and this functionality is only of use to lldb
4794     // developers who can live with not pretty...
4795     thread->Flush();
4796     return eExpressionStoppedForDebug;
4797   }
4798 
4799   ListenerSP listener_sp(
4800       Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4801 
4802   lldb::EventSP event_to_broadcast_sp;
4803 
4804   {
4805     // This process event hijacker Hijacks the Public events and its destructor
4806     // makes sure that the process events get restored on exit to the function.
4807     //
4808     // If the event needs to propagate beyond the hijacker (e.g., the process
4809     // exits during execution), then the event is put into
4810     // event_to_broadcast_sp for rebroadcasting.
4811 
4812     ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4813 
4814     if (log) {
4815       StreamString s;
4816       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4817       log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4818                   " to run thread plan \"%s\".",
4819                   thread->GetIndexID(), thread->GetID(), s.GetData());
4820     }
4821 
4822     bool got_event;
4823     lldb::EventSP event_sp;
4824     lldb::StateType stop_state = lldb::eStateInvalid;
4825 
4826     bool before_first_timeout = true; // This is set to false the first time
4827                                       // that we have to halt the target.
4828     bool do_resume = true;
4829     bool handle_running_event = true;
4830 
4831     // This is just for accounting:
4832     uint32_t num_resumes = 0;
4833 
4834     // If we are going to run all threads the whole time, or if we are only
4835     // going to run one thread, then we don't need the first timeout.  So we
4836     // pretend we are after the first timeout already.
4837     if (!options.GetStopOthers() || !options.GetTryAllThreads())
4838       before_first_timeout = false;
4839 
4840     if (log)
4841       log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
4842                   options.GetStopOthers(), options.GetTryAllThreads(),
4843                   before_first_timeout);
4844 
4845     // This isn't going to work if there are unfetched events on the queue. Are
4846     // there cases where we might want to run the remaining events here, and
4847     // then try to call the function?  That's probably being too tricky for our
4848     // own good.
4849 
4850     Event *other_events = listener_sp->PeekAtNextEvent();
4851     if (other_events != nullptr) {
4852       diagnostic_manager.PutString(
4853           eDiagnosticSeverityError,
4854           "RunThreadPlan called with pending events on the queue.");
4855       return eExpressionSetupError;
4856     }
4857 
4858     // We also need to make sure that the next event is delivered.  We might be
4859     // calling a function as part of a thread plan, in which case the last
4860     // delivered event could be the running event, and we don't want event
4861     // coalescing to cause us to lose OUR running event...
4862     ForceNextEventDelivery();
4863 
4864 // This while loop must exit out the bottom, there's cleanup that we need to do
4865 // when we are done. So don't call return anywhere within it.
4866 
4867 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4868     // It's pretty much impossible to write test cases for things like: One
4869     // thread timeout expires, I go to halt, but the process already stopped on
4870     // the function call stop breakpoint.  Turning on this define will make us
4871     // not fetch the first event till after the halt.  So if you run a quick
4872     // function, it will have completed, and the completion event will be
4873     // waiting, when you interrupt for halt. The expression evaluation should
4874     // still succeed.
4875     bool miss_first_event = true;
4876 #endif
4877     while (true) {
4878       // We usually want to resume the process if we get to the top of the
4879       // loop. The only exception is if we get two running events with no
4880       // intervening stop, which can happen, we will just wait for then next
4881       // stop event.
4882       if (log)
4883         log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
4884                     "before_first_timeout: %i.",
4885                     do_resume, handle_running_event, before_first_timeout);
4886 
4887       if (do_resume || handle_running_event) {
4888         // Do the initial resume and wait for the running event before going
4889         // further.
4890 
4891         if (do_resume) {
4892           num_resumes++;
4893           Status resume_error = PrivateResume();
4894           if (!resume_error.Success()) {
4895             diagnostic_manager.Printf(
4896                 eDiagnosticSeverityError,
4897                 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4898                 resume_error.AsCString());
4899             return_value = eExpressionSetupError;
4900             break;
4901           }
4902         }
4903 
4904         got_event =
4905             listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
4906         if (!got_event) {
4907           if (log)
4908             log->Printf("Process::RunThreadPlan(): didn't get any event after "
4909                         "resume %" PRIu32 ", exiting.",
4910                         num_resumes);
4911 
4912           diagnostic_manager.Printf(eDiagnosticSeverityError,
4913                                     "didn't get any event after resume %" PRIu32
4914                                     ", exiting.",
4915                                     num_resumes);
4916           return_value = eExpressionSetupError;
4917           break;
4918         }
4919 
4920         stop_state =
4921             Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4922 
4923         if (stop_state != eStateRunning) {
4924           bool restarted = false;
4925 
4926           if (stop_state == eStateStopped) {
4927             restarted = Process::ProcessEventData::GetRestartedFromEvent(
4928                 event_sp.get());
4929             if (log)
4930               log->Printf(
4931                   "Process::RunThreadPlan(): didn't get running event after "
4932                   "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4933                   "handle_running_event: %i).",
4934                   num_resumes, StateAsCString(stop_state), restarted, do_resume,
4935                   handle_running_event);
4936           }
4937 
4938           if (restarted) {
4939             // This is probably an overabundance of caution, I don't think I
4940             // should ever get a stopped & restarted event here.  But if I do,
4941             // the best thing is to Halt and then get out of here.
4942             const bool clear_thread_plans = false;
4943             const bool use_run_lock = false;
4944             Halt(clear_thread_plans, use_run_lock);
4945           }
4946 
4947           diagnostic_manager.Printf(
4948               eDiagnosticSeverityError,
4949               "didn't get running event after initial resume, got %s instead.",
4950               StateAsCString(stop_state));
4951           return_value = eExpressionSetupError;
4952           break;
4953         }
4954 
4955         if (log)
4956           log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
4957         // We need to call the function synchronously, so spin waiting for it
4958         // to return. If we get interrupted while executing, we're going to
4959         // lose our context, and won't be able to gather the result at this
4960         // point. We set the timeout AFTER the resume, since the resume takes
4961         // some time and we don't want to charge that to the timeout.
4962       } else {
4963         if (log)
4964           log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4965       }
4966 
4967       do_resume = true;
4968       handle_running_event = true;
4969 
4970       // Now wait for the process to stop again:
4971       event_sp.reset();
4972 
4973       Timeout<std::micro> timeout =
4974           GetExpressionTimeout(options, before_first_timeout);
4975       if (log) {
4976         if (timeout) {
4977           auto now = system_clock::now();
4978           log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
4979                       "endpoint is %s",
4980                       llvm::to_string(now).c_str(),
4981                       llvm::to_string(now + *timeout).c_str());
4982         } else {
4983           log->Printf("Process::RunThreadPlan(): about to wait forever.");
4984         }
4985       }
4986 
4987 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4988       // See comment above...
4989       if (miss_first_event) {
4990         usleep(1000);
4991         miss_first_event = false;
4992         got_event = false;
4993       } else
4994 #endif
4995         got_event = listener_sp->GetEvent(event_sp, timeout);
4996 
4997       if (got_event) {
4998         if (event_sp) {
4999           bool keep_going = false;
5000           if (event_sp->GetType() == eBroadcastBitInterrupt) {
5001             const bool clear_thread_plans = false;
5002             const bool use_run_lock = false;
5003             Halt(clear_thread_plans, use_run_lock);
5004             return_value = eExpressionInterrupted;
5005             diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5006                                          "execution halted by user interrupt.");
5007             if (log)
5008               log->Printf("Process::RunThreadPlan(): Got  interrupted by "
5009                           "eBroadcastBitInterrupted, exiting.");
5010             break;
5011           } else {
5012             stop_state =
5013                 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5014             if (log)
5015               log->Printf(
5016                   "Process::RunThreadPlan(): in while loop, got event: %s.",
5017                   StateAsCString(stop_state));
5018 
5019             switch (stop_state) {
5020             case lldb::eStateStopped: {
5021               // We stopped, figure out what we are going to do now.
5022               ThreadSP thread_sp =
5023                   GetThreadList().FindThreadByIndexID(thread_idx_id);
5024               if (!thread_sp) {
5025                 // Ooh, our thread has vanished.  Unlikely that this was
5026                 // successful execution...
5027                 if (log)
5028                   log->Printf("Process::RunThreadPlan(): execution completed "
5029                               "but our thread (index-id=%u) has vanished.",
5030                               thread_idx_id);
5031                 return_value = eExpressionInterrupted;
5032               } else if (Process::ProcessEventData::GetRestartedFromEvent(
5033                              event_sp.get())) {
5034                 // If we were restarted, we just need to go back up to fetch
5035                 // another event.
5036                 if (log) {
5037                   log->Printf("Process::RunThreadPlan(): Got a stop and "
5038                               "restart, so we'll continue waiting.");
5039                 }
5040                 keep_going = true;
5041                 do_resume = false;
5042                 handle_running_event = true;
5043               } else {
5044                 const bool handle_interrupts = true;
5045                 return_value = *HandleStoppedEvent(
5046                     *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5047                     event_to_broadcast_sp, options, handle_interrupts);
5048               }
5049             } break;
5050 
5051             case lldb::eStateRunning:
5052               // This shouldn't really happen, but sometimes we do get two
5053               // running events without an intervening stop, and in that case
5054               // we should just go back to waiting for the stop.
5055               do_resume = false;
5056               keep_going = true;
5057               handle_running_event = false;
5058               break;
5059 
5060             default:
5061               if (log)
5062                 log->Printf("Process::RunThreadPlan(): execution stopped with "
5063                             "unexpected state: %s.",
5064                             StateAsCString(stop_state));
5065 
5066               if (stop_state == eStateExited)
5067                 event_to_broadcast_sp = event_sp;
5068 
5069               diagnostic_manager.PutString(
5070                   eDiagnosticSeverityError,
5071                   "execution stopped with unexpected state.");
5072               return_value = eExpressionInterrupted;
5073               break;
5074             }
5075           }
5076 
5077           if (keep_going)
5078             continue;
5079           else
5080             break;
5081         } else {
5082           if (log)
5083             log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5084                             "the event pointer was null.  How odd...");
5085           return_value = eExpressionInterrupted;
5086           break;
5087         }
5088       } else {
5089         // If we didn't get an event that means we've timed out... We will
5090         // interrupt the process here.  Depending on what we were asked to do
5091         // we will either exit, or try with all threads running for the same
5092         // timeout.
5093 
5094         if (log) {
5095           if (options.GetTryAllThreads()) {
5096             if (before_first_timeout) {
5097               LLDB_LOG(log,
5098                        "Running function with one thread timeout timed out.");
5099             } else
5100               LLDB_LOG(log, "Restarting function with all threads enabled and "
5101                             "timeout: {0} timed out, abandoning execution.",
5102                        timeout);
5103           } else
5104             LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5105                           "abandoning execution.",
5106                      timeout);
5107         }
5108 
5109         // It is possible that between the time we issued the Halt, and we get
5110         // around to calling Halt the target could have stopped.  That's fine,
5111         // Halt will figure that out and send the appropriate Stopped event.
5112         // BUT it is also possible that we stopped & restarted (e.g. hit a
5113         // signal with "stop" set to false.)  In
5114         // that case, we'll get the stopped & restarted event, and we should go
5115         // back to waiting for the Halt's stopped event.  That's what this
5116         // while loop does.
5117 
5118         bool back_to_top = true;
5119         uint32_t try_halt_again = 0;
5120         bool do_halt = true;
5121         const uint32_t num_retries = 5;
5122         while (try_halt_again < num_retries) {
5123           Status halt_error;
5124           if (do_halt) {
5125             if (log)
5126               log->Printf("Process::RunThreadPlan(): Running Halt.");
5127             const bool clear_thread_plans = false;
5128             const bool use_run_lock = false;
5129             Halt(clear_thread_plans, use_run_lock);
5130           }
5131           if (halt_error.Success()) {
5132             if (log)
5133               log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5134 
5135             got_event =
5136                 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5137 
5138             if (got_event) {
5139               stop_state =
5140                   Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5141               if (log) {
5142                 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5143                             StateAsCString(stop_state));
5144                 if (stop_state == lldb::eStateStopped &&
5145                     Process::ProcessEventData::GetInterruptedFromEvent(
5146                         event_sp.get()))
5147                   log->PutCString("    Event was the Halt interruption event.");
5148               }
5149 
5150               if (stop_state == lldb::eStateStopped) {
5151                 if (Process::ProcessEventData::GetRestartedFromEvent(
5152                         event_sp.get())) {
5153                   if (log)
5154                     log->PutCString("Process::RunThreadPlan(): Went to halt "
5155                                     "but got a restarted event, there must be "
5156                                     "an un-restarted stopped event so try "
5157                                     "again...  "
5158                                     "Exiting wait loop.");
5159                   try_halt_again++;
5160                   do_halt = false;
5161                   continue;
5162                 }
5163 
5164                 // Between the time we initiated the Halt and the time we
5165                 // delivered it, the process could have already finished its
5166                 // job.  Check that here:
5167                 const bool handle_interrupts = false;
5168                 if (auto result = HandleStoppedEvent(
5169                         *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5170                         event_to_broadcast_sp, options, handle_interrupts)) {
5171                   return_value = *result;
5172                   back_to_top = false;
5173                   break;
5174                 }
5175 
5176                 if (!options.GetTryAllThreads()) {
5177                   if (log)
5178                     log->PutCString("Process::RunThreadPlan(): try_all_threads "
5179                                     "was false, we stopped so now we're "
5180                                     "quitting.");
5181                   return_value = eExpressionInterrupted;
5182                   back_to_top = false;
5183                   break;
5184                 }
5185 
5186                 if (before_first_timeout) {
5187                   // Set all the other threads to run, and return to the top of
5188                   // the loop, which will continue;
5189                   before_first_timeout = false;
5190                   thread_plan_sp->SetStopOthers(false);
5191                   if (log)
5192                     log->PutCString(
5193                         "Process::RunThreadPlan(): about to resume.");
5194 
5195                   back_to_top = true;
5196                   break;
5197                 } else {
5198                   // Running all threads failed, so return Interrupted.
5199                   if (log)
5200                     log->PutCString("Process::RunThreadPlan(): running all "
5201                                     "threads timed out.");
5202                   return_value = eExpressionInterrupted;
5203                   back_to_top = false;
5204                   break;
5205                 }
5206               }
5207             } else {
5208               if (log)
5209                 log->PutCString("Process::RunThreadPlan(): halt said it "
5210                                 "succeeded, but I got no event.  "
5211                                 "I'm getting out of here passing Interrupted.");
5212               return_value = eExpressionInterrupted;
5213               back_to_top = false;
5214               break;
5215             }
5216           } else {
5217             try_halt_again++;
5218             continue;
5219           }
5220         }
5221 
5222         if (!back_to_top || try_halt_again > num_retries)
5223           break;
5224         else
5225           continue;
5226       }
5227     } // END WAIT LOOP
5228 
5229     // If we had to start up a temporary private state thread to run this
5230     // thread plan, shut it down now.
5231     if (backup_private_state_thread.IsJoinable()) {
5232       StopPrivateStateThread();
5233       Status error;
5234       m_private_state_thread = backup_private_state_thread;
5235       if (stopper_base_plan_sp) {
5236         thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5237       }
5238       if (old_state != eStateInvalid)
5239         m_public_state.SetValueNoLock(old_state);
5240     }
5241 
5242     if (return_value != eExpressionCompleted && log) {
5243       // Print a backtrace into the log so we can figure out where we are:
5244       StreamString s;
5245       s.PutCString("Thread state after unsuccessful completion: \n");
5246       thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5247       log->PutString(s.GetString());
5248     }
5249     // Restore the thread state if we are going to discard the plan execution.
5250     // There are three cases where this could happen: 1) The execution
5251     // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5252     // was true 3) We got some other error, and discard_on_error was true
5253     bool should_unwind = (return_value == eExpressionInterrupted &&
5254                           options.DoesUnwindOnError()) ||
5255                          (return_value == eExpressionHitBreakpoint &&
5256                           options.DoesIgnoreBreakpoints());
5257 
5258     if (return_value == eExpressionCompleted || should_unwind) {
5259       thread_plan_sp->RestoreThreadState();
5260     }
5261 
5262     // Now do some processing on the results of the run:
5263     if (return_value == eExpressionInterrupted ||
5264         return_value == eExpressionHitBreakpoint) {
5265       if (log) {
5266         StreamString s;
5267         if (event_sp)
5268           event_sp->Dump(&s);
5269         else {
5270           log->PutCString("Process::RunThreadPlan(): Stop event that "
5271                           "interrupted us is NULL.");
5272         }
5273 
5274         StreamString ts;
5275 
5276         const char *event_explanation = nullptr;
5277 
5278         do {
5279           if (!event_sp) {
5280             event_explanation = "<no event>";
5281             break;
5282           } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5283             event_explanation = "<user interrupt>";
5284             break;
5285           } else {
5286             const Process::ProcessEventData *event_data =
5287                 Process::ProcessEventData::GetEventDataFromEvent(
5288                     event_sp.get());
5289 
5290             if (!event_data) {
5291               event_explanation = "<no event data>";
5292               break;
5293             }
5294 
5295             Process *process = event_data->GetProcessSP().get();
5296 
5297             if (!process) {
5298               event_explanation = "<no process>";
5299               break;
5300             }
5301 
5302             ThreadList &thread_list = process->GetThreadList();
5303 
5304             uint32_t num_threads = thread_list.GetSize();
5305             uint32_t thread_index;
5306 
5307             ts.Printf("<%u threads> ", num_threads);
5308 
5309             for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5310               Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5311 
5312               if (!thread) {
5313                 ts.Printf("<?> ");
5314                 continue;
5315               }
5316 
5317               ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5318               RegisterContext *register_context =
5319                   thread->GetRegisterContext().get();
5320 
5321               if (register_context)
5322                 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5323               else
5324                 ts.Printf("[ip unknown] ");
5325 
5326               // Show the private stop info here, the public stop info will be
5327               // from the last natural stop.
5328               lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5329               if (stop_info_sp) {
5330                 const char *stop_desc = stop_info_sp->GetDescription();
5331                 if (stop_desc)
5332                   ts.PutCString(stop_desc);
5333               }
5334               ts.Printf(">");
5335             }
5336 
5337             event_explanation = ts.GetData();
5338           }
5339         } while (0);
5340 
5341         if (event_explanation)
5342           log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5343                       s.GetData(), event_explanation);
5344         else
5345           log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5346                       s.GetData());
5347       }
5348 
5349       if (should_unwind) {
5350         if (log)
5351           log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5352                       "discarding thread plans up to %p.",
5353                       static_cast<void *>(thread_plan_sp.get()));
5354         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5355       } else {
5356         if (log)
5357           log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5358                       "plan: %p not discarding.",
5359                       static_cast<void *>(thread_plan_sp.get()));
5360       }
5361     } else if (return_value == eExpressionSetupError) {
5362       if (log)
5363         log->PutCString("Process::RunThreadPlan(): execution set up error.");
5364 
5365       if (options.DoesUnwindOnError()) {
5366         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5367       }
5368     } else {
5369       if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5370         if (log)
5371           log->PutCString("Process::RunThreadPlan(): thread plan is done");
5372         return_value = eExpressionCompleted;
5373       } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5374         if (log)
5375           log->PutCString(
5376               "Process::RunThreadPlan(): thread plan was discarded");
5377         return_value = eExpressionDiscarded;
5378       } else {
5379         if (log)
5380           log->PutCString(
5381               "Process::RunThreadPlan(): thread plan stopped in mid course");
5382         if (options.DoesUnwindOnError() && thread_plan_sp) {
5383           if (log)
5384             log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5385                             "'cause unwind_on_error is set.");
5386           thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5387         }
5388       }
5389     }
5390 
5391     // Thread we ran the function in may have gone away because we ran the
5392     // target Check that it's still there, and if it is put it back in the
5393     // context. Also restore the frame in the context if it is still present.
5394     thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5395     if (thread) {
5396       exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5397     }
5398 
5399     // Also restore the current process'es selected frame & thread, since this
5400     // function calling may be done behind the user's back.
5401 
5402     if (selected_tid != LLDB_INVALID_THREAD_ID) {
5403       if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5404           selected_stack_id.IsValid()) {
5405         // We were able to restore the selected thread, now restore the frame:
5406         std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5407         StackFrameSP old_frame_sp =
5408             GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5409                 selected_stack_id);
5410         if (old_frame_sp)
5411           GetThreadList().GetSelectedThread()->SetSelectedFrame(
5412               old_frame_sp.get());
5413       }
5414     }
5415   }
5416 
5417   // If the process exited during the run of the thread plan, notify everyone.
5418 
5419   if (event_to_broadcast_sp) {
5420     if (log)
5421       log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5422     BroadcastEvent(event_to_broadcast_sp);
5423   }
5424 
5425   return return_value;
5426 }
5427 
5428 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5429   const char *result_name;
5430 
5431   switch (result) {
5432   case eExpressionCompleted:
5433     result_name = "eExpressionCompleted";
5434     break;
5435   case eExpressionDiscarded:
5436     result_name = "eExpressionDiscarded";
5437     break;
5438   case eExpressionInterrupted:
5439     result_name = "eExpressionInterrupted";
5440     break;
5441   case eExpressionHitBreakpoint:
5442     result_name = "eExpressionHitBreakpoint";
5443     break;
5444   case eExpressionSetupError:
5445     result_name = "eExpressionSetupError";
5446     break;
5447   case eExpressionParseError:
5448     result_name = "eExpressionParseError";
5449     break;
5450   case eExpressionResultUnavailable:
5451     result_name = "eExpressionResultUnavailable";
5452     break;
5453   case eExpressionTimedOut:
5454     result_name = "eExpressionTimedOut";
5455     break;
5456   case eExpressionStoppedForDebug:
5457     result_name = "eExpressionStoppedForDebug";
5458     break;
5459   }
5460   return result_name;
5461 }
5462 
5463 void Process::GetStatus(Stream &strm) {
5464   const StateType state = GetState();
5465   if (StateIsStoppedState(state, false)) {
5466     if (state == eStateExited) {
5467       int exit_status = GetExitStatus();
5468       const char *exit_description = GetExitDescription();
5469       strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5470                   GetID(), exit_status, exit_status,
5471                   exit_description ? exit_description : "");
5472     } else {
5473       if (state == eStateConnected)
5474         strm.Printf("Connected to remote target.\n");
5475       else
5476         strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5477     }
5478   } else {
5479     strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5480   }
5481 }
5482 
5483 size_t Process::GetThreadStatus(Stream &strm,
5484                                 bool only_threads_with_stop_reason,
5485                                 uint32_t start_frame, uint32_t num_frames,
5486                                 uint32_t num_frames_with_source,
5487                                 bool stop_format) {
5488   size_t num_thread_infos_dumped = 0;
5489 
5490   // You can't hold the thread list lock while calling Thread::GetStatus.  That
5491   // very well might run code (e.g. if we need it to get return values or
5492   // arguments.)  For that to work the process has to be able to acquire it.
5493   // So instead copy the thread ID's, and look them up one by one:
5494 
5495   uint32_t num_threads;
5496   std::vector<lldb::tid_t> thread_id_array;
5497   // Scope for thread list locker;
5498   {
5499     std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5500     ThreadList &curr_thread_list = GetThreadList();
5501     num_threads = curr_thread_list.GetSize();
5502     uint32_t idx;
5503     thread_id_array.resize(num_threads);
5504     for (idx = 0; idx < num_threads; ++idx)
5505       thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5506   }
5507 
5508   for (uint32_t i = 0; i < num_threads; i++) {
5509     ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5510     if (thread_sp) {
5511       if (only_threads_with_stop_reason) {
5512         StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5513         if (!stop_info_sp || !stop_info_sp->IsValid())
5514           continue;
5515       }
5516       thread_sp->GetStatus(strm, start_frame, num_frames,
5517                            num_frames_with_source,
5518                            stop_format);
5519       ++num_thread_infos_dumped;
5520     } else {
5521       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5522       if (log)
5523         log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5524                     " vanished while running Thread::GetStatus.");
5525     }
5526   }
5527   return num_thread_infos_dumped;
5528 }
5529 
5530 void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5531   m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5532 }
5533 
5534 bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5535   return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5536                                            region.GetByteSize());
5537 }
5538 
5539 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5540                                  void *baton) {
5541   m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5542 }
5543 
5544 bool Process::RunPreResumeActions() {
5545   bool result = true;
5546   while (!m_pre_resume_actions.empty()) {
5547     struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5548     m_pre_resume_actions.pop_back();
5549     bool this_result = action.callback(action.baton);
5550     if (result)
5551       result = this_result;
5552   }
5553   return result;
5554 }
5555 
5556 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5557 
5558 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5559 {
5560     PreResumeCallbackAndBaton element(callback, baton);
5561     auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5562     if (found_iter != m_pre_resume_actions.end())
5563     {
5564         m_pre_resume_actions.erase(found_iter);
5565     }
5566 }
5567 
5568 ProcessRunLock &Process::GetRunLock() {
5569   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5570     return m_private_run_lock;
5571   else
5572     return m_public_run_lock;
5573 }
5574 
5575 void Process::Flush() {
5576   m_thread_list.Flush();
5577   m_extended_thread_list.Flush();
5578   m_extended_thread_stop_id = 0;
5579   m_queue_list.Clear();
5580   m_queue_list_stop_id = 0;
5581 }
5582 
5583 void Process::DidExec() {
5584   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5585   if (log)
5586     log->Printf("Process::%s()", __FUNCTION__);
5587 
5588   Target &target = GetTarget();
5589   target.CleanupProcess();
5590   target.ClearModules(false);
5591   m_dynamic_checkers_up.reset();
5592   m_abi_sp.reset();
5593   m_system_runtime_up.reset();
5594   m_os_up.reset();
5595   m_dyld_up.reset();
5596   m_jit_loaders_up.reset();
5597   m_image_tokens.clear();
5598   m_allocated_memory_cache.Clear();
5599   m_language_runtimes.clear();
5600   m_instrumentation_runtimes.clear();
5601   m_thread_list.DiscardThreadPlans();
5602   m_memory_cache.Clear(true);
5603   DoDidExec();
5604   CompleteAttach();
5605   // Flush the process (threads and all stack frames) after running
5606   // CompleteAttach() in case the dynamic loader loaded things in new
5607   // locations.
5608   Flush();
5609 
5610   // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5611   // let the target know so it can do any cleanup it needs to.
5612   target.DidExec();
5613 }
5614 
5615 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
5616   if (address == nullptr) {
5617     error.SetErrorString("Invalid address argument");
5618     return LLDB_INVALID_ADDRESS;
5619   }
5620 
5621   addr_t function_addr = LLDB_INVALID_ADDRESS;
5622 
5623   addr_t addr = address->GetLoadAddress(&GetTarget());
5624   std::map<addr_t, addr_t>::const_iterator iter =
5625       m_resolved_indirect_addresses.find(addr);
5626   if (iter != m_resolved_indirect_addresses.end()) {
5627     function_addr = (*iter).second;
5628   } else {
5629     if (!InferiorCall(this, address, function_addr)) {
5630       Symbol *symbol = address->CalculateSymbolContextSymbol();
5631       error.SetErrorStringWithFormat(
5632           "Unable to call resolver for indirect function %s",
5633           symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5634       function_addr = LLDB_INVALID_ADDRESS;
5635     } else {
5636       m_resolved_indirect_addresses.insert(
5637           std::pair<addr_t, addr_t>(addr, function_addr));
5638     }
5639   }
5640   return function_addr;
5641 }
5642 
5643 void Process::ModulesDidLoad(ModuleList &module_list) {
5644   SystemRuntime *sys_runtime = GetSystemRuntime();
5645   if (sys_runtime) {
5646     sys_runtime->ModulesDidLoad(module_list);
5647   }
5648 
5649   GetJITLoaders().ModulesDidLoad(module_list);
5650 
5651   // Give runtimes a chance to be created.
5652   InstrumentationRuntime::ModulesDidLoad(module_list, this,
5653                                          m_instrumentation_runtimes);
5654 
5655   // Tell runtimes about new modules.
5656   for (auto pos = m_instrumentation_runtimes.begin();
5657        pos != m_instrumentation_runtimes.end(); ++pos) {
5658     InstrumentationRuntimeSP runtime = pos->second;
5659     runtime->ModulesDidLoad(module_list);
5660   }
5661 
5662   // Let any language runtimes we have already created know about the modules
5663   // that loaded.
5664 
5665   // Iterate over a copy of this language runtime list in case the language
5666   // runtime ModulesDidLoad somehow causes the language runtime to be
5667   // unloaded.
5668   LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5669   for (const auto &pair : language_runtimes) {
5670     // We must check language_runtime_sp to make sure it is not nullptr as we
5671     // might cache the fact that we didn't have a language runtime for a
5672     // language.
5673     LanguageRuntimeSP language_runtime_sp = pair.second;
5674     if (language_runtime_sp)
5675       language_runtime_sp->ModulesDidLoad(module_list);
5676   }
5677 
5678   // If we don't have an operating system plug-in, try to load one since
5679   // loading shared libraries might cause a new one to try and load
5680   if (!m_os_up)
5681     LoadOperatingSystemPlugin(false);
5682 
5683   // Give structured-data plugins a chance to see the modified modules.
5684   for (auto pair : m_structured_data_plugin_map) {
5685     if (pair.second)
5686       pair.second->ModulesDidLoad(*this, module_list);
5687   }
5688 }
5689 
5690 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5691                            const char *fmt, ...) {
5692   bool print_warning = true;
5693 
5694   StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5695   if (!stream_sp)
5696     return;
5697   if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5698     return;
5699   }
5700 
5701   if (repeat_key != nullptr) {
5702     WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5703     if (it == m_warnings_issued.end()) {
5704       m_warnings_issued[warning_type] = WarningsPointerSet();
5705       m_warnings_issued[warning_type].insert(repeat_key);
5706     } else {
5707       if (it->second.find(repeat_key) != it->second.end()) {
5708         print_warning = false;
5709       } else {
5710         it->second.insert(repeat_key);
5711       }
5712     }
5713   }
5714 
5715   if (print_warning) {
5716     va_list args;
5717     va_start(args, fmt);
5718     stream_sp->PrintfVarArg(fmt, args);
5719     va_end(args);
5720   }
5721 }
5722 
5723 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5724   if (GetWarningsOptimization() && sc.module_sp &&
5725       !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5726       sc.function->GetIsOptimized()) {
5727     PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5728                  "%s was compiled with optimization - stepping may behave "
5729                  "oddly; variables may not be available.\n",
5730                  sc.module_sp->GetFileSpec().GetFilename().GetCString());
5731   }
5732 }
5733 
5734 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5735   info.Clear();
5736 
5737   PlatformSP platform_sp = GetTarget().GetPlatform();
5738   if (!platform_sp)
5739     return false;
5740 
5741   return platform_sp->GetProcessInfo(GetID(), info);
5742 }
5743 
5744 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5745   ThreadCollectionSP threads;
5746 
5747   const MemoryHistorySP &memory_history =
5748       MemoryHistory::FindPlugin(shared_from_this());
5749 
5750   if (!memory_history) {
5751     return threads;
5752   }
5753 
5754   threads = std::make_shared<ThreadCollection>(
5755       memory_history->GetHistoryThreads(addr));
5756 
5757   return threads;
5758 }
5759 
5760 InstrumentationRuntimeSP
5761 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5762   InstrumentationRuntimeCollection::iterator pos;
5763   pos = m_instrumentation_runtimes.find(type);
5764   if (pos == m_instrumentation_runtimes.end()) {
5765     return InstrumentationRuntimeSP();
5766   } else
5767     return (*pos).second;
5768 }
5769 
5770 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5771                             const ArchSpec &arch, ModuleSpec &module_spec) {
5772   module_spec.Clear();
5773   return false;
5774 }
5775 
5776 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5777   m_image_tokens.push_back(image_ptr);
5778   return m_image_tokens.size() - 1;
5779 }
5780 
5781 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5782   if (token < m_image_tokens.size())
5783     return m_image_tokens[token];
5784   return LLDB_INVALID_IMAGE_TOKEN;
5785 }
5786 
5787 void Process::ResetImageToken(size_t token) {
5788   if (token < m_image_tokens.size())
5789     m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
5790 }
5791 
5792 Address
5793 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5794                                                AddressRange range_bounds) {
5795   Target &target = GetTarget();
5796   DisassemblerSP disassembler_sp;
5797   InstructionList *insn_list = nullptr;
5798 
5799   Address retval = default_stop_addr;
5800 
5801   if (!target.GetUseFastStepping())
5802     return retval;
5803   if (!default_stop_addr.IsValid())
5804     return retval;
5805 
5806   ExecutionContext exe_ctx(this);
5807   const char *plugin_name = nullptr;
5808   const char *flavor = nullptr;
5809   const bool prefer_file_cache = true;
5810   disassembler_sp = Disassembler::DisassembleRange(
5811       target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5812       prefer_file_cache);
5813   if (disassembler_sp)
5814     insn_list = &disassembler_sp->GetInstructionList();
5815 
5816   if (insn_list == nullptr) {
5817     return retval;
5818   }
5819 
5820   size_t insn_offset =
5821       insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5822   if (insn_offset == UINT32_MAX) {
5823     return retval;
5824   }
5825 
5826   uint32_t branch_index =
5827       insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
5828   if (branch_index == UINT32_MAX) {
5829     return retval;
5830   }
5831 
5832   if (branch_index > insn_offset) {
5833     Address next_branch_insn_address =
5834         insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5835     if (next_branch_insn_address.IsValid() &&
5836         range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5837       retval = next_branch_insn_address;
5838     }
5839   }
5840 
5841   return retval;
5842 }
5843 
5844 Status
5845 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
5846 
5847   Status error;
5848 
5849   lldb::addr_t range_end = 0;
5850 
5851   region_list.clear();
5852   do {
5853     lldb_private::MemoryRegionInfo region_info;
5854     error = GetMemoryRegionInfo(range_end, region_info);
5855     // GetMemoryRegionInfo should only return an error if it is unimplemented.
5856     if (error.Fail()) {
5857       region_list.clear();
5858       break;
5859     }
5860 
5861     range_end = region_info.GetRange().GetRangeEnd();
5862     if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5863       region_list.push_back(std::move(region_info));
5864     }
5865   } while (range_end != LLDB_INVALID_ADDRESS);
5866 
5867   return error;
5868 }
5869 
5870 Status
5871 Process::ConfigureStructuredData(ConstString type_name,
5872                                  const StructuredData::ObjectSP &config_sp) {
5873   // If you get this, the Process-derived class needs to implement a method to
5874   // enable an already-reported asynchronous structured data feature. See
5875   // ProcessGDBRemote for an example implementation over gdb-remote.
5876   return Status("unimplemented");
5877 }
5878 
5879 void Process::MapSupportedStructuredDataPlugins(
5880     const StructuredData::Array &supported_type_names) {
5881   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5882 
5883   // Bail out early if there are no type names to map.
5884   if (supported_type_names.GetSize() == 0) {
5885     if (log)
5886       log->Printf("Process::%s(): no structured data types supported",
5887                   __FUNCTION__);
5888     return;
5889   }
5890 
5891   // Convert StructuredData type names to ConstString instances.
5892   std::set<ConstString> const_type_names;
5893 
5894   if (log)
5895     log->Printf("Process::%s(): the process supports the following async "
5896                 "structured data types:",
5897                 __FUNCTION__);
5898 
5899   supported_type_names.ForEach(
5900       [&const_type_names, &log](StructuredData::Object *object) {
5901         if (!object) {
5902           // Invalid - shouldn't be null objects in the array.
5903           return false;
5904         }
5905 
5906         auto type_name = object->GetAsString();
5907         if (!type_name) {
5908           // Invalid format - all type names should be strings.
5909           return false;
5910         }
5911 
5912         const_type_names.insert(ConstString(type_name->GetValue()));
5913         LLDB_LOG(log, "- {0}", type_name->GetValue());
5914         return true;
5915       });
5916 
5917   // For each StructuredDataPlugin, if the plugin handles any of the types in
5918   // the supported_type_names, map that type name to that plugin. Stop when
5919   // we've consumed all the type names.
5920   // FIXME: should we return an error if there are type names nobody
5921   // supports?
5922   for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5923     auto create_instance =
5924            PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5925                plugin_index);
5926     if (!create_instance)
5927       break;
5928 
5929     // Create the plugin.
5930     StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5931     if (!plugin_sp) {
5932       // This plugin doesn't think it can work with the process. Move on to the
5933       // next.
5934       continue;
5935     }
5936 
5937     // For any of the remaining type names, map any that this plugin supports.
5938     std::vector<ConstString> names_to_remove;
5939     for (auto &type_name : const_type_names) {
5940       if (plugin_sp->SupportsStructuredDataType(type_name)) {
5941         m_structured_data_plugin_map.insert(
5942             std::make_pair(type_name, plugin_sp));
5943         names_to_remove.push_back(type_name);
5944         if (log)
5945           log->Printf("Process::%s(): using plugin %s for type name "
5946                       "%s",
5947                       __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5948                       type_name.GetCString());
5949       }
5950     }
5951 
5952     // Remove the type names that were consumed by this plugin.
5953     for (auto &type_name : names_to_remove)
5954       const_type_names.erase(type_name);
5955   }
5956 }
5957 
5958 bool Process::RouteAsyncStructuredData(
5959     const StructuredData::ObjectSP object_sp) {
5960   // Nothing to do if there's no data.
5961   if (!object_sp)
5962     return false;
5963 
5964   // The contract is this must be a dictionary, so we can look up the routing
5965   // key via the top-level 'type' string value within the dictionary.
5966   StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5967   if (!dictionary)
5968     return false;
5969 
5970   // Grab the async structured type name (i.e. the feature/plugin name).
5971   ConstString type_name;
5972   if (!dictionary->GetValueForKeyAsString("type", type_name))
5973     return false;
5974 
5975   // Check if there's a plugin registered for this type name.
5976   auto find_it = m_structured_data_plugin_map.find(type_name);
5977   if (find_it == m_structured_data_plugin_map.end()) {
5978     // We don't have a mapping for this structured data type.
5979     return false;
5980   }
5981 
5982   // Route the structured data to the plugin.
5983   find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5984   return true;
5985 }
5986 
5987 Status Process::UpdateAutomaticSignalFiltering() {
5988   // Default implementation does nothign.
5989   // No automatic signal filtering to speak of.
5990   return Status();
5991 }
5992 
5993 UtilityFunction *Process::GetLoadImageUtilityFunction(
5994     Platform *platform,
5995     llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
5996   if (platform != GetTarget().GetPlatform().get())
5997     return nullptr;
5998   std::call_once(m_dlopen_utility_func_flag_once,
5999                  [&] { m_dlopen_utility_func_up = factory(); });
6000   return m_dlopen_utility_func_up.get();
6001 }
6002