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