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