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