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