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