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