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