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