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