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