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