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