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