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