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