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