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