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, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
1634                 error = result_valobj_sp->GetError();
1635                 if (error.Success())
1636                 {
1637                     Scalar scalar;
1638                     if (result_valobj_sp->ResolveValue (scalar))
1639                     {
1640                         addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1641                         if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1642                         {
1643                             uint32_t image_token = m_image_tokens.size();
1644                             m_image_tokens.push_back (image_ptr);
1645                             return image_token;
1646                         }
1647                     }
1648                 }
1649             }
1650         }
1651     }
1652     if (!error.AsCString())
1653         error.SetErrorStringWithFormat("unable to load '%s'", path);
1654     return LLDB_INVALID_IMAGE_TOKEN;
1655 }
1656 
1657 //----------------------------------------------------------------------
1658 // UnloadImage
1659 //
1660 // This function provides a default implementation that works for most
1661 // unix variants. Any Process subclasses that need to do shared library
1662 // loading differently should override LoadImage and UnloadImage and
1663 // do what is needed.
1664 //----------------------------------------------------------------------
1665 Error
1666 Process::UnloadImage (uint32_t image_token)
1667 {
1668     Error error;
1669     if (image_token < m_image_tokens.size())
1670     {
1671         const addr_t image_addr = m_image_tokens[image_token];
1672         if (image_addr == LLDB_INVALID_ADDRESS)
1673         {
1674             error.SetErrorString("image already unloaded");
1675         }
1676         else
1677         {
1678             DynamicLoader *loader = GetDynamicLoader();
1679             if (loader)
1680                 error = loader->CanLoadImage();
1681 
1682             if (error.Success())
1683             {
1684                 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1685 
1686                 if (thread_sp)
1687                 {
1688                     StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1689 
1690                     if (frame_sp)
1691                     {
1692                         ExecutionContext exe_ctx;
1693                         frame_sp->CalculateExecutionContext (exe_ctx);
1694                         bool unwind_on_error = true;
1695                         StreamString expr;
1696                         expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1697                         const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1698                         lldb::ValueObjectSP result_valobj_sp;
1699                         ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
1700                         if (result_valobj_sp->GetError().Success())
1701                         {
1702                             Scalar scalar;
1703                             if (result_valobj_sp->ResolveValue (scalar))
1704                             {
1705                                 if (scalar.UInt(1))
1706                                 {
1707                                     error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1708                                 }
1709                                 else
1710                                 {
1711                                     m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1712                                 }
1713                             }
1714                         }
1715                         else
1716                         {
1717                             error = result_valobj_sp->GetError();
1718                         }
1719                     }
1720                 }
1721             }
1722         }
1723     }
1724     else
1725     {
1726         error.SetErrorString("invalid image token");
1727     }
1728     return error;
1729 }
1730 
1731 const lldb::ABISP &
1732 Process::GetABI()
1733 {
1734     if (!m_abi_sp)
1735         m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1736     return m_abi_sp;
1737 }
1738 
1739 LanguageRuntime *
1740 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
1741 {
1742     LanguageRuntimeCollection::iterator pos;
1743     pos = m_language_runtimes.find (language);
1744     if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
1745     {
1746         lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
1747 
1748         m_language_runtimes[language] = runtime_sp;
1749         return runtime_sp.get();
1750     }
1751     else
1752         return (*pos).second.get();
1753 }
1754 
1755 CPPLanguageRuntime *
1756 Process::GetCPPLanguageRuntime (bool retry_if_null)
1757 {
1758     LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1759     if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1760         return static_cast<CPPLanguageRuntime *> (runtime);
1761     return NULL;
1762 }
1763 
1764 ObjCLanguageRuntime *
1765 Process::GetObjCLanguageRuntime (bool retry_if_null)
1766 {
1767     LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1768     if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1769         return static_cast<ObjCLanguageRuntime *> (runtime);
1770     return NULL;
1771 }
1772 
1773 bool
1774 Process::IsPossibleDynamicValue (ValueObject& in_value)
1775 {
1776     if (in_value.IsDynamic())
1777         return false;
1778     LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1779 
1780     if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1781     {
1782         LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1783         return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1784     }
1785 
1786     LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1787     if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1788         return true;
1789 
1790     LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1791     return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1792 }
1793 
1794 BreakpointSiteList &
1795 Process::GetBreakpointSiteList()
1796 {
1797     return m_breakpoint_site_list;
1798 }
1799 
1800 const BreakpointSiteList &
1801 Process::GetBreakpointSiteList() const
1802 {
1803     return m_breakpoint_site_list;
1804 }
1805 
1806 
1807 void
1808 Process::DisableAllBreakpointSites ()
1809 {
1810     m_breakpoint_site_list.SetEnabledForAll (false);
1811     size_t num_sites = m_breakpoint_site_list.GetSize();
1812     for (size_t i = 0; i < num_sites; i++)
1813     {
1814         DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1815     }
1816 }
1817 
1818 Error
1819 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1820 {
1821     Error error (DisableBreakpointSiteByID (break_id));
1822 
1823     if (error.Success())
1824         m_breakpoint_site_list.Remove(break_id);
1825 
1826     return error;
1827 }
1828 
1829 Error
1830 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1831 {
1832     Error error;
1833     BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1834     if (bp_site_sp)
1835     {
1836         if (bp_site_sp->IsEnabled())
1837             error = DisableBreakpoint (bp_site_sp.get());
1838     }
1839     else
1840     {
1841         error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
1842     }
1843 
1844     return error;
1845 }
1846 
1847 Error
1848 Process::EnableBreakpointSiteByID (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 = EnableBreakpoint (bp_site_sp.get());
1856     }
1857     else
1858     {
1859         error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
1860     }
1861     return error;
1862 }
1863 
1864 lldb::break_id_t
1865 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
1866 {
1867     const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1868     if (load_addr != LLDB_INVALID_ADDRESS)
1869     {
1870         BreakpointSiteSP bp_site_sp;
1871 
1872         // Look up this breakpoint site.  If it exists, then add this new owner, otherwise
1873         // create a new breakpoint site and add it.
1874 
1875         bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1876 
1877         if (bp_site_sp)
1878         {
1879             bp_site_sp->AddOwner (owner);
1880             owner->SetBreakpointSite (bp_site_sp);
1881             return bp_site_sp->GetID();
1882         }
1883         else
1884         {
1885             bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1886             if (bp_site_sp)
1887             {
1888                 if (EnableBreakpoint (bp_site_sp.get()).Success())
1889                 {
1890                     owner->SetBreakpointSite (bp_site_sp);
1891                     return m_breakpoint_site_list.Add (bp_site_sp);
1892                 }
1893             }
1894         }
1895     }
1896     // We failed to enable the breakpoint
1897     return LLDB_INVALID_BREAK_ID;
1898 
1899 }
1900 
1901 void
1902 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1903 {
1904     uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1905     if (num_owners == 0)
1906     {
1907         DisableBreakpoint(bp_site_sp.get());
1908         m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1909     }
1910 }
1911 
1912 
1913 size_t
1914 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1915 {
1916     size_t bytes_removed = 0;
1917     addr_t intersect_addr;
1918     size_t intersect_size;
1919     size_t opcode_offset;
1920     size_t idx;
1921     BreakpointSiteSP bp_sp;
1922     BreakpointSiteList bp_sites_in_range;
1923 
1924     if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
1925     {
1926         for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
1927         {
1928             if (bp_sp->GetType() == BreakpointSite::eSoftware)
1929             {
1930                 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1931                 {
1932                     assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1933                     assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1934                     assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
1935                     size_t buf_offset = intersect_addr - bp_addr;
1936                     ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1937                 }
1938             }
1939         }
1940     }
1941     return bytes_removed;
1942 }
1943 
1944 
1945 
1946 size_t
1947 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1948 {
1949     PlatformSP platform_sp (m_target.GetPlatform());
1950     if (platform_sp)
1951         return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1952     return 0;
1953 }
1954 
1955 Error
1956 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1957 {
1958     Error error;
1959     assert (bp_site != NULL);
1960     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
1961     const addr_t bp_addr = bp_site->GetLoadAddress();
1962     if (log)
1963         log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1964     if (bp_site->IsEnabled())
1965     {
1966         if (log)
1967             log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1968         return error;
1969     }
1970 
1971     if (bp_addr == LLDB_INVALID_ADDRESS)
1972     {
1973         error.SetErrorString("BreakpointSite contains an invalid load address.");
1974         return error;
1975     }
1976     // Ask the lldb::Process subclass to fill in the correct software breakpoint
1977     // trap for the breakpoint site
1978     const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1979 
1980     if (bp_opcode_size == 0)
1981     {
1982         error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
1983     }
1984     else
1985     {
1986         const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1987 
1988         if (bp_opcode_bytes == NULL)
1989         {
1990             error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1991             return error;
1992         }
1993 
1994         // Save the original opcode by reading it
1995         if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1996         {
1997             // Write a software breakpoint in place of the original opcode
1998             if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1999             {
2000                 uint8_t verify_bp_opcode_bytes[64];
2001                 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2002                 {
2003                     if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2004                     {
2005                         bp_site->SetEnabled(true);
2006                         bp_site->SetType (BreakpointSite::eSoftware);
2007                         if (log)
2008                             log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
2009                                          bp_site->GetID(),
2010                                          (uint64_t)bp_addr);
2011                     }
2012                     else
2013                         error.SetErrorString("failed to verify the breakpoint trap in memory.");
2014                 }
2015                 else
2016                     error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2017             }
2018             else
2019                 error.SetErrorString("Unable to write breakpoint trap to memory.");
2020         }
2021         else
2022             error.SetErrorString("Unable to read memory at breakpoint address.");
2023     }
2024     if (log && error.Fail())
2025         log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2026                      bp_site->GetID(),
2027                      (uint64_t)bp_addr,
2028                      error.AsCString());
2029     return error;
2030 }
2031 
2032 Error
2033 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2034 {
2035     Error error;
2036     assert (bp_site != NULL);
2037     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2038     addr_t bp_addr = bp_site->GetLoadAddress();
2039     lldb::user_id_t breakID = bp_site->GetID();
2040     if (log)
2041         log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
2042 
2043     if (bp_site->IsHardware())
2044     {
2045         error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2046     }
2047     else if (bp_site->IsEnabled())
2048     {
2049         const size_t break_op_size = bp_site->GetByteSize();
2050         const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2051         if (break_op_size > 0)
2052         {
2053             // Clear a software breakoint instruction
2054             uint8_t curr_break_op[8];
2055             assert (break_op_size <= sizeof(curr_break_op));
2056             bool break_op_found = false;
2057 
2058             // Read the breakpoint opcode
2059             if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2060             {
2061                 bool verify = false;
2062                 // Make sure we have the a breakpoint opcode exists at this address
2063                 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2064                 {
2065                     break_op_found = true;
2066                     // We found a valid breakpoint opcode at this address, now restore
2067                     // the saved opcode.
2068                     if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2069                     {
2070                         verify = true;
2071                     }
2072                     else
2073                         error.SetErrorString("Memory write failed when restoring original opcode.");
2074                 }
2075                 else
2076                 {
2077                     error.SetErrorString("Original breakpoint trap is no longer in memory.");
2078                     // Set verify to true and so we can check if the original opcode has already been restored
2079                     verify = true;
2080                 }
2081 
2082                 if (verify)
2083                 {
2084                     uint8_t verify_opcode[8];
2085                     assert (break_op_size < sizeof(verify_opcode));
2086                     // Verify that our original opcode made it back to the inferior
2087                     if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2088                     {
2089                         // compare the memory we just read with the original opcode
2090                         if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2091                         {
2092                             // SUCCESS
2093                             bp_site->SetEnabled(false);
2094                             if (log)
2095                                 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2096                             return error;
2097                         }
2098                         else
2099                         {
2100                             if (break_op_found)
2101                                 error.SetErrorString("Failed to restore original opcode.");
2102                         }
2103                     }
2104                     else
2105                         error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2106                 }
2107             }
2108             else
2109                 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2110         }
2111     }
2112     else
2113     {
2114         if (log)
2115             log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2116         return error;
2117     }
2118 
2119     if (log)
2120         log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2121                      bp_site->GetID(),
2122                      (uint64_t)bp_addr,
2123                      error.AsCString());
2124     return error;
2125 
2126 }
2127 
2128 // Uncomment to verify memory caching works after making changes to caching code
2129 //#define VERIFY_MEMORY_READS
2130 
2131 size_t
2132 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2133 {
2134     if (!GetDisableMemoryCache())
2135     {
2136 #if defined (VERIFY_MEMORY_READS)
2137         // Memory caching is enabled, with debug verification
2138 
2139         if (buf && size)
2140         {
2141             // Uncomment the line below to make sure memory caching is working.
2142             // I ran this through the test suite and got no assertions, so I am
2143             // pretty confident this is working well. If any changes are made to
2144             // memory caching, uncomment the line below and test your changes!
2145 
2146             // Verify all memory reads by using the cache first, then redundantly
2147             // reading the same memory from the inferior and comparing to make sure
2148             // everything is exactly the same.
2149             std::string verify_buf (size, '\0');
2150             assert (verify_buf.size() == size);
2151             const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2152             Error verify_error;
2153             const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2154             assert (cache_bytes_read == verify_bytes_read);
2155             assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2156             assert (verify_error.Success() == error.Success());
2157             return cache_bytes_read;
2158         }
2159         return 0;
2160 #else // !defined(VERIFY_MEMORY_READS)
2161         // Memory caching is enabled, without debug verification
2162 
2163         return m_memory_cache.Read (addr, buf, size, error);
2164 #endif // defined (VERIFY_MEMORY_READS)
2165     }
2166     else
2167     {
2168         // Memory caching is disabled
2169 
2170         return ReadMemoryFromInferior (addr, buf, size, error);
2171     }
2172 }
2173 
2174 size_t
2175 Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2176 {
2177     char buf[256];
2178     out_str.clear();
2179     addr_t curr_addr = addr;
2180     while (1)
2181     {
2182         size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2183         if (length == 0)
2184             break;
2185         out_str.append(buf, length);
2186         // If we got "length - 1" bytes, we didn't get the whole C string, we
2187         // need to read some more characters
2188         if (length == sizeof(buf) - 1)
2189             curr_addr += length;
2190         else
2191             break;
2192     }
2193     return out_str.size();
2194 }
2195 
2196 
2197 size_t
2198 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
2199 {
2200     size_t total_cstr_len = 0;
2201     if (dst && dst_max_len)
2202     {
2203         result_error.Clear();
2204         // NULL out everything just to be safe
2205         memset (dst, 0, dst_max_len);
2206         Error error;
2207         addr_t curr_addr = addr;
2208         const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2209         size_t bytes_left = dst_max_len - 1;
2210         char *curr_dst = dst;
2211 
2212         while (bytes_left > 0)
2213         {
2214             addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2215             addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2216             size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2217 
2218             if (bytes_read == 0)
2219             {
2220                 result_error = error;
2221                 dst[total_cstr_len] = '\0';
2222                 break;
2223             }
2224             const size_t len = strlen(curr_dst);
2225 
2226             total_cstr_len += len;
2227 
2228             if (len < bytes_to_read)
2229                 break;
2230 
2231             curr_dst += bytes_read;
2232             curr_addr += bytes_read;
2233             bytes_left -= bytes_read;
2234         }
2235     }
2236     else
2237     {
2238         if (dst == NULL)
2239             result_error.SetErrorString("invalid arguments");
2240         else
2241             result_error.Clear();
2242     }
2243     return total_cstr_len;
2244 }
2245 
2246 size_t
2247 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2248 {
2249     if (buf == NULL || size == 0)
2250         return 0;
2251 
2252     size_t bytes_read = 0;
2253     uint8_t *bytes = (uint8_t *)buf;
2254 
2255     while (bytes_read < size)
2256     {
2257         const size_t curr_size = size - bytes_read;
2258         const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2259                                                      bytes + bytes_read,
2260                                                      curr_size,
2261                                                      error);
2262         bytes_read += curr_bytes_read;
2263         if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2264             break;
2265     }
2266 
2267     // Replace any software breakpoint opcodes that fall into this range back
2268     // into "buf" before we return
2269     if (bytes_read > 0)
2270         RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2271     return bytes_read;
2272 }
2273 
2274 uint64_t
2275 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
2276 {
2277     Scalar scalar;
2278     if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2279         return scalar.ULongLong(fail_value);
2280     return fail_value;
2281 }
2282 
2283 addr_t
2284 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2285 {
2286     Scalar scalar;
2287     if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2288         return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2289     return LLDB_INVALID_ADDRESS;
2290 }
2291 
2292 
2293 bool
2294 Process::WritePointerToMemory (lldb::addr_t vm_addr,
2295                                lldb::addr_t ptr_value,
2296                                Error &error)
2297 {
2298     Scalar scalar;
2299     const uint32_t addr_byte_size = GetAddressByteSize();
2300     if (addr_byte_size <= 4)
2301         scalar = (uint32_t)ptr_value;
2302     else
2303         scalar = ptr_value;
2304     return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
2305 }
2306 
2307 size_t
2308 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2309 {
2310     size_t bytes_written = 0;
2311     const uint8_t *bytes = (const uint8_t *)buf;
2312 
2313     while (bytes_written < size)
2314     {
2315         const size_t curr_size = size - bytes_written;
2316         const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2317                                                          bytes + bytes_written,
2318                                                          curr_size,
2319                                                          error);
2320         bytes_written += curr_bytes_written;
2321         if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2322             break;
2323     }
2324     return bytes_written;
2325 }
2326 
2327 size_t
2328 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2329 {
2330 #if defined (ENABLE_MEMORY_CACHING)
2331     m_memory_cache.Flush (addr, size);
2332 #endif
2333 
2334     if (buf == NULL || size == 0)
2335         return 0;
2336 
2337     m_mod_id.BumpMemoryID();
2338 
2339     // We need to write any data that would go where any current software traps
2340     // (enabled software breakpoints) any software traps (breakpoints) that we
2341     // may have placed in our tasks memory.
2342 
2343     BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2344     BreakpointSiteList::collection::const_iterator end =  m_breakpoint_site_list.GetMap()->end();
2345 
2346     if (iter == end || iter->second->GetLoadAddress() > addr + size)
2347         return WriteMemoryPrivate (addr, buf, size, error);
2348 
2349     BreakpointSiteList::collection::const_iterator pos;
2350     size_t bytes_written = 0;
2351     addr_t intersect_addr = 0;
2352     size_t intersect_size = 0;
2353     size_t opcode_offset = 0;
2354     const uint8_t *ubuf = (const uint8_t *)buf;
2355 
2356     for (pos = iter; pos != end; ++pos)
2357     {
2358         BreakpointSiteSP bp;
2359         bp = pos->second;
2360 
2361         assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2362         assert(addr <= intersect_addr && intersect_addr < addr + size);
2363         assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2364         assert(opcode_offset + intersect_size <= bp->GetByteSize());
2365 
2366         // Check for bytes before this breakpoint
2367         const addr_t curr_addr = addr + bytes_written;
2368         if (intersect_addr > curr_addr)
2369         {
2370             // There are some bytes before this breakpoint that we need to
2371             // just write to memory
2372             size_t curr_size = intersect_addr - curr_addr;
2373             size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2374                                                             ubuf + bytes_written,
2375                                                             curr_size,
2376                                                             error);
2377             bytes_written += curr_bytes_written;
2378             if (curr_bytes_written != curr_size)
2379             {
2380                 // We weren't able to write all of the requested bytes, we
2381                 // are done looping and will return the number of bytes that
2382                 // we have written so far.
2383                 break;
2384             }
2385         }
2386 
2387         // Now write any bytes that would cover up any software breakpoints
2388         // directly into the breakpoint opcode buffer
2389         ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2390         bytes_written += intersect_size;
2391     }
2392 
2393     // Write any remaining bytes after the last breakpoint if we have any left
2394     if (bytes_written < size)
2395         bytes_written += WriteMemoryPrivate (addr + bytes_written,
2396                                              ubuf + bytes_written,
2397                                              size - bytes_written,
2398                                              error);
2399 
2400     return bytes_written;
2401 }
2402 
2403 size_t
2404 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2405 {
2406     if (byte_size == UINT32_MAX)
2407         byte_size = scalar.GetByteSize();
2408     if (byte_size > 0)
2409     {
2410         uint8_t buf[32];
2411         const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2412         if (mem_size > 0)
2413             return WriteMemory(addr, buf, mem_size, error);
2414         else
2415             error.SetErrorString ("failed to get scalar as memory data");
2416     }
2417     else
2418     {
2419         error.SetErrorString ("invalid scalar value");
2420     }
2421     return 0;
2422 }
2423 
2424 size_t
2425 Process::ReadScalarIntegerFromMemory (addr_t addr,
2426                                       uint32_t byte_size,
2427                                       bool is_signed,
2428                                       Scalar &scalar,
2429                                       Error &error)
2430 {
2431     uint64_t uval;
2432 
2433     if (byte_size <= sizeof(uval))
2434     {
2435         size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2436         if (bytes_read == byte_size)
2437         {
2438             DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2439             uint32_t offset = 0;
2440             if (byte_size <= 4)
2441                 scalar = data.GetMaxU32 (&offset, byte_size);
2442             else
2443                 scalar = data.GetMaxU64 (&offset, byte_size);
2444 
2445             if (is_signed)
2446                 scalar.SignExtend(byte_size * 8);
2447             return bytes_read;
2448         }
2449     }
2450     else
2451     {
2452         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2453     }
2454     return 0;
2455 }
2456 
2457 #define USE_ALLOCATE_MEMORY_CACHE 1
2458 addr_t
2459 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2460 {
2461     if (GetPrivateState() != eStateStopped)
2462         return LLDB_INVALID_ADDRESS;
2463 
2464 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2465     return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2466 #else
2467     addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2468     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2469     if (log)
2470         log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
2471                     size,
2472                     GetPermissionsAsCString (permissions),
2473                     (uint64_t)allocated_addr,
2474                     m_mod_id.GetStopID(),
2475                     m_mod_id.GetMemoryID());
2476     return allocated_addr;
2477 #endif
2478 }
2479 
2480 bool
2481 Process::CanJIT ()
2482 {
2483     if (m_can_jit == eCanJITDontKnow)
2484     {
2485         Error err;
2486 
2487         uint64_t allocated_memory = AllocateMemory(8,
2488                                                    ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2489                                                    err);
2490 
2491         if (err.Success())
2492             m_can_jit = eCanJITYes;
2493         else
2494             m_can_jit = eCanJITNo;
2495 
2496         DeallocateMemory (allocated_memory);
2497     }
2498 
2499     return m_can_jit == eCanJITYes;
2500 }
2501 
2502 void
2503 Process::SetCanJIT (bool can_jit)
2504 {
2505     m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2506 }
2507 
2508 Error
2509 Process::DeallocateMemory (addr_t ptr)
2510 {
2511     Error error;
2512 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2513     if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2514     {
2515         error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2516     }
2517 #else
2518     error = DoDeallocateMemory (ptr);
2519 
2520     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2521     if (log)
2522         log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
2523                     ptr,
2524                     error.AsCString("SUCCESS"),
2525                     m_mod_id.GetStopID(),
2526                     m_mod_id.GetMemoryID());
2527 #endif
2528     return error;
2529 }
2530 
2531 ModuleSP
2532 Process::ReadModuleFromMemory (const FileSpec& file_spec,
2533                                lldb::addr_t header_addr,
2534                                bool add_image_to_target,
2535                                bool load_sections_in_target)
2536 {
2537     ModuleSP module_sp (new Module (file_spec, ArchSpec()));
2538     if (module_sp)
2539     {
2540         Error error;
2541         ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2542         if (objfile)
2543         {
2544             if (add_image_to_target)
2545             {
2546                 m_target.GetImages().Append(module_sp);
2547                 if (load_sections_in_target)
2548                 {
2549                     bool changed = false;
2550                     module_sp->SetLoadAddress (m_target, 0, changed);
2551                 }
2552             }
2553             return module_sp;
2554         }
2555     }
2556     return ModuleSP();
2557 }
2558 
2559 Error
2560 Process::EnableWatchpoint (Watchpoint *watchpoint)
2561 {
2562     Error error;
2563     error.SetErrorString("watchpoints are not supported");
2564     return error;
2565 }
2566 
2567 Error
2568 Process::DisableWatchpoint (Watchpoint *watchpoint)
2569 {
2570     Error error;
2571     error.SetErrorString("watchpoints are not supported");
2572     return error;
2573 }
2574 
2575 StateType
2576 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2577 {
2578     StateType state;
2579     // Now wait for the process to launch and return control to us, and then
2580     // call DidLaunch:
2581     while (1)
2582     {
2583         event_sp.reset();
2584         state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2585 
2586         if (StateIsStoppedState(state, false))
2587             break;
2588 
2589         // If state is invalid, then we timed out
2590         if (state == eStateInvalid)
2591             break;
2592 
2593         if (event_sp)
2594             HandlePrivateEvent (event_sp);
2595     }
2596     return state;
2597 }
2598 
2599 Error
2600 Process::Launch (const ProcessLaunchInfo &launch_info)
2601 {
2602     Error error;
2603     m_abi_sp.reset();
2604     m_dyld_ap.reset();
2605     m_os_ap.reset();
2606     m_process_input_reader.reset();
2607 
2608     Module *exe_module = m_target.GetExecutableModulePointer();
2609     if (exe_module)
2610     {
2611         char local_exec_file_path[PATH_MAX];
2612         char platform_exec_file_path[PATH_MAX];
2613         exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2614         exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
2615         if (exe_module->GetFileSpec().Exists())
2616         {
2617             if (PrivateStateThreadIsValid ())
2618                 PausePrivateStateThread ();
2619 
2620             error = WillLaunch (exe_module);
2621             if (error.Success())
2622             {
2623                 SetPublicState (eStateLaunching);
2624                 m_should_detach = false;
2625 
2626                 if (m_run_lock.WriteTryLock())
2627                 {
2628                     // Now launch using these arguments.
2629                     error = DoLaunch (exe_module, launch_info);
2630                 }
2631                 else
2632                 {
2633                     // This shouldn't happen
2634                     error.SetErrorString("failed to acquire process run lock");
2635                 }
2636 
2637                 if (error.Fail())
2638                 {
2639                     if (GetID() != LLDB_INVALID_PROCESS_ID)
2640                     {
2641                         SetID (LLDB_INVALID_PROCESS_ID);
2642                         const char *error_string = error.AsCString();
2643                         if (error_string == NULL)
2644                             error_string = "launch failed";
2645                         SetExitStatus (-1, error_string);
2646                     }
2647                 }
2648                 else
2649                 {
2650                     EventSP event_sp;
2651                     TimeValue timeout_time;
2652                     timeout_time = TimeValue::Now();
2653                     timeout_time.OffsetWithSeconds(10);
2654                     StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
2655 
2656                     if (state == eStateInvalid || event_sp.get() == NULL)
2657                     {
2658                         // We were able to launch the process, but we failed to
2659                         // catch the initial stop.
2660                         SetExitStatus (0, "failed to catch stop after launch");
2661                         Destroy();
2662                     }
2663                     else if (state == eStateStopped || state == eStateCrashed)
2664                     {
2665 
2666                         DidLaunch ();
2667 
2668                         DynamicLoader *dyld = GetDynamicLoader ();
2669                         if (dyld)
2670                             dyld->DidLaunch();
2671 
2672                         m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2673                         // This delays passing the stopped event to listeners till DidLaunch gets
2674                         // a chance to complete...
2675                         HandlePrivateEvent (event_sp);
2676 
2677                         if (PrivateStateThreadIsValid ())
2678                             ResumePrivateStateThread ();
2679                         else
2680                             StartPrivateStateThread ();
2681                     }
2682                     else if (state == eStateExited)
2683                     {
2684                         // We exited while trying to launch somehow.  Don't call DidLaunch as that's
2685                         // not likely to work, and return an invalid pid.
2686                         HandlePrivateEvent (event_sp);
2687                     }
2688                 }
2689             }
2690         }
2691         else
2692         {
2693             error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
2694         }
2695     }
2696     return error;
2697 }
2698 
2699 
2700 Error
2701 Process::LoadCore ()
2702 {
2703     Error error = DoLoadCore();
2704     if (error.Success())
2705     {
2706         if (PrivateStateThreadIsValid ())
2707             ResumePrivateStateThread ();
2708         else
2709             StartPrivateStateThread ();
2710 
2711         DynamicLoader *dyld = GetDynamicLoader ();
2712         if (dyld)
2713             dyld->DidAttach();
2714 
2715         m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2716         // We successfully loaded a core file, now pretend we stopped so we can
2717         // show all of the threads in the core file and explore the crashed
2718         // state.
2719         SetPrivateState (eStateStopped);
2720 
2721     }
2722     return error;
2723 }
2724 
2725 DynamicLoader *
2726 Process::GetDynamicLoader ()
2727 {
2728     if (m_dyld_ap.get() == NULL)
2729         m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2730     return m_dyld_ap.get();
2731 }
2732 
2733 
2734 Process::NextEventAction::EventActionResult
2735 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
2736 {
2737     StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2738     switch (state)
2739     {
2740         case eStateRunning:
2741         case eStateConnected:
2742             return eEventActionRetry;
2743 
2744         case eStateStopped:
2745         case eStateCrashed:
2746             {
2747                 // During attach, prior to sending the eStateStopped event,
2748                 // lldb_private::Process subclasses must set the new process ID.
2749                 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2750                 if (m_exec_count > 0)
2751                 {
2752                     --m_exec_count;
2753                     m_process->PrivateResume ();
2754                     Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
2755                     return eEventActionRetry;
2756                 }
2757                 else
2758                 {
2759                     m_process->CompleteAttach ();
2760                     return eEventActionSuccess;
2761                 }
2762             }
2763             break;
2764 
2765         default:
2766         case eStateExited:
2767         case eStateInvalid:
2768             break;
2769     }
2770 
2771     m_exit_string.assign ("No valid Process");
2772     return eEventActionExit;
2773 }
2774 
2775 Process::NextEventAction::EventActionResult
2776 Process::AttachCompletionHandler::HandleBeingInterrupted()
2777 {
2778     return eEventActionSuccess;
2779 }
2780 
2781 const char *
2782 Process::AttachCompletionHandler::GetExitString ()
2783 {
2784     return m_exit_string.c_str();
2785 }
2786 
2787 Error
2788 Process::Attach (ProcessAttachInfo &attach_info)
2789 {
2790     m_abi_sp.reset();
2791     m_process_input_reader.reset();
2792     m_dyld_ap.reset();
2793     m_os_ap.reset();
2794 
2795     lldb::pid_t attach_pid = attach_info.GetProcessID();
2796     Error error;
2797     if (attach_pid == LLDB_INVALID_PROCESS_ID)
2798     {
2799         char process_name[PATH_MAX];
2800 
2801         if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
2802         {
2803             const bool wait_for_launch = attach_info.GetWaitForLaunch();
2804 
2805             if (wait_for_launch)
2806             {
2807                 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2808                 if (error.Success())
2809                 {
2810                     if (m_run_lock.WriteTryLock())
2811                     {
2812                         m_should_detach = true;
2813                         SetPublicState (eStateAttaching);
2814                         // Now attach using these arguments.
2815                         error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2816                     }
2817                     else
2818                     {
2819                         // This shouldn't happen
2820                         error.SetErrorString("failed to acquire process run lock");
2821                     }
2822 
2823                     if (error.Fail())
2824                     {
2825                         if (GetID() != LLDB_INVALID_PROCESS_ID)
2826                         {
2827                             SetID (LLDB_INVALID_PROCESS_ID);
2828                             if (error.AsCString() == NULL)
2829                                 error.SetErrorString("attach failed");
2830 
2831                             SetExitStatus(-1, error.AsCString());
2832                         }
2833                     }
2834                     else
2835                     {
2836                         SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2837                         StartPrivateStateThread();
2838                     }
2839                     return error;
2840                 }
2841             }
2842             else
2843             {
2844                 ProcessInstanceInfoList process_infos;
2845                 PlatformSP platform_sp (m_target.GetPlatform ());
2846 
2847                 if (platform_sp)
2848                 {
2849                     ProcessInstanceInfoMatch match_info;
2850                     match_info.GetProcessInfo() = attach_info;
2851                     match_info.SetNameMatchType (eNameMatchEquals);
2852                     platform_sp->FindProcesses (match_info, process_infos);
2853                     const uint32_t num_matches = process_infos.GetSize();
2854                     if (num_matches == 1)
2855                     {
2856                         attach_pid = process_infos.GetProcessIDAtIndex(0);
2857                         // Fall through and attach using the above process ID
2858                     }
2859                     else
2860                     {
2861                         match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2862                         if (num_matches > 1)
2863                             error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2864                         else
2865                             error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2866                     }
2867                 }
2868                 else
2869                 {
2870                     error.SetErrorString ("invalid platform, can't find processes by name");
2871                     return error;
2872                 }
2873             }
2874         }
2875         else
2876         {
2877             error.SetErrorString ("invalid process name");
2878         }
2879     }
2880 
2881     if (attach_pid != LLDB_INVALID_PROCESS_ID)
2882     {
2883         error = WillAttachToProcessWithID(attach_pid);
2884         if (error.Success())
2885         {
2886 
2887             if (m_run_lock.WriteTryLock())
2888             {
2889                 // Now attach using these arguments.
2890                 m_should_detach = true;
2891                 SetPublicState (eStateAttaching);
2892                 error = DoAttachToProcessWithID (attach_pid, attach_info);
2893             }
2894             else
2895             {
2896                 // This shouldn't happen
2897                 error.SetErrorString("failed to acquire process run lock");
2898             }
2899 
2900             if (error.Success())
2901             {
2902 
2903                 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2904                 StartPrivateStateThread();
2905             }
2906             else
2907             {
2908                 if (GetID() != LLDB_INVALID_PROCESS_ID)
2909                 {
2910                     SetID (LLDB_INVALID_PROCESS_ID);
2911                     const char *error_string = error.AsCString();
2912                     if (error_string == NULL)
2913                         error_string = "attach failed";
2914 
2915                     SetExitStatus(-1, error_string);
2916                 }
2917             }
2918         }
2919     }
2920     return error;
2921 }
2922 
2923 void
2924 Process::CompleteAttach ()
2925 {
2926     // Let the process subclass figure out at much as it can about the process
2927     // before we go looking for a dynamic loader plug-in.
2928     DidAttach();
2929 
2930     // We just attached.  If we have a platform, ask it for the process architecture, and if it isn't
2931     // the same as the one we've already set, switch architectures.
2932     PlatformSP platform_sp (m_target.GetPlatform ());
2933     assert (platform_sp.get());
2934     if (platform_sp)
2935     {
2936         const ArchSpec &target_arch = m_target.GetArchitecture();
2937         if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2938         {
2939             ArchSpec platform_arch;
2940             platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2941             if (platform_sp)
2942             {
2943                 m_target.SetPlatform (platform_sp);
2944                 m_target.SetArchitecture(platform_arch);
2945             }
2946         }
2947         else
2948         {
2949             ProcessInstanceInfo process_info;
2950             platform_sp->GetProcessInfo (GetID(), process_info);
2951             const ArchSpec &process_arch = process_info.GetArchitecture();
2952             if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2953                 m_target.SetArchitecture (process_arch);
2954         }
2955     }
2956 
2957     // We have completed the attach, now it is time to find the dynamic loader
2958     // plug-in
2959     DynamicLoader *dyld = GetDynamicLoader ();
2960     if (dyld)
2961         dyld->DidAttach();
2962 
2963     m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2964     // Figure out which one is the executable, and set that in our target:
2965     ModuleList &target_modules = m_target.GetImages();
2966     Mutex::Locker modules_locker(target_modules.GetMutex());
2967     size_t num_modules = target_modules.GetSize();
2968     ModuleSP new_executable_module_sp;
2969 
2970     for (int i = 0; i < num_modules; i++)
2971     {
2972         ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
2973         if (module_sp && module_sp->IsExecutable())
2974         {
2975             if (m_target.GetExecutableModulePointer() != module_sp.get())
2976                 new_executable_module_sp = module_sp;
2977             break;
2978         }
2979     }
2980     if (new_executable_module_sp)
2981         m_target.SetExecutableModule (new_executable_module_sp, false);
2982 }
2983 
2984 Error
2985 Process::ConnectRemote (Stream *strm, const char *remote_url)
2986 {
2987     m_abi_sp.reset();
2988     m_process_input_reader.reset();
2989 
2990     // Find the process and its architecture.  Make sure it matches the architecture
2991     // of the current Target, and if not adjust it.
2992 
2993     Error error (DoConnectRemote (strm, remote_url));
2994     if (error.Success())
2995     {
2996         if (GetID() != LLDB_INVALID_PROCESS_ID)
2997         {
2998             EventSP event_sp;
2999             StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3000 
3001             if (state == eStateStopped || state == eStateCrashed)
3002             {
3003                 // If we attached and actually have a process on the other end, then
3004                 // this ended up being the equivalent of an attach.
3005                 CompleteAttach ();
3006 
3007                 // This delays passing the stopped event to listeners till
3008                 // CompleteAttach gets a chance to complete...
3009                 HandlePrivateEvent (event_sp);
3010 
3011             }
3012         }
3013 
3014         if (PrivateStateThreadIsValid ())
3015             ResumePrivateStateThread ();
3016         else
3017             StartPrivateStateThread ();
3018     }
3019     return error;
3020 }
3021 
3022 
3023 Error
3024 Process::PrivateResume ()
3025 {
3026     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
3027     if (log)
3028         log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
3029                     m_mod_id.GetStopID(),
3030                     StateAsCString(m_public_state.GetValue()),
3031                     StateAsCString(m_private_state.GetValue()));
3032 
3033     Error error (WillResume());
3034     // Tell the process it is about to resume before the thread list
3035     if (error.Success())
3036     {
3037         // Now let the thread list know we are about to resume so it
3038         // can let all of our threads know that they are about to be
3039         // resumed. Threads will each be called with
3040         // Thread::WillResume(StateType) where StateType contains the state
3041         // that they are supposed to have when the process is resumed
3042         // (suspended/running/stepping). Threads should also check
3043         // their resume signal in lldb::Thread::GetResumeSignal()
3044         // to see if they are suppoed to start back up with a signal.
3045         if (m_thread_list.WillResume())
3046         {
3047             // Last thing, do the PreResumeActions.
3048             if (!RunPreResumeActions())
3049             {
3050                 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3051             }
3052             else
3053             {
3054                 m_mod_id.BumpResumeID();
3055                 error = DoResume();
3056                 if (error.Success())
3057                 {
3058                     DidResume();
3059                     m_thread_list.DidResume();
3060                     if (log)
3061                         log->Printf ("Process thinks the process has resumed.");
3062                 }
3063             }
3064         }
3065         else
3066         {
3067             // Somebody wanted to run without running.  So generate a continue & a stopped event,
3068             // and let the world handle them.
3069             if (log)
3070                 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3071 
3072             SetPrivateState(eStateRunning);
3073             SetPrivateState(eStateStopped);
3074         }
3075     }
3076     else if (log)
3077         log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
3078     return error;
3079 }
3080 
3081 Error
3082 Process::Halt ()
3083 {
3084     // First make sure we aren't in the middle of handling an event, or we might restart.  This is pretty weak, since
3085     // we could just straightaway get another event.  It just narrows the window...
3086     m_currently_handling_event.WaitForValueEqualTo(false);
3087 
3088 
3089     // Pause our private state thread so we can ensure no one else eats
3090     // the stop event out from under us.
3091     Listener halt_listener ("lldb.process.halt_listener");
3092     HijackPrivateProcessEvents(&halt_listener);
3093 
3094     EventSP event_sp;
3095     Error error (WillHalt());
3096 
3097     if (error.Success())
3098     {
3099 
3100         bool caused_stop = false;
3101 
3102         // Ask the process subclass to actually halt our process
3103         error = DoHalt(caused_stop);
3104         if (error.Success())
3105         {
3106             if (m_public_state.GetValue() == eStateAttaching)
3107             {
3108                 SetExitStatus(SIGKILL, "Cancelled async attach.");
3109                 Destroy ();
3110             }
3111             else
3112             {
3113                 // If "caused_stop" is true, then DoHalt stopped the process. If
3114                 // "caused_stop" is false, the process was already stopped.
3115                 // If the DoHalt caused the process to stop, then we want to catch
3116                 // this event and set the interrupted bool to true before we pass
3117                 // this along so clients know that the process was interrupted by
3118                 // a halt command.
3119                 if (caused_stop)
3120                 {
3121                     // Wait for 1 second for the process to stop.
3122                     TimeValue timeout_time;
3123                     timeout_time = TimeValue::Now();
3124                     timeout_time.OffsetWithSeconds(1);
3125                     bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3126                     StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3127 
3128                     if (!got_event || state == eStateInvalid)
3129                     {
3130                         // We timeout out and didn't get a stop event...
3131                         error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
3132                     }
3133                     else
3134                     {
3135                         if (StateIsStoppedState (state, false))
3136                         {
3137                             // We caused the process to interrupt itself, so mark this
3138                             // as such in the stop event so clients can tell an interrupted
3139                             // process from a natural stop
3140                             ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3141                         }
3142                         else
3143                         {
3144                             LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3145                             if (log)
3146                                 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3147                             error.SetErrorString ("Did not get stopped event after halt.");
3148                         }
3149                     }
3150                 }
3151                 DidHalt();
3152             }
3153         }
3154     }
3155     // Resume our private state thread before we post the event (if any)
3156     RestorePrivateProcessEvents();
3157 
3158     // Post any event we might have consumed. If all goes well, we will have
3159     // stopped the process, intercepted the event and set the interrupted
3160     // bool in the event.  Post it to the private event queue and that will end up
3161     // correctly setting the state.
3162     if (event_sp)
3163         m_private_state_broadcaster.BroadcastEvent(event_sp);
3164 
3165     return error;
3166 }
3167 
3168 Error
3169 Process::Detach ()
3170 {
3171     Error error (WillDetach());
3172 
3173     if (error.Success())
3174     {
3175         DisableAllBreakpointSites();
3176         error = DoDetach();
3177         if (error.Success())
3178         {
3179             DidDetach();
3180             StopPrivateStateThread();
3181         }
3182     }
3183     return error;
3184 }
3185 
3186 Error
3187 Process::Destroy ()
3188 {
3189     Error error (WillDestroy());
3190     if (error.Success())
3191     {
3192         EventSP exit_event_sp;
3193         if (m_public_state.GetValue() == eStateRunning)
3194         {
3195             LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3196             if (log)
3197                 log->Printf("Process::Destroy() About to halt.");
3198             error = Halt();
3199             if (error.Success())
3200             {
3201                 // Consume the halt event.
3202                 TimeValue timeout (TimeValue::Now());
3203                 timeout.OffsetWithSeconds(1);
3204                 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3205                 if (state != eStateExited)
3206                     exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3207 
3208                 if (state != eStateStopped)
3209                 {
3210                     if (log)
3211                         log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
3212                     // If we really couldn't stop the process then we should just error out here, but if the
3213                     // lower levels just bobbled sending the event and we really are stopped, then continue on.
3214                     StateType private_state = m_private_state.GetValue();
3215                     if (private_state != eStateStopped && private_state != eStateExited)
3216                     {
3217                         // If we exited when we were waiting for a process to stop, then
3218                         // forward the event here so we don't lose the event
3219                         return error;
3220                     }
3221                 }
3222             }
3223             else
3224             {
3225                 if (log)
3226                     log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3227                 return error;
3228             }
3229         }
3230 
3231         if (m_public_state.GetValue() != eStateRunning)
3232         {
3233             // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3234             // kill it, we don't want it hitting a breakpoint...
3235             // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3236             // we're not going to have much luck doing this now.
3237             m_thread_list.DiscardThreadPlans();
3238             DisableAllBreakpointSites();
3239         }
3240 
3241         error = DoDestroy();
3242         if (error.Success())
3243         {
3244             DidDestroy();
3245             StopPrivateStateThread();
3246         }
3247         m_stdio_communication.StopReadThread();
3248         m_stdio_communication.Disconnect();
3249         if (m_process_input_reader && m_process_input_reader->IsActive())
3250             m_target.GetDebugger().PopInputReader (m_process_input_reader);
3251         if (m_process_input_reader)
3252             m_process_input_reader.reset();
3253 
3254         // If we exited when we were waiting for a process to stop, then
3255         // forward the event here so we don't lose the event
3256         if (exit_event_sp)
3257         {
3258             // Directly broadcast our exited event because we shut down our
3259             // private state thread above
3260             BroadcastEvent(exit_event_sp);
3261         }
3262 
3263         // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3264         // the last events through the event system, in which case we might strand the write lock.  Unlock
3265         // it here so when we do to tear down the process we don't get an error destroying the lock.
3266         m_run_lock.WriteUnlock();
3267     }
3268     return error;
3269 }
3270 
3271 Error
3272 Process::Signal (int signal)
3273 {
3274     Error error (WillSignal());
3275     if (error.Success())
3276     {
3277         error = DoSignal(signal);
3278         if (error.Success())
3279             DidSignal();
3280     }
3281     return error;
3282 }
3283 
3284 lldb::ByteOrder
3285 Process::GetByteOrder () const
3286 {
3287     return m_target.GetArchitecture().GetByteOrder();
3288 }
3289 
3290 uint32_t
3291 Process::GetAddressByteSize () const
3292 {
3293     return m_target.GetArchitecture().GetAddressByteSize();
3294 }
3295 
3296 
3297 bool
3298 Process::ShouldBroadcastEvent (Event *event_ptr)
3299 {
3300     const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3301     bool return_value = true;
3302     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3303 
3304     switch (state)
3305     {
3306         case eStateConnected:
3307         case eStateAttaching:
3308         case eStateLaunching:
3309         case eStateDetached:
3310         case eStateExited:
3311         case eStateUnloaded:
3312             // These events indicate changes in the state of the debugging session, always report them.
3313             return_value = true;
3314             break;
3315         case eStateInvalid:
3316             // We stopped for no apparent reason, don't report it.
3317             return_value = false;
3318             break;
3319         case eStateRunning:
3320         case eStateStepping:
3321             // If we've started the target running, we handle the cases where we
3322             // are already running and where there is a transition from stopped to
3323             // running differently.
3324             // running -> running: Automatically suppress extra running events
3325             // stopped -> running: Report except when there is one or more no votes
3326             //     and no yes votes.
3327             SynchronouslyNotifyStateChanged (state);
3328             switch (m_public_state.GetValue())
3329             {
3330                 case eStateRunning:
3331                 case eStateStepping:
3332                     // We always suppress multiple runnings with no PUBLIC stop in between.
3333                     return_value = false;
3334                     break;
3335                 default:
3336                     // TODO: make this work correctly. For now always report
3337                     // run if we aren't running so we don't miss any runnning
3338                     // events. If I run the lldb/test/thread/a.out file and
3339                     // break at main.cpp:58, run and hit the breakpoints on
3340                     // multiple threads, then somehow during the stepping over
3341                     // of all breakpoints no run gets reported.
3342 
3343                     // This is a transition from stop to run.
3344                     switch (m_thread_list.ShouldReportRun (event_ptr))
3345                     {
3346                         default:
3347                         case eVoteYes:
3348                         case eVoteNoOpinion:
3349                             return_value = true;
3350                             break;
3351                         case eVoteNo:
3352                             return_value = false;
3353                             break;
3354                     }
3355                     break;
3356             }
3357             break;
3358         case eStateStopped:
3359         case eStateCrashed:
3360         case eStateSuspended:
3361         {
3362             // We've stopped.  First see if we're going to restart the target.
3363             // If we are going to stop, then we always broadcast the event.
3364             // If we aren't going to stop, let the thread plans decide if we're going to report this event.
3365             // If no thread has an opinion, we don't report it.
3366 
3367             RefreshStateAfterStop ();
3368             if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
3369             {
3370                 if (log)
3371                     log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
3372                 return true;
3373             }
3374             else
3375             {
3376 
3377                 if (m_thread_list.ShouldStop (event_ptr) == false)
3378                 {
3379                     // ShouldStop may have restarted the target already.  If so, don't
3380                     // resume it twice.
3381                     bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3382                     switch (m_thread_list.ShouldReportStop (event_ptr))
3383                     {
3384                         case eVoteYes:
3385                             Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
3386                             // Intentional fall-through here.
3387                         case eVoteNoOpinion:
3388                         case eVoteNo:
3389                             return_value = false;
3390                             break;
3391                     }
3392 
3393                     if (log)
3394                         log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3395                     if (!was_restarted)
3396                         PrivateResume ();
3397                 }
3398                 else
3399                 {
3400                     return_value = true;
3401                     SynchronouslyNotifyStateChanged (state);
3402                 }
3403             }
3404         }
3405     }
3406 
3407     if (log)
3408         log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
3409     return return_value;
3410 }
3411 
3412 
3413 bool
3414 Process::StartPrivateStateThread (bool force)
3415 {
3416     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3417 
3418     bool already_running = PrivateStateThreadIsValid ();
3419     if (log)
3420         log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3421 
3422     if (!force && already_running)
3423         return true;
3424 
3425     // Create a thread that watches our internal state and controls which
3426     // events make it to clients (into the DCProcess event queue).
3427     char thread_name[1024];
3428     if (already_running)
3429         snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3430     else
3431         snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
3432 
3433     // Create the private state thread, and start it running.
3434     m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
3435     bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3436     if (success)
3437     {
3438         ResumePrivateStateThread();
3439         return true;
3440     }
3441     else
3442         return false;
3443 }
3444 
3445 void
3446 Process::PausePrivateStateThread ()
3447 {
3448     ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3449 }
3450 
3451 void
3452 Process::ResumePrivateStateThread ()
3453 {
3454     ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3455 }
3456 
3457 void
3458 Process::StopPrivateStateThread ()
3459 {
3460     if (PrivateStateThreadIsValid ())
3461         ControlPrivateStateThread (eBroadcastInternalStateControlStop);
3462     else
3463     {
3464         LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3465         if (log)
3466             printf ("Went to stop the private state thread, but it was already invalid.");
3467     }
3468 }
3469 
3470 void
3471 Process::ControlPrivateStateThread (uint32_t signal)
3472 {
3473     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3474 
3475     assert (signal == eBroadcastInternalStateControlStop ||
3476             signal == eBroadcastInternalStateControlPause ||
3477             signal == eBroadcastInternalStateControlResume);
3478 
3479     if (log)
3480         log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
3481 
3482     // Signal the private state thread. First we should copy this is case the
3483     // thread starts exiting since the private state thread will NULL this out
3484     // when it exits
3485     const lldb::thread_t private_state_thread = m_private_state_thread;
3486     if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
3487     {
3488         TimeValue timeout_time;
3489         bool timed_out;
3490 
3491         m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3492 
3493         timeout_time = TimeValue::Now();
3494         timeout_time.OffsetWithSeconds(2);
3495         if (log)
3496             log->Printf ("Sending control event of type: %d.", signal);
3497         m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3498         m_private_state_control_wait.SetValue (false, eBroadcastNever);
3499 
3500         if (signal == eBroadcastInternalStateControlStop)
3501         {
3502             if (timed_out)
3503             {
3504                 Error error;
3505                 Host::ThreadCancel (private_state_thread, &error);
3506                 if (log)
3507                     log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3508             }
3509             else
3510             {
3511                 if (log)
3512                     log->Printf ("The control event killed the private state thread without having to cancel.");
3513             }
3514 
3515             thread_result_t result = NULL;
3516             Host::ThreadJoin (private_state_thread, &result, NULL);
3517             m_private_state_thread = LLDB_INVALID_HOST_THREAD;
3518         }
3519     }
3520     else
3521     {
3522         if (log)
3523             log->Printf ("Private state thread already dead, no need to signal it to stop.");
3524     }
3525 }
3526 
3527 void
3528 Process::SendAsyncInterrupt ()
3529 {
3530     if (PrivateStateThreadIsValid())
3531         m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3532     else
3533         BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3534 }
3535 
3536 void
3537 Process::HandlePrivateEvent (EventSP &event_sp)
3538 {
3539     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3540     m_currently_handling_event.SetValue(true, eBroadcastNever);
3541 
3542     const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3543 
3544     // First check to see if anybody wants a shot at this event:
3545     if (m_next_event_action_ap.get() != NULL)
3546     {
3547         NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
3548         switch (action_result)
3549         {
3550             case NextEventAction::eEventActionSuccess:
3551                 SetNextEventAction(NULL);
3552                 break;
3553 
3554             case NextEventAction::eEventActionRetry:
3555                 break;
3556 
3557             case NextEventAction::eEventActionExit:
3558                 // Handle Exiting Here.  If we already got an exited event,
3559                 // we should just propagate it.  Otherwise, swallow this event,
3560                 // and set our state to exit so the next event will kill us.
3561                 if (new_state != eStateExited)
3562                 {
3563                     // FIXME: should cons up an exited event, and discard this one.
3564                     SetExitStatus(0, m_next_event_action_ap->GetExitString());
3565                     SetNextEventAction(NULL);
3566                     return;
3567                 }
3568                 SetNextEventAction(NULL);
3569                 break;
3570         }
3571     }
3572 
3573     // See if we should broadcast this state to external clients?
3574     const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
3575 
3576     if (should_broadcast)
3577     {
3578         if (log)
3579         {
3580             log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
3581                          __FUNCTION__,
3582                          GetID(),
3583                          StateAsCString(new_state),
3584                          StateAsCString (GetState ()),
3585                          IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
3586         }
3587         Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3588         if (StateIsRunningState (new_state))
3589             PushProcessInputReader ();
3590         else
3591             PopProcessInputReader ();
3592 
3593         BroadcastEvent (event_sp);
3594     }
3595     else
3596     {
3597         if (log)
3598         {
3599             log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
3600                          __FUNCTION__,
3601                          GetID(),
3602                          StateAsCString(new_state),
3603                          StateAsCString (GetState ()));
3604         }
3605     }
3606     m_currently_handling_event.SetValue(false, eBroadcastAlways);
3607 }
3608 
3609 void *
3610 Process::PrivateStateThread (void *arg)
3611 {
3612     Process *proc = static_cast<Process*> (arg);
3613     void *result = proc->RunPrivateStateThread ();
3614     return result;
3615 }
3616 
3617 void *
3618 Process::RunPrivateStateThread ()
3619 {
3620     bool control_only = true;
3621     m_private_state_control_wait.SetValue (false, eBroadcastNever);
3622 
3623     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3624     if (log)
3625         log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
3626 
3627     bool exit_now = false;
3628     while (!exit_now)
3629     {
3630         EventSP event_sp;
3631         WaitForEventsPrivate (NULL, event_sp, control_only);
3632         if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3633         {
3634             if (log)
3635                 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3636 
3637             switch (event_sp->GetType())
3638             {
3639             case eBroadcastInternalStateControlStop:
3640                 exit_now = true;
3641                 break;      // doing any internal state managment below
3642 
3643             case eBroadcastInternalStateControlPause:
3644                 control_only = true;
3645                 break;
3646 
3647             case eBroadcastInternalStateControlResume:
3648                 control_only = false;
3649                 break;
3650             }
3651 
3652             m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3653             continue;
3654         }
3655         else if (event_sp->GetType() == eBroadcastBitInterrupt)
3656         {
3657             if (m_public_state.GetValue() == eStateAttaching)
3658             {
3659                 if (log)
3660                     log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3661                 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3662             }
3663             else
3664             {
3665                 if (log)
3666                     log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3667                 Halt();
3668             }
3669             continue;
3670         }
3671 
3672         const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3673 
3674         if (internal_state != eStateInvalid)
3675         {
3676             HandlePrivateEvent (event_sp);
3677         }
3678 
3679         if (internal_state == eStateInvalid ||
3680             internal_state == eStateExited  ||
3681             internal_state == eStateDetached )
3682         {
3683             if (log)
3684                 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
3685 
3686             break;
3687         }
3688     }
3689 
3690     // Verify log is still enabled before attempting to write to it...
3691     if (log)
3692         log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
3693 
3694     m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3695     m_private_state_thread = LLDB_INVALID_HOST_THREAD;
3696     return NULL;
3697 }
3698 
3699 //------------------------------------------------------------------
3700 // Process Event Data
3701 //------------------------------------------------------------------
3702 
3703 Process::ProcessEventData::ProcessEventData () :
3704     EventData (),
3705     m_process_sp (),
3706     m_state (eStateInvalid),
3707     m_restarted (false),
3708     m_update_state (0),
3709     m_interrupted (false)
3710 {
3711 }
3712 
3713 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3714     EventData (),
3715     m_process_sp (process_sp),
3716     m_state (state),
3717     m_restarted (false),
3718     m_update_state (0),
3719     m_interrupted (false)
3720 {
3721 }
3722 
3723 Process::ProcessEventData::~ProcessEventData()
3724 {
3725 }
3726 
3727 const ConstString &
3728 Process::ProcessEventData::GetFlavorString ()
3729 {
3730     static ConstString g_flavor ("Process::ProcessEventData");
3731     return g_flavor;
3732 }
3733 
3734 const ConstString &
3735 Process::ProcessEventData::GetFlavor () const
3736 {
3737     return ProcessEventData::GetFlavorString ();
3738 }
3739 
3740 void
3741 Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3742 {
3743     // This function gets called twice for each event, once when the event gets pulled
3744     // off of the private process event queue, and then any number of times, first when it gets pulled off of
3745     // the public event queue, then other times when we're pretending that this is where we stopped at the
3746     // end of expression evaluation.  m_update_state is used to distinguish these
3747     // three cases; it is 0 when we're just pulling it off for private handling,
3748     // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
3749 
3750     if (m_update_state != 1)
3751         return;
3752 
3753     m_process_sp->SetPublicState (m_state);
3754 
3755     // If we're stopped and haven't restarted, then do the breakpoint commands here:
3756     if (m_state == eStateStopped && ! m_restarted)
3757     {
3758         ThreadList &curr_thread_list = m_process_sp->GetThreadList();
3759         uint32_t num_threads = curr_thread_list.GetSize();
3760         uint32_t idx;
3761 
3762         // The actions might change one of the thread's stop_info's opinions about whether we should
3763         // stop the process, so we need to query that as we go.
3764 
3765         // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3766         // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3767         // that would cause our iteration here to crash.  We could make a copy of the thread list, but we'd really like
3768         // 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
3769         // against this list & bag out if anything differs.
3770         std::vector<uint32_t> thread_index_array(num_threads);
3771         for (idx = 0; idx < num_threads; ++idx)
3772             thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3773 
3774         bool still_should_stop = true;
3775 
3776         for (idx = 0; idx < num_threads; ++idx)
3777         {
3778             curr_thread_list = m_process_sp->GetThreadList();
3779             if (curr_thread_list.GetSize() != num_threads)
3780             {
3781                 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3782                 if (log)
3783                     log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
3784                 break;
3785             }
3786 
3787             lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3788 
3789             if (thread_sp->GetIndexID() != thread_index_array[idx])
3790             {
3791                 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3792                 if (log)
3793                     log->Printf("The thread at position %u changed from %u to %u while processing event.",
3794                                 idx,
3795                                 thread_index_array[idx],
3796                                 thread_sp->GetIndexID());
3797                 break;
3798             }
3799 
3800             StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3801             if (stop_info_sp && stop_info_sp->IsValid())
3802             {
3803                 stop_info_sp->PerformAction(event_ptr);
3804                 // The stop action might restart the target.  If it does, then we want to mark that in the
3805                 // event so that whoever is receiving it will know to wait for the running event and reflect
3806                 // that state appropriately.
3807                 // We also need to stop processing actions, since they aren't expecting the target to be running.
3808 
3809                 // FIXME: we might have run.
3810                 if (stop_info_sp->HasTargetRunSinceMe())
3811                 {
3812                     SetRestarted (true);
3813                     break;
3814                 }
3815                 else if (!stop_info_sp->ShouldStop(event_ptr))
3816                 {
3817                     still_should_stop = false;
3818                 }
3819             }
3820         }
3821 
3822 
3823         if (m_process_sp->GetPrivateState() != eStateRunning)
3824         {
3825             if (!still_should_stop)
3826             {
3827                 // We've been asked to continue, so do that here.
3828                 SetRestarted(true);
3829                 // Use the public resume method here, since this is just
3830                 // extending a public resume.
3831                 m_process_sp->Resume();
3832             }
3833             else
3834             {
3835                 // If we didn't restart, run the Stop Hooks here:
3836                 // They might also restart the target, so watch for that.
3837                 m_process_sp->GetTarget().RunStopHooks();
3838                 if (m_process_sp->GetPrivateState() == eStateRunning)
3839                     SetRestarted(true);
3840             }
3841         }
3842 
3843     }
3844 }
3845 
3846 void
3847 Process::ProcessEventData::Dump (Stream *s) const
3848 {
3849     if (m_process_sp)
3850         s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
3851 
3852     s->Printf("state = %s", StateAsCString(GetState()));
3853 }
3854 
3855 const Process::ProcessEventData *
3856 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3857 {
3858     if (event_ptr)
3859     {
3860         const EventData *event_data = event_ptr->GetData();
3861         if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3862             return static_cast <const ProcessEventData *> (event_ptr->GetData());
3863     }
3864     return NULL;
3865 }
3866 
3867 ProcessSP
3868 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3869 {
3870     ProcessSP process_sp;
3871     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3872     if (data)
3873         process_sp = data->GetProcessSP();
3874     return process_sp;
3875 }
3876 
3877 StateType
3878 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3879 {
3880     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3881     if (data == NULL)
3882         return eStateInvalid;
3883     else
3884         return data->GetState();
3885 }
3886 
3887 bool
3888 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3889 {
3890     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3891     if (data == NULL)
3892         return false;
3893     else
3894         return data->GetRestarted();
3895 }
3896 
3897 void
3898 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3899 {
3900     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3901     if (data != NULL)
3902         data->SetRestarted(new_value);
3903 }
3904 
3905 bool
3906 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3907 {
3908     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3909     if (data == NULL)
3910         return false;
3911     else
3912         return data->GetInterrupted ();
3913 }
3914 
3915 void
3916 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3917 {
3918     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3919     if (data != NULL)
3920         data->SetInterrupted(new_value);
3921 }
3922 
3923 bool
3924 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3925 {
3926     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3927     if (data)
3928     {
3929         data->SetUpdateStateOnRemoval();
3930         return true;
3931     }
3932     return false;
3933 }
3934 
3935 lldb::TargetSP
3936 Process::CalculateTarget ()
3937 {
3938     return m_target.shared_from_this();
3939 }
3940 
3941 void
3942 Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
3943 {
3944     exe_ctx.SetTargetPtr (&m_target);
3945     exe_ctx.SetProcessPtr (this);
3946     exe_ctx.SetThreadPtr(NULL);
3947     exe_ctx.SetFramePtr (NULL);
3948 }
3949 
3950 //uint32_t
3951 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3952 //{
3953 //    return 0;
3954 //}
3955 //
3956 //ArchSpec
3957 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3958 //{
3959 //    return Host::GetArchSpecForExistingProcess (pid);
3960 //}
3961 //
3962 //ArchSpec
3963 //Process::GetArchSpecForExistingProcess (const char *process_name)
3964 //{
3965 //    return Host::GetArchSpecForExistingProcess (process_name);
3966 //}
3967 //
3968 void
3969 Process::AppendSTDOUT (const char * s, size_t len)
3970 {
3971     Mutex::Locker locker (m_stdio_communication_mutex);
3972     m_stdout_data.append (s, len);
3973     BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
3974 }
3975 
3976 void
3977 Process::AppendSTDERR (const char * s, size_t len)
3978 {
3979     Mutex::Locker locker (m_stdio_communication_mutex);
3980     m_stderr_data.append (s, len);
3981     BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
3982 }
3983 
3984 //------------------------------------------------------------------
3985 // Process STDIO
3986 //------------------------------------------------------------------
3987 
3988 size_t
3989 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3990 {
3991     Mutex::Locker locker(m_stdio_communication_mutex);
3992     size_t bytes_available = m_stdout_data.size();
3993     if (bytes_available > 0)
3994     {
3995         LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3996         if (log)
3997             log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
3998         if (bytes_available > buf_size)
3999         {
4000             memcpy(buf, m_stdout_data.c_str(), buf_size);
4001             m_stdout_data.erase(0, buf_size);
4002             bytes_available = buf_size;
4003         }
4004         else
4005         {
4006             memcpy(buf, m_stdout_data.c_str(), bytes_available);
4007             m_stdout_data.clear();
4008         }
4009     }
4010     return bytes_available;
4011 }
4012 
4013 
4014 size_t
4015 Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4016 {
4017     Mutex::Locker locker(m_stdio_communication_mutex);
4018     size_t bytes_available = m_stderr_data.size();
4019     if (bytes_available > 0)
4020     {
4021         LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4022         if (log)
4023             log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
4024         if (bytes_available > buf_size)
4025         {
4026             memcpy(buf, m_stderr_data.c_str(), buf_size);
4027             m_stderr_data.erase(0, buf_size);
4028             bytes_available = buf_size;
4029         }
4030         else
4031         {
4032             memcpy(buf, m_stderr_data.c_str(), bytes_available);
4033             m_stderr_data.clear();
4034         }
4035     }
4036     return bytes_available;
4037 }
4038 
4039 void
4040 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4041 {
4042     Process *process = (Process *) baton;
4043     process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4044 }
4045 
4046 size_t
4047 Process::ProcessInputReaderCallback (void *baton,
4048                                      InputReader &reader,
4049                                      lldb::InputReaderAction notification,
4050                                      const char *bytes,
4051                                      size_t bytes_len)
4052 {
4053     Process *process = (Process *) baton;
4054 
4055     switch (notification)
4056     {
4057     case eInputReaderActivate:
4058         break;
4059 
4060     case eInputReaderDeactivate:
4061         break;
4062 
4063     case eInputReaderReactivate:
4064         break;
4065 
4066     case eInputReaderAsynchronousOutputWritten:
4067         break;
4068 
4069     case eInputReaderGotToken:
4070         {
4071             Error error;
4072             process->PutSTDIN (bytes, bytes_len, error);
4073         }
4074         break;
4075 
4076     case eInputReaderInterrupt:
4077         process->Halt ();
4078         break;
4079 
4080     case eInputReaderEndOfFile:
4081         process->AppendSTDOUT ("^D", 2);
4082         break;
4083 
4084     case eInputReaderDone:
4085         break;
4086 
4087     }
4088 
4089     return bytes_len;
4090 }
4091 
4092 void
4093 Process::ResetProcessInputReader ()
4094 {
4095     m_process_input_reader.reset();
4096 }
4097 
4098 void
4099 Process::SetSTDIOFileDescriptor (int file_descriptor)
4100 {
4101     // First set up the Read Thread for reading/handling process I/O
4102 
4103     std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4104 
4105     if (conn_ap.get())
4106     {
4107         m_stdio_communication.SetConnection (conn_ap.release());
4108         if (m_stdio_communication.IsConnected())
4109         {
4110             m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4111             m_stdio_communication.StartReadThread();
4112 
4113             // Now read thread is set up, set up input reader.
4114 
4115             if (!m_process_input_reader.get())
4116             {
4117                 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4118                 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4119                                                                this,
4120                                                                eInputReaderGranularityByte,
4121                                                                NULL,
4122                                                                NULL,
4123                                                                false));
4124 
4125                 if  (err.Fail())
4126                     m_process_input_reader.reset();
4127             }
4128         }
4129     }
4130 }
4131 
4132 void
4133 Process::PushProcessInputReader ()
4134 {
4135     if (m_process_input_reader && !m_process_input_reader->IsActive())
4136         m_target.GetDebugger().PushInputReader (m_process_input_reader);
4137 }
4138 
4139 void
4140 Process::PopProcessInputReader ()
4141 {
4142     if (m_process_input_reader && m_process_input_reader->IsActive())
4143         m_target.GetDebugger().PopInputReader (m_process_input_reader);
4144 }
4145 
4146 // The process needs to know about installed plug-ins
4147 void
4148 Process::SettingsInitialize ()
4149 {
4150 //    static std::vector<OptionEnumValueElement> g_plugins;
4151 //
4152 //    int i=0;
4153 //    const char *name;
4154 //    OptionEnumValueElement option_enum;
4155 //    while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4156 //    {
4157 //        if (name)
4158 //        {
4159 //            option_enum.value = i;
4160 //            option_enum.string_value = name;
4161 //            option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4162 //            g_plugins.push_back (option_enum);
4163 //        }
4164 //        ++i;
4165 //    }
4166 //    option_enum.value = 0;
4167 //    option_enum.string_value = NULL;
4168 //    option_enum.usage = NULL;
4169 //    g_plugins.push_back (option_enum);
4170 //
4171 //    for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4172 //    {
4173 //        if (::strcmp (name, "plugin") == 0)
4174 //        {
4175 //            SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4176 //            break;
4177 //        }
4178 //    }
4179 //
4180     Thread::SettingsInitialize ();
4181 }
4182 
4183 void
4184 Process::SettingsTerminate ()
4185 {
4186     Thread::SettingsTerminate ();
4187 }
4188 
4189 ExecutionResults
4190 Process::RunThreadPlan (ExecutionContext &exe_ctx,
4191                         lldb::ThreadPlanSP &thread_plan_sp,
4192                         bool stop_others,
4193                         bool run_others,
4194                         bool discard_on_error,
4195                         uint32_t timeout_usec,
4196                         Stream &errors)
4197 {
4198     ExecutionResults return_value = eExecutionSetupError;
4199 
4200     if (thread_plan_sp.get() == NULL)
4201     {
4202         errors.Printf("RunThreadPlan called with empty thread plan.");
4203         return eExecutionSetupError;
4204     }
4205 
4206     if (exe_ctx.GetProcessPtr() != this)
4207     {
4208         errors.Printf("RunThreadPlan called on wrong process.");
4209         return eExecutionSetupError;
4210     }
4211 
4212     Thread *thread = exe_ctx.GetThreadPtr();
4213     if (thread == NULL)
4214     {
4215         errors.Printf("RunThreadPlan called with invalid thread.");
4216         return eExecutionSetupError;
4217     }
4218 
4219     // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4220     // For that to be true the plan can't be private - since private plans suppress themselves in the
4221     // GetCompletedPlan call.
4222 
4223     bool orig_plan_private = thread_plan_sp->GetPrivate();
4224     thread_plan_sp->SetPrivate(false);
4225 
4226     if (m_private_state.GetValue() != eStateStopped)
4227     {
4228         errors.Printf ("RunThreadPlan called while the private state was not stopped.");
4229         return eExecutionSetupError;
4230     }
4231 
4232     // Save the thread & frame from the exe_ctx for restoration after we run
4233     const uint32_t thread_idx_id = thread->GetIndexID();
4234     StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
4235 
4236     // N.B. Running the target may unset the currently selected thread and frame.  We don't want to do that either,
4237     // so we should arrange to reset them as well.
4238 
4239     lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4240 
4241     uint32_t selected_tid;
4242     StackID selected_stack_id;
4243     if (selected_thread_sp)
4244     {
4245         selected_tid = selected_thread_sp->GetIndexID();
4246         selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4247     }
4248     else
4249     {
4250         selected_tid = LLDB_INVALID_THREAD_ID;
4251     }
4252 
4253     lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
4254     lldb::StateType old_state;
4255     lldb::ThreadPlanSP stopper_base_plan_sp;
4256 
4257     lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4258     if (Host::GetCurrentThread() == m_private_state_thread)
4259     {
4260         // Yikes, we are running on the private state thread!  So we can't wait for public events on this thread, since
4261         // we are the thread that is generating public events.
4262         // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
4263         // we are fielding public events here.
4264         if (log)
4265 			log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4266 
4267 
4268         backup_private_state_thread = m_private_state_thread;
4269 
4270         // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4271         // returning control here.
4272         // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4273         // event before deciding to stop, and we don't want that.  So we insert a "stopper" base plan on the stack
4274         // before the plan we want to run.  Since base plans always stop and return control to the user, that will
4275         // do just what we want.
4276         stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4277         thread->QueueThreadPlan (stopper_base_plan_sp, false);
4278         // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4279         old_state = m_public_state.GetValue();
4280         m_public_state.SetValueNoLock(eStateStopped);
4281 
4282         // Now spin up the private state thread:
4283         StartPrivateStateThread(true);
4284     }
4285 
4286     thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
4287 
4288     Listener listener("lldb.process.listener.run-thread-plan");
4289 
4290     lldb::EventSP event_to_broadcast_sp;
4291 
4292     {
4293         // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4294         // restored on exit to the function.
4295         //
4296         // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4297         // is put into event_to_broadcast_sp for rebroadcasting.
4298 
4299         ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
4300 
4301         if (log)
4302         {
4303             StreamString s;
4304             thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4305             log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4306                          thread->GetIndexID(),
4307                          thread->GetID(),
4308                          s.GetData());
4309         }
4310 
4311         bool got_event;
4312         lldb::EventSP event_sp;
4313         lldb::StateType stop_state = lldb::eStateInvalid;
4314 
4315         TimeValue* timeout_ptr = NULL;
4316         TimeValue real_timeout;
4317 
4318         bool first_timeout = true;
4319         bool do_resume = true;
4320         const uint64_t default_one_thread_timeout_usec = 250000;
4321         uint64_t computed_timeout = 0;
4322 
4323         while (1)
4324         {
4325             // We usually want to resume the process if we get to the top of the loop.
4326             // The only exception is if we get two running events with no intervening
4327             // stop, which can happen, we will just wait for then next stop event.
4328 
4329             if (do_resume)
4330             {
4331                 // Do the initial resume and wait for the running event before going further.
4332 
4333                 Error resume_error = PrivateResume ();
4334                 if (!resume_error.Success())
4335                 {
4336                     errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4337                     return_value = eExecutionSetupError;
4338                     break;
4339                 }
4340 
4341                 real_timeout = TimeValue::Now();
4342                 real_timeout.OffsetWithMicroSeconds(500000);
4343                 timeout_ptr = &real_timeout;
4344 
4345                 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4346                 if (!got_event)
4347                 {
4348                     if (log)
4349                         log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4350 
4351                     errors.Printf("Didn't get any event after initial resume, exiting.");
4352                     return_value = eExecutionSetupError;
4353                     break;
4354                 }
4355 
4356                 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4357                 if (stop_state != eStateRunning)
4358                 {
4359                     if (log)
4360                         log->Printf("Process::RunThreadPlan(): didn't get running event after "
4361                                     "initial resume, got %s instead.",
4362                                     StateAsCString(stop_state));
4363 
4364                     errors.Printf("Didn't get running event after initial resume, got %s instead.",
4365                                   StateAsCString(stop_state));
4366                     return_value = eExecutionSetupError;
4367                     break;
4368                 }
4369 
4370                 if (log)
4371                     log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4372                 // We need to call the function synchronously, so spin waiting for it to return.
4373                 // If we get interrupted while executing, we're going to lose our context, and
4374                 // won't be able to gather the result at this point.
4375                 // We set the timeout AFTER the resume, since the resume takes some time and we
4376                 // don't want to charge that to the timeout.
4377 
4378                 if (first_timeout)
4379                 {
4380                     if (run_others)
4381                     {
4382                         // If we are running all threads then we take half the time to run all threads, bounded by
4383                         // .25 sec.
4384                         if (timeout_usec == 0)
4385                             computed_timeout = default_one_thread_timeout_usec;
4386                         else
4387                         {
4388                             computed_timeout = timeout_usec / 2;
4389                             if (computed_timeout > default_one_thread_timeout_usec)
4390                             {
4391                                 computed_timeout = default_one_thread_timeout_usec;
4392                             }
4393                             timeout_usec -= computed_timeout;
4394                         }
4395                     }
4396                     else
4397                     {
4398                         computed_timeout = timeout_usec;
4399                     }
4400                 }
4401                 else
4402                 {
4403                     computed_timeout = timeout_usec;
4404                 }
4405 
4406                 if (computed_timeout != 0)
4407                 {
4408                     // we have a > 0 timeout, let us set it so that we stop after the deadline
4409                     real_timeout = TimeValue::Now();
4410                     real_timeout.OffsetWithMicroSeconds(computed_timeout);
4411 
4412                     timeout_ptr = &real_timeout;
4413                 }
4414                 else
4415                 {
4416                     timeout_ptr = NULL;
4417                 }
4418             }
4419             else
4420             {
4421                 if (log)
4422                     log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4423                 do_resume = true;
4424             }
4425 
4426             // Now wait for the process to stop again:
4427             event_sp.reset();
4428 
4429             if (log)
4430             {
4431                 if (timeout_ptr)
4432                 {
4433                     StreamString s;
4434                     s.Printf ("about to wait - timeout is:\n   ");
4435                     timeout_ptr->Dump (&s, 120);
4436                     s.Printf ("\nNow is:\n    ");
4437                     TimeValue::Now().Dump (&s, 120);
4438                     log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4439                 }
4440                 else
4441                 {
4442                     log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4443                 }
4444             }
4445 
4446             got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4447 
4448             if (got_event)
4449             {
4450                 if (event_sp.get())
4451                 {
4452                     bool keep_going = false;
4453                     if (event_sp->GetType() == eBroadcastBitInterrupt)
4454                     {
4455                         Halt();
4456                         keep_going = false;
4457                         return_value = eExecutionInterrupted;
4458                         errors.Printf ("Execution halted by user interrupt.");
4459                         if (log)
4460                             log->Printf ("Process::RunThreadPlan(): Got  interrupted by eBroadcastBitInterrupted, exiting.");
4461                     }
4462                     else
4463                     {
4464                         stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4465                         if (log)
4466                             log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4467 
4468                         switch (stop_state)
4469                         {
4470                         case lldb::eStateStopped:
4471                             {
4472                                 // Yay, we're done.  Now make sure that our thread plan actually completed.
4473                                 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4474                                 if (!thread_sp)
4475                                 {
4476                                     // Ooh, our thread has vanished.  Unlikely that this was successful execution...
4477                                     if (log)
4478                                         log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4479                                     return_value = eExecutionInterrupted;
4480                                 }
4481                                 else
4482                                 {
4483                                     StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4484                                     StopReason stop_reason = eStopReasonInvalid;
4485                                     if (stop_info_sp)
4486                                          stop_reason = stop_info_sp->GetStopReason();
4487                                     if (stop_reason == eStopReasonPlanComplete)
4488                                     {
4489                                         if (log)
4490                                             log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4491                                         // Now mark this plan as private so it doesn't get reported as the stop reason
4492                                         // after this point.
4493                                         if (thread_plan_sp)
4494                                             thread_plan_sp->SetPrivate (orig_plan_private);
4495                                         return_value = eExecutionCompleted;
4496                                     }
4497                                     else
4498                                     {
4499                                         if (log)
4500                                             log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
4501 
4502                                         return_value = eExecutionInterrupted;
4503                                     }
4504                                 }
4505                             }
4506                             break;
4507 
4508                         case lldb::eStateCrashed:
4509                             if (log)
4510                                 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4511                             return_value = eExecutionInterrupted;
4512                             break;
4513 
4514                         case lldb::eStateRunning:
4515                             do_resume = false;
4516                             keep_going = true;
4517                             break;
4518 
4519                         default:
4520                             if (log)
4521                                 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4522 
4523                             if (stop_state == eStateExited)
4524                                 event_to_broadcast_sp = event_sp;
4525 
4526                             errors.Printf ("Execution stopped with unexpected state.\n");
4527                             return_value = eExecutionInterrupted;
4528                             break;
4529                         }
4530                     }
4531 
4532                     if (keep_going)
4533                         continue;
4534                     else
4535                         break;
4536                 }
4537                 else
4538                 {
4539                     if (log)
4540                         log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null.  How odd...");
4541                     return_value = eExecutionInterrupted;
4542                     break;
4543                 }
4544             }
4545             else
4546             {
4547                 // If we didn't get an event that means we've timed out...
4548                 // We will interrupt the process here.  Depending on what we were asked to do we will
4549                 // either exit, or try with all threads running for the same timeout.
4550                 // Not really sure what to do if Halt fails here...
4551 
4552                 if (log) {
4553                     if (run_others)
4554                     {
4555                         if (first_timeout)
4556                             log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4557                                          "trying  for %d usec with all threads enabled.",
4558                                          computed_timeout, timeout_usec);
4559                         else
4560                             log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4561                                          "and timeout: %d timed out, abandoning execution.",
4562                                          timeout_usec);
4563                     }
4564                     else
4565                         log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4566                                      "abandoning execution.",
4567                                      timeout_usec);
4568                 }
4569 
4570                 Error halt_error = Halt();
4571                 if (halt_error.Success())
4572                 {
4573                     if (log)
4574                         log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4575 
4576                     // If halt succeeds, it always produces a stopped event.  Wait for that:
4577 
4578                     real_timeout = TimeValue::Now();
4579                     real_timeout.OffsetWithMicroSeconds(500000);
4580 
4581                     got_event = listener.WaitForEvent(&real_timeout, event_sp);
4582 
4583                     if (got_event)
4584                     {
4585                         stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4586                         if (log)
4587                         {
4588                             log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4589                             if (stop_state == lldb::eStateStopped
4590                                 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4591                                 log->PutCString ("    Event was the Halt interruption event.");
4592                         }
4593 
4594                         if (stop_state == lldb::eStateStopped)
4595                         {
4596                             // Between the time we initiated the Halt and the time we delivered it, the process could have
4597                             // already finished its job.  Check that here:
4598 
4599                             if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4600                             {
4601                                 if (log)
4602                                     log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done.  "
4603                                                  "Exiting wait loop.");
4604                                 return_value = eExecutionCompleted;
4605                                 break;
4606                             }
4607 
4608                             if (!run_others)
4609                             {
4610                                 if (log)
4611                                     log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4612                                 return_value = eExecutionInterrupted;
4613                                 break;
4614                             }
4615 
4616                             if (first_timeout)
4617                             {
4618                                 // Set all the other threads to run, and return to the top of the loop, which will continue;
4619                                 first_timeout = false;
4620                                 thread_plan_sp->SetStopOthers (false);
4621                                 if (log)
4622                                     log->PutCString ("Process::RunThreadPlan(): about to resume.");
4623 
4624                                 continue;
4625                             }
4626                             else
4627                             {
4628                                 // Running all threads failed, so return Interrupted.
4629                                 if (log)
4630                                     log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4631                                 return_value = eExecutionInterrupted;
4632                                 break;
4633                             }
4634                         }
4635                     }
4636                     else
4637                     {   if (log)
4638                             log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event.  "
4639                                     "I'm getting out of here passing Interrupted.");
4640                         return_value = eExecutionInterrupted;
4641                         break;
4642                     }
4643                 }
4644                 else
4645                 {
4646                     // This branch is to work around some problems with gdb-remote's Halt.  It is a little racy, and can return
4647                     // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4648                     if (log)
4649                         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.",
4650                                      halt_error.AsCString());
4651                     real_timeout = TimeValue::Now();
4652                     real_timeout.OffsetWithMicroSeconds(500000);
4653                     timeout_ptr = &real_timeout;
4654                     got_event = listener.WaitForEvent(&real_timeout, event_sp);
4655                     if (!got_event || event_sp.get() == NULL)
4656                     {
4657                         // This is not going anywhere, bag out.
4658                         if (log)
4659                             log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4660                         return_value = eExecutionInterrupted;
4661                         break;
4662                     }
4663                     else
4664                     {
4665                         stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4666                         if (log)
4667                             log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event.  Whatever...");
4668                         if (stop_state == lldb::eStateStopped)
4669                         {
4670                             // Between the time we initiated the Halt and the time we delivered it, the process could have
4671                             // already finished its job.  Check that here:
4672 
4673                             if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4674                             {
4675                                 if (log)
4676                                     log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done.  "
4677                                                  "Exiting wait loop.");
4678                                 return_value = eExecutionCompleted;
4679                                 break;
4680                             }
4681 
4682                             if (first_timeout)
4683                             {
4684                                 // Set all the other threads to run, and return to the top of the loop, which will continue;
4685                                 first_timeout = false;
4686                                 thread_plan_sp->SetStopOthers (false);
4687                                 if (log)
4688                                     log->PutCString ("Process::RunThreadPlan(): About to resume.");
4689 
4690                                 continue;
4691                             }
4692                             else
4693                             {
4694                                 // Running all threads failed, so return Interrupted.
4695                                 if (log)
4696                                     log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4697                                 return_value = eExecutionInterrupted;
4698                                 break;
4699                             }
4700                         }
4701                         else
4702                         {
4703                             if (log)
4704                                 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4705                                              " a stopped event, instead got %s.", StateAsCString(stop_state));
4706                             return_value = eExecutionInterrupted;
4707                             break;
4708                         }
4709                     }
4710                 }
4711 
4712             }
4713 
4714         }  // END WAIT LOOP
4715 
4716         // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4717         if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4718         {
4719             StopPrivateStateThread();
4720             Error error;
4721             m_private_state_thread = backup_private_state_thread;
4722             if (stopper_base_plan_sp)
4723             {
4724                 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4725             }
4726             m_public_state.SetValueNoLock(old_state);
4727 
4728         }
4729 
4730 
4731         // Now do some processing on the results of the run:
4732         if (return_value == eExecutionInterrupted)
4733         {
4734             if (log)
4735             {
4736                 StreamString s;
4737                 if (event_sp)
4738                     event_sp->Dump (&s);
4739                 else
4740                 {
4741                     log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4742                 }
4743 
4744                 StreamString ts;
4745 
4746                 const char *event_explanation = NULL;
4747 
4748                 do
4749                 {
4750                     if (!event_sp)
4751                     {
4752                         event_explanation = "<no event>";
4753                         break;
4754                     }
4755                     else if (event_sp->GetType() == eBroadcastBitInterrupt)
4756                     {
4757                         event_explanation = "<user interrupt>";
4758                         break;
4759                     }
4760                     else
4761                     {
4762                         const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4763 
4764                         if (!event_data)
4765                         {
4766                             event_explanation = "<no event data>";
4767                             break;
4768                         }
4769 
4770                         Process *process = event_data->GetProcessSP().get();
4771 
4772                         if (!process)
4773                         {
4774                             event_explanation = "<no process>";
4775                             break;
4776                         }
4777 
4778                         ThreadList &thread_list = process->GetThreadList();
4779 
4780                         uint32_t num_threads = thread_list.GetSize();
4781                         uint32_t thread_index;
4782 
4783                         ts.Printf("<%u threads> ", num_threads);
4784 
4785                         for (thread_index = 0;
4786                              thread_index < num_threads;
4787                              ++thread_index)
4788                         {
4789                             Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4790 
4791                             if (!thread)
4792                             {
4793                                 ts.Printf("<?> ");
4794                                 continue;
4795                             }
4796 
4797                             ts.Printf("<0x%4.4llx ", thread->GetID());
4798                             RegisterContext *register_context = thread->GetRegisterContext().get();
4799 
4800                             if (register_context)
4801                                 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4802                             else
4803                                 ts.Printf("[ip unknown] ");
4804 
4805                             lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4806                             if (stop_info_sp)
4807                             {
4808                                 const char *stop_desc = stop_info_sp->GetDescription();
4809                                 if (stop_desc)
4810                                     ts.PutCString (stop_desc);
4811                             }
4812                             ts.Printf(">");
4813                         }
4814 
4815                         event_explanation = ts.GetData();
4816                     }
4817                 } while (0);
4818 
4819                 if (event_explanation)
4820                     log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4821                 else
4822                     log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4823             }
4824 
4825             if (discard_on_error && thread_plan_sp)
4826             {
4827                 if (log)
4828                     log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4829                 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4830                 thread_plan_sp->SetPrivate (orig_plan_private);
4831             }
4832             else
4833             {
4834                 if (log)
4835                     log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
4836             }
4837         }
4838         else if (return_value == eExecutionSetupError)
4839         {
4840             if (log)
4841                 log->PutCString("Process::RunThreadPlan(): execution set up error.");
4842 
4843             if (discard_on_error && thread_plan_sp)
4844             {
4845                 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4846                 thread_plan_sp->SetPrivate (orig_plan_private);
4847             }
4848         }
4849         else
4850         {
4851             if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4852             {
4853                 if (log)
4854                     log->PutCString("Process::RunThreadPlan(): thread plan is done");
4855                 return_value = eExecutionCompleted;
4856             }
4857             else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4858             {
4859                 if (log)
4860                     log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4861                 return_value = eExecutionDiscarded;
4862             }
4863             else
4864             {
4865                 if (log)
4866                     log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4867                 if (discard_on_error && thread_plan_sp)
4868                 {
4869                     if (log)
4870                         log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4871                     thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4872                     thread_plan_sp->SetPrivate (orig_plan_private);
4873                 }
4874             }
4875         }
4876 
4877         // Thread we ran the function in may have gone away because we ran the target
4878         // Check that it's still there, and if it is put it back in the context.  Also restore the
4879         // frame in the context if it is still present.
4880         thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4881         if (thread)
4882         {
4883             exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4884         }
4885 
4886         // Also restore the current process'es selected frame & thread, since this function calling may
4887         // be done behind the user's back.
4888 
4889         if (selected_tid != LLDB_INVALID_THREAD_ID)
4890         {
4891             if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4892             {
4893                 // We were able to restore the selected thread, now restore the frame:
4894                 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4895                 if (old_frame_sp)
4896                     GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
4897             }
4898         }
4899     }
4900 
4901     // If the process exited during the run of the thread plan, notify everyone.
4902 
4903     if (event_to_broadcast_sp)
4904     {
4905         if (log)
4906             log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4907         BroadcastEvent(event_to_broadcast_sp);
4908     }
4909 
4910     return return_value;
4911 }
4912 
4913 const char *
4914 Process::ExecutionResultAsCString (ExecutionResults result)
4915 {
4916     const char *result_name;
4917 
4918     switch (result)
4919     {
4920         case eExecutionCompleted:
4921             result_name = "eExecutionCompleted";
4922             break;
4923         case eExecutionDiscarded:
4924             result_name = "eExecutionDiscarded";
4925             break;
4926         case eExecutionInterrupted:
4927             result_name = "eExecutionInterrupted";
4928             break;
4929         case eExecutionSetupError:
4930             result_name = "eExecutionSetupError";
4931             break;
4932         case eExecutionTimedOut:
4933             result_name = "eExecutionTimedOut";
4934             break;
4935     }
4936     return result_name;
4937 }
4938 
4939 void
4940 Process::GetStatus (Stream &strm)
4941 {
4942     const StateType state = GetState();
4943     if (StateIsStoppedState(state, false))
4944     {
4945         if (state == eStateExited)
4946         {
4947             int exit_status = GetExitStatus();
4948             const char *exit_description = GetExitDescription();
4949             strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
4950                           GetID(),
4951                           exit_status,
4952                           exit_status,
4953                           exit_description ? exit_description : "");
4954         }
4955         else
4956         {
4957             if (state == eStateConnected)
4958                 strm.Printf ("Connected to remote target.\n");
4959             else
4960                 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
4961         }
4962     }
4963     else
4964     {
4965         strm.Printf ("Process %llu is running.\n", GetID());
4966     }
4967 }
4968 
4969 size_t
4970 Process::GetThreadStatus (Stream &strm,
4971                           bool only_threads_with_stop_reason,
4972                           uint32_t start_frame,
4973                           uint32_t num_frames,
4974                           uint32_t num_frames_with_source)
4975 {
4976     size_t num_thread_infos_dumped = 0;
4977 
4978     Mutex::Locker locker (GetThreadList().GetMutex());
4979     const size_t num_threads = GetThreadList().GetSize();
4980     for (uint32_t i = 0; i < num_threads; i++)
4981     {
4982         Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4983         if (thread)
4984         {
4985             if (only_threads_with_stop_reason)
4986             {
4987                 StopInfoSP stop_info_sp = thread->GetStopInfo();
4988                 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
4989                     continue;
4990             }
4991             thread->GetStatus (strm,
4992                                start_frame,
4993                                num_frames,
4994                                num_frames_with_source);
4995             ++num_thread_infos_dumped;
4996         }
4997     }
4998     return num_thread_infos_dumped;
4999 }
5000 
5001 void
5002 Process::AddInvalidMemoryRegion (const LoadRange &region)
5003 {
5004     m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5005 }
5006 
5007 bool
5008 Process::RemoveInvalidMemoryRange (const LoadRange &region)
5009 {
5010     return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5011 }
5012 
5013 void
5014 Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5015 {
5016     m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5017 }
5018 
5019 bool
5020 Process::RunPreResumeActions ()
5021 {
5022     bool result = true;
5023     while (!m_pre_resume_actions.empty())
5024     {
5025         struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5026         m_pre_resume_actions.pop_back();
5027         bool this_result = action.callback (action.baton);
5028         if (result == true) result = this_result;
5029     }
5030     return result;
5031 }
5032 
5033 void
5034 Process::ClearPreResumeActions ()
5035 {
5036     m_pre_resume_actions.clear();
5037 }
5038 
5039 void
5040 Process::Flush ()
5041 {
5042     m_thread_list.Flush();
5043 }
5044