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