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