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