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