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