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