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