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