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