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