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