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