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