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