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