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