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