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