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