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