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