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