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