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