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