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