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