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