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