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