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