1254721Semaste//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste#include "lldb/lldb-python.h"
11254721Semaste
12254721Semaste#include "lldb/Target/Process.h"
13254721Semaste
14254721Semaste#include "lldb/lldb-private-log.h"
15254721Semaste
16254721Semaste#include "lldb/Breakpoint/StoppointCallbackContext.h"
17254721Semaste#include "lldb/Breakpoint/BreakpointLocation.h"
18254721Semaste#include "lldb/Core/Event.h"
19254721Semaste#include "lldb/Core/ConnectionFileDescriptor.h"
20254721Semaste#include "lldb/Core/Debugger.h"
21254721Semaste#include "lldb/Core/InputReader.h"
22254721Semaste#include "lldb/Core/Log.h"
23254721Semaste#include "lldb/Core/Module.h"
24254721Semaste#include "lldb/Core/PluginManager.h"
25254721Semaste#include "lldb/Core/State.h"
26254721Semaste#include "lldb/Expression/ClangUserExpression.h"
27254721Semaste#include "lldb/Interpreter/CommandInterpreter.h"
28254721Semaste#include "lldb/Host/Host.h"
29254721Semaste#include "lldb/Target/ABI.h"
30254721Semaste#include "lldb/Target/DynamicLoader.h"
31254721Semaste#include "lldb/Target/OperatingSystem.h"
32254721Semaste#include "lldb/Target/LanguageRuntime.h"
33254721Semaste#include "lldb/Target/CPPLanguageRuntime.h"
34254721Semaste#include "lldb/Target/ObjCLanguageRuntime.h"
35254721Semaste#include "lldb/Target/Platform.h"
36254721Semaste#include "lldb/Target/RegisterContext.h"
37254721Semaste#include "lldb/Target/StopInfo.h"
38254721Semaste#include "lldb/Target/Target.h"
39254721Semaste#include "lldb/Target/TargetList.h"
40254721Semaste#include "lldb/Target/Thread.h"
41254721Semaste#include "lldb/Target/ThreadPlan.h"
42254721Semaste#include "lldb/Target/ThreadPlanBase.h"
43254721Semaste
44254721Semasteusing namespace lldb;
45254721Semasteusing namespace lldb_private;
46254721Semaste
47254721Semaste
48254721Semaste// Comment out line below to disable memory caching, overriding the process setting
49254721Semaste// target.process.disable-memory-cache
50254721Semaste#define ENABLE_MEMORY_CACHING
51254721Semaste
52254721Semaste#ifdef ENABLE_MEMORY_CACHING
53254721Semaste#define DISABLE_MEM_CACHE_DEFAULT false
54254721Semaste#else
55254721Semaste#define DISABLE_MEM_CACHE_DEFAULT true
56254721Semaste#endif
57254721Semaste
58254721Semasteclass ProcessOptionValueProperties : public OptionValueProperties
59254721Semaste{
60254721Semastepublic:
61254721Semaste    ProcessOptionValueProperties (const ConstString &name) :
62254721Semaste        OptionValueProperties (name)
63254721Semaste    {
64254721Semaste    }
65254721Semaste
66254721Semaste    // This constructor is used when creating ProcessOptionValueProperties when it
67254721Semaste    // is part of a new lldb_private::Process instance. It will copy all current
68254721Semaste    // global property values as needed
69254721Semaste    ProcessOptionValueProperties (ProcessProperties *global_properties) :
70254721Semaste        OptionValueProperties(*global_properties->GetValueProperties())
71254721Semaste    {
72254721Semaste    }
73254721Semaste
74254721Semaste    virtual const Property *
75254721Semaste    GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
76254721Semaste    {
77254721Semaste        // When gettings the value for a key from the process options, we will always
78254721Semaste        // try and grab the setting from the current process if there is one. Else we just
79254721Semaste        // use the one from this instance.
80254721Semaste        if (exe_ctx)
81254721Semaste        {
82254721Semaste            Process *process = exe_ctx->GetProcessPtr();
83254721Semaste            if (process)
84254721Semaste            {
85254721Semaste                ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86254721Semaste                if (this != instance_properties)
87254721Semaste                    return instance_properties->ProtectedGetPropertyAtIndex (idx);
88254721Semaste            }
89254721Semaste        }
90254721Semaste        return ProtectedGetPropertyAtIndex (idx);
91254721Semaste    }
92254721Semaste};
93254721Semaste
94254721Semastestatic PropertyDefinition
95254721Semasteg_properties[] =
96254721Semaste{
97254721Semaste    { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
98254721Semaste    { "extra-startup-command", OptionValue::eTypeArray  , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used.  "
99254721Semaste                                                                                                       "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
100254721Semaste    { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101254721Semaste    { "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." },
102254721Semaste    { "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." },
103254721Semaste    { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
104254721Semaste    { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
105254721Semaste    {  NULL                  , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL  }
106254721Semaste};
107254721Semaste
108254721Semasteenum {
109254721Semaste    ePropertyDisableMemCache,
110254721Semaste    ePropertyExtraStartCommand,
111254721Semaste    ePropertyIgnoreBreakpointsInExpressions,
112254721Semaste    ePropertyUnwindOnErrorInExpressions,
113254721Semaste    ePropertyPythonOSPluginPath,
114254721Semaste    ePropertyStopOnSharedLibraryEvents,
115254721Semaste    ePropertyDetachKeepsStopped
116254721Semaste};
117254721Semaste
118254721SemasteProcessProperties::ProcessProperties (bool is_global) :
119254721Semaste    Properties ()
120254721Semaste{
121254721Semaste    if (is_global)
122254721Semaste    {
123254721Semaste        m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
124254721Semaste        m_collection_sp->Initialize(g_properties);
125254721Semaste        m_collection_sp->AppendProperty(ConstString("thread"),
126254721Semaste                                        ConstString("Settings specific to threads."),
127254721Semaste                                        true,
128254721Semaste                                        Thread::GetGlobalProperties()->GetValueProperties());
129254721Semaste    }
130254721Semaste    else
131254721Semaste        m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
132254721Semaste}
133254721Semaste
134254721SemasteProcessProperties::~ProcessProperties()
135254721Semaste{
136254721Semaste}
137254721Semaste
138254721Semastebool
139254721SemasteProcessProperties::GetDisableMemoryCache() const
140254721Semaste{
141254721Semaste    const uint32_t idx = ePropertyDisableMemCache;
142254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
143254721Semaste}
144254721Semaste
145254721SemasteArgs
146254721SemasteProcessProperties::GetExtraStartupCommands () const
147254721Semaste{
148254721Semaste    Args args;
149254721Semaste    const uint32_t idx = ePropertyExtraStartCommand;
150254721Semaste    m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
151254721Semaste    return args;
152254721Semaste}
153254721Semaste
154254721Semastevoid
155254721SemasteProcessProperties::SetExtraStartupCommands (const Args &args)
156254721Semaste{
157254721Semaste    const uint32_t idx = ePropertyExtraStartCommand;
158254721Semaste    m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
159254721Semaste}
160254721Semaste
161254721SemasteFileSpec
162254721SemasteProcessProperties::GetPythonOSPluginPath () const
163254721Semaste{
164254721Semaste    const uint32_t idx = ePropertyPythonOSPluginPath;
165254721Semaste    return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
166254721Semaste}
167254721Semaste
168254721Semastevoid
169254721SemasteProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
170254721Semaste{
171254721Semaste    const uint32_t idx = ePropertyPythonOSPluginPath;
172254721Semaste    m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
173254721Semaste}
174254721Semaste
175254721Semaste
176254721Semastebool
177254721SemasteProcessProperties::GetIgnoreBreakpointsInExpressions () const
178254721Semaste{
179254721Semaste    const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
180254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
181254721Semaste}
182254721Semaste
183254721Semastevoid
184254721SemasteProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
185254721Semaste{
186254721Semaste    const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
187254721Semaste    m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
188254721Semaste}
189254721Semaste
190254721Semastebool
191254721SemasteProcessProperties::GetUnwindOnErrorInExpressions () const
192254721Semaste{
193254721Semaste    const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
194254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
195254721Semaste}
196254721Semaste
197254721Semastevoid
198254721SemasteProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
199254721Semaste{
200254721Semaste    const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201254721Semaste    m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
202254721Semaste}
203254721Semaste
204254721Semastebool
205254721SemasteProcessProperties::GetStopOnSharedLibraryEvents () const
206254721Semaste{
207254721Semaste    const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
208254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
209254721Semaste}
210254721Semaste
211254721Semastevoid
212254721SemasteProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
213254721Semaste{
214254721Semaste    const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
215254721Semaste    m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
216254721Semaste}
217254721Semaste
218254721Semastebool
219254721SemasteProcessProperties::GetDetachKeepsStopped () const
220254721Semaste{
221254721Semaste    const uint32_t idx = ePropertyDetachKeepsStopped;
222254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
223254721Semaste}
224254721Semaste
225254721Semastevoid
226254721SemasteProcessProperties::SetDetachKeepsStopped (bool stop)
227254721Semaste{
228254721Semaste    const uint32_t idx = ePropertyDetachKeepsStopped;
229254721Semaste    m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
230254721Semaste}
231254721Semaste
232254721Semastevoid
233254721SemasteProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
234254721Semaste{
235254721Semaste    const char *cstr;
236254721Semaste    if (m_pid != LLDB_INVALID_PROCESS_ID)
237254721Semaste        s.Printf ("    pid = %" PRIu64 "\n", m_pid);
238254721Semaste
239254721Semaste    if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
240254721Semaste        s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
241254721Semaste
242254721Semaste    if (m_executable)
243254721Semaste    {
244254721Semaste        s.Printf ("   name = %s\n", m_executable.GetFilename().GetCString());
245254721Semaste        s.PutCString ("   file = ");
246254721Semaste        m_executable.Dump(&s);
247254721Semaste        s.EOL();
248254721Semaste    }
249254721Semaste    const uint32_t argc = m_arguments.GetArgumentCount();
250254721Semaste    if (argc > 0)
251254721Semaste    {
252254721Semaste        for (uint32_t i=0; i<argc; i++)
253254721Semaste        {
254254721Semaste            const char *arg = m_arguments.GetArgumentAtIndex(i);
255254721Semaste            if (i < 10)
256254721Semaste                s.Printf (" arg[%u] = %s\n", i, arg);
257254721Semaste            else
258254721Semaste                s.Printf ("arg[%u] = %s\n", i, arg);
259254721Semaste        }
260254721Semaste    }
261254721Semaste
262254721Semaste    const uint32_t envc = m_environment.GetArgumentCount();
263254721Semaste    if (envc > 0)
264254721Semaste    {
265254721Semaste        for (uint32_t i=0; i<envc; i++)
266254721Semaste        {
267254721Semaste            const char *env = m_environment.GetArgumentAtIndex(i);
268254721Semaste            if (i < 10)
269254721Semaste                s.Printf (" env[%u] = %s\n", i, env);
270254721Semaste            else
271254721Semaste                s.Printf ("env[%u] = %s\n", i, env);
272254721Semaste        }
273254721Semaste    }
274254721Semaste
275254721Semaste    if (m_arch.IsValid())
276254721Semaste        s.Printf ("   arch = %s\n", m_arch.GetTriple().str().c_str());
277254721Semaste
278254721Semaste    if (m_uid != UINT32_MAX)
279254721Semaste    {
280254721Semaste        cstr = platform->GetUserName (m_uid);
281254721Semaste        s.Printf ("    uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
282254721Semaste    }
283254721Semaste    if (m_gid != UINT32_MAX)
284254721Semaste    {
285254721Semaste        cstr = platform->GetGroupName (m_gid);
286254721Semaste        s.Printf ("    gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
287254721Semaste    }
288254721Semaste    if (m_euid != UINT32_MAX)
289254721Semaste    {
290254721Semaste        cstr = platform->GetUserName (m_euid);
291254721Semaste        s.Printf ("   euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
292254721Semaste    }
293254721Semaste    if (m_egid != UINT32_MAX)
294254721Semaste    {
295254721Semaste        cstr = platform->GetGroupName (m_egid);
296254721Semaste        s.Printf ("   egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
297254721Semaste    }
298254721Semaste}
299254721Semaste
300254721Semastevoid
301254721SemasteProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
302254721Semaste{
303254721Semaste    const char *label;
304254721Semaste    if (show_args || verbose)
305254721Semaste        label = "ARGUMENTS";
306254721Semaste    else
307254721Semaste        label = "NAME";
308254721Semaste
309254721Semaste    if (verbose)
310254721Semaste    {
311254721Semaste        s.Printf     ("PID    PARENT USER       GROUP      EFF USER   EFF GROUP  TRIPLE                   %s\n", label);
312254721Semaste        s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
313254721Semaste    }
314254721Semaste    else
315254721Semaste    {
316254721Semaste        s.Printf     ("PID    PARENT USER       ARCH    %s\n", label);
317254721Semaste        s.PutCString ("====== ====== ========== ======= ============================\n");
318254721Semaste    }
319254721Semaste}
320254721Semaste
321254721Semastevoid
322254721SemasteProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
323254721Semaste{
324254721Semaste    if (m_pid != LLDB_INVALID_PROCESS_ID)
325254721Semaste    {
326254721Semaste        const char *cstr;
327254721Semaste        s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
328254721Semaste
329254721Semaste
330254721Semaste        if (verbose)
331254721Semaste        {
332254721Semaste            cstr = platform->GetUserName (m_uid);
333254721Semaste            if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
334254721Semaste                s.Printf ("%-10s ", cstr);
335254721Semaste            else
336254721Semaste                s.Printf ("%-10u ", m_uid);
337254721Semaste
338254721Semaste            cstr = platform->GetGroupName (m_gid);
339254721Semaste            if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
340254721Semaste                s.Printf ("%-10s ", cstr);
341254721Semaste            else
342254721Semaste                s.Printf ("%-10u ", m_gid);
343254721Semaste
344254721Semaste            cstr = platform->GetUserName (m_euid);
345254721Semaste            if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
346254721Semaste                s.Printf ("%-10s ", cstr);
347254721Semaste            else
348254721Semaste                s.Printf ("%-10u ", m_euid);
349254721Semaste
350254721Semaste            cstr = platform->GetGroupName (m_egid);
351254721Semaste            if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
352254721Semaste                s.Printf ("%-10s ", cstr);
353254721Semaste            else
354254721Semaste                s.Printf ("%-10u ", m_egid);
355254721Semaste            s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
356254721Semaste        }
357254721Semaste        else
358254721Semaste        {
359254721Semaste            s.Printf ("%-10s %-7d %s ",
360254721Semaste                      platform->GetUserName (m_euid),
361254721Semaste                      (int)m_arch.GetTriple().getArchName().size(),
362254721Semaste                      m_arch.GetTriple().getArchName().data());
363254721Semaste        }
364254721Semaste
365254721Semaste        if (verbose || show_args)
366254721Semaste        {
367254721Semaste            const uint32_t argc = m_arguments.GetArgumentCount();
368254721Semaste            if (argc > 0)
369254721Semaste            {
370254721Semaste                for (uint32_t i=0; i<argc; i++)
371254721Semaste                {
372254721Semaste                    if (i > 0)
373254721Semaste                        s.PutChar (' ');
374254721Semaste                    s.PutCString (m_arguments.GetArgumentAtIndex(i));
375254721Semaste                }
376254721Semaste            }
377254721Semaste        }
378254721Semaste        else
379254721Semaste        {
380254721Semaste            s.PutCString (GetName());
381254721Semaste        }
382254721Semaste
383254721Semaste        s.EOL();
384254721Semaste    }
385254721Semaste}
386254721Semaste
387254721Semaste
388254721Semastevoid
389254721SemasteProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
390254721Semaste{
391254721Semaste    m_arguments.SetArguments (argv);
392254721Semaste
393254721Semaste    // Is the first argument the executable?
394254721Semaste    if (first_arg_is_executable)
395254721Semaste    {
396254721Semaste        const char *first_arg = m_arguments.GetArgumentAtIndex (0);
397254721Semaste        if (first_arg)
398254721Semaste        {
399254721Semaste            // Yes the first argument is an executable, set it as the executable
400254721Semaste            // in the launch options. Don't resolve the file path as the path
401254721Semaste            // could be a remote platform path
402254721Semaste            const bool resolve = false;
403254721Semaste            m_executable.SetFile(first_arg, resolve);
404254721Semaste        }
405254721Semaste    }
406254721Semaste}
407254721Semastevoid
408254721SemasteProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
409254721Semaste{
410254721Semaste    // Copy all arguments
411254721Semaste    m_arguments = args;
412254721Semaste
413254721Semaste    // Is the first argument the executable?
414254721Semaste    if (first_arg_is_executable)
415254721Semaste    {
416254721Semaste        const char *first_arg = m_arguments.GetArgumentAtIndex (0);
417254721Semaste        if (first_arg)
418254721Semaste        {
419254721Semaste            // Yes the first argument is an executable, set it as the executable
420254721Semaste            // in the launch options. Don't resolve the file path as the path
421254721Semaste            // could be a remote platform path
422254721Semaste            const bool resolve = false;
423254721Semaste            m_executable.SetFile(first_arg, resolve);
424254721Semaste        }
425254721Semaste    }
426254721Semaste}
427254721Semaste
428254721Semastevoid
429254721SemasteProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
430254721Semaste{
431254721Semaste    // If notthing was specified, then check the process for any default
432254721Semaste    // settings that were set with "settings set"
433254721Semaste    if (m_file_actions.empty())
434254721Semaste    {
435254721Semaste        if (m_flags.Test(eLaunchFlagDisableSTDIO))
436254721Semaste        {
437254721Semaste            AppendSuppressFileAction (STDIN_FILENO , true, false);
438254721Semaste            AppendSuppressFileAction (STDOUT_FILENO, false, true);
439254721Semaste            AppendSuppressFileAction (STDERR_FILENO, false, true);
440254721Semaste        }
441254721Semaste        else
442254721Semaste        {
443254721Semaste            // Check for any values that might have gotten set with any of:
444254721Semaste            // (lldb) settings set target.input-path
445254721Semaste            // (lldb) settings set target.output-path
446254721Semaste            // (lldb) settings set target.error-path
447254721Semaste            FileSpec in_path;
448254721Semaste            FileSpec out_path;
449254721Semaste            FileSpec err_path;
450254721Semaste            if (target)
451254721Semaste            {
452254721Semaste                in_path = target->GetStandardInputPath();
453254721Semaste                out_path = target->GetStandardOutputPath();
454254721Semaste                err_path = target->GetStandardErrorPath();
455254721Semaste            }
456254721Semaste
457254721Semaste            if (in_path || out_path || err_path)
458254721Semaste            {
459254721Semaste                char path[PATH_MAX];
460254721Semaste                if (in_path && in_path.GetPath(path, sizeof(path)))
461254721Semaste                    AppendOpenFileAction(STDIN_FILENO, path, true, false);
462254721Semaste
463254721Semaste                if (out_path && out_path.GetPath(path, sizeof(path)))
464254721Semaste                    AppendOpenFileAction(STDOUT_FILENO, path, false, true);
465254721Semaste
466254721Semaste                if (err_path && err_path.GetPath(path, sizeof(path)))
467254721Semaste                    AppendOpenFileAction(STDERR_FILENO, path, false, true);
468254721Semaste            }
469254721Semaste            else if (default_to_use_pty)
470254721Semaste            {
471254721Semaste                if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
472254721Semaste                {
473254721Semaste                    const char *slave_path = m_pty.GetSlaveName (NULL, 0);
474254721Semaste                    AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
475254721Semaste                    AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
476254721Semaste                    AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
477254721Semaste                }
478254721Semaste            }
479254721Semaste        }
480254721Semaste    }
481254721Semaste}
482254721Semaste
483254721Semaste
484254721Semastebool
485254721SemasteProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
486254721Semaste                                                        bool localhost,
487254721Semaste                                                        bool will_debug,
488254721Semaste                                                        bool first_arg_is_full_shell_command)
489254721Semaste{
490254721Semaste    error.Clear();
491254721Semaste
492254721Semaste    if (GetFlags().Test (eLaunchFlagLaunchInShell))
493254721Semaste    {
494254721Semaste        const char *shell_executable = GetShell();
495254721Semaste        if (shell_executable)
496254721Semaste        {
497254721Semaste            char shell_resolved_path[PATH_MAX];
498254721Semaste
499254721Semaste            if (localhost)
500254721Semaste            {
501254721Semaste                FileSpec shell_filespec (shell_executable, true);
502254721Semaste
503254721Semaste                if (!shell_filespec.Exists())
504254721Semaste                {
505254721Semaste                    // Resolve the path in case we just got "bash", "sh" or "tcsh"
506254721Semaste                    if (!shell_filespec.ResolveExecutableLocation ())
507254721Semaste                    {
508254721Semaste                        error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
509254721Semaste                        return false;
510254721Semaste                    }
511254721Semaste                }
512254721Semaste                shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
513254721Semaste                shell_executable = shell_resolved_path;
514254721Semaste            }
515254721Semaste
516254721Semaste            const char **argv = GetArguments().GetConstArgumentVector ();
517254721Semaste            if (argv == NULL || argv[0] == NULL)
518254721Semaste                return false;
519254721Semaste            Args shell_arguments;
520254721Semaste            std::string safe_arg;
521254721Semaste            shell_arguments.AppendArgument (shell_executable);
522254721Semaste            shell_arguments.AppendArgument ("-c");
523254721Semaste            StreamString shell_command;
524254721Semaste            if (will_debug)
525254721Semaste            {
526254721Semaste                // Add a modified PATH environment variable in case argv[0]
527254721Semaste                // is a relative path
528254721Semaste                const char *argv0 = argv[0];
529254721Semaste                if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
530254721Semaste                {
531254721Semaste                    // We have a relative path to our executable which may not work if
532254721Semaste                    // we just try to run "a.out" (without it being converted to "./a.out")
533254721Semaste                    const char *working_dir = GetWorkingDirectory();
534254721Semaste                    // Be sure to put quotes around PATH's value in case any paths have spaces...
535254721Semaste                    std::string new_path("PATH=\"");
536254721Semaste                    const size_t empty_path_len = new_path.size();
537254721Semaste
538254721Semaste                    if (working_dir && working_dir[0])
539254721Semaste                    {
540254721Semaste                        new_path += working_dir;
541254721Semaste                    }
542254721Semaste                    else
543254721Semaste                    {
544254721Semaste                        char current_working_dir[PATH_MAX];
545254721Semaste                        const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
546254721Semaste                        if (cwd && cwd[0])
547254721Semaste                            new_path += cwd;
548254721Semaste                    }
549254721Semaste                    const char *curr_path = getenv("PATH");
550254721Semaste                    if (curr_path)
551254721Semaste                    {
552254721Semaste                        if (new_path.size() > empty_path_len)
553254721Semaste                            new_path += ':';
554254721Semaste                        new_path += curr_path;
555254721Semaste                    }
556254721Semaste                    new_path += "\" ";
557254721Semaste                    shell_command.PutCString(new_path.c_str());
558254721Semaste                }
559254721Semaste
560254721Semaste                shell_command.PutCString ("exec");
561254721Semaste
562254721Semaste                // Only Apple supports /usr/bin/arch being able to specify the architecture
563254721Semaste                if (GetArchitecture().IsValid())
564254721Semaste                {
565254721Semaste                    shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
566254721Semaste                    // Set the resume count to 2:
567254721Semaste                    // 1 - stop in shell
568254721Semaste                    // 2 - stop in /usr/bin/arch
569254721Semaste                    // 3 - then we will stop in our program
570254721Semaste                    SetResumeCount(2);
571254721Semaste                }
572254721Semaste                else
573254721Semaste                {
574254721Semaste                    // Set the resume count to 1:
575254721Semaste                    // 1 - stop in shell
576254721Semaste                    // 2 - then we will stop in our program
577254721Semaste                    SetResumeCount(1);
578254721Semaste                }
579254721Semaste            }
580254721Semaste
581254721Semaste            if (first_arg_is_full_shell_command)
582254721Semaste            {
583254721Semaste                // There should only be one argument that is the shell command itself to be used as is
584254721Semaste                if (argv[0] && !argv[1])
585254721Semaste                    shell_command.Printf("%s", argv[0]);
586254721Semaste                else
587254721Semaste                    return false;
588254721Semaste            }
589254721Semaste            else
590254721Semaste            {
591254721Semaste                for (size_t i=0; argv[i] != NULL; ++i)
592254721Semaste                {
593254721Semaste                    const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
594254721Semaste                    shell_command.Printf(" %s", arg);
595254721Semaste                }
596254721Semaste            }
597254721Semaste            shell_arguments.AppendArgument (shell_command.GetString().c_str());
598254721Semaste            m_executable.SetFile(shell_executable, false);
599254721Semaste            m_arguments = shell_arguments;
600254721Semaste            return true;
601254721Semaste        }
602254721Semaste        else
603254721Semaste        {
604254721Semaste            error.SetErrorString ("invalid shell path");
605254721Semaste        }
606254721Semaste    }
607254721Semaste    else
608254721Semaste    {
609254721Semaste        error.SetErrorString ("not launching in shell");
610254721Semaste    }
611254721Semaste    return false;
612254721Semaste}
613254721Semaste
614254721Semaste
615254721Semastebool
616254721SemasteProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
617254721Semaste{
618254721Semaste    if ((read || write) && fd >= 0 && path && path[0])
619254721Semaste    {
620254721Semaste        m_action = eFileActionOpen;
621254721Semaste        m_fd = fd;
622254721Semaste        if (read && write)
623254721Semaste            m_arg = O_NOCTTY | O_CREAT | O_RDWR;
624254721Semaste        else if (read)
625254721Semaste            m_arg = O_NOCTTY | O_RDONLY;
626254721Semaste        else
627254721Semaste            m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
628254721Semaste        m_path.assign (path);
629254721Semaste        return true;
630254721Semaste    }
631254721Semaste    else
632254721Semaste    {
633254721Semaste        Clear();
634254721Semaste    }
635254721Semaste    return false;
636254721Semaste}
637254721Semaste
638254721Semastebool
639254721SemasteProcessLaunchInfo::FileAction::Close (int fd)
640254721Semaste{
641254721Semaste    Clear();
642254721Semaste    if (fd >= 0)
643254721Semaste    {
644254721Semaste        m_action = eFileActionClose;
645254721Semaste        m_fd = fd;
646254721Semaste    }
647254721Semaste    return m_fd >= 0;
648254721Semaste}
649254721Semaste
650254721Semaste
651254721Semastebool
652254721SemasteProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
653254721Semaste{
654254721Semaste    Clear();
655254721Semaste    if (fd >= 0 && dup_fd >= 0)
656254721Semaste    {
657254721Semaste        m_action = eFileActionDuplicate;
658254721Semaste        m_fd = fd;
659254721Semaste        m_arg = dup_fd;
660254721Semaste    }
661254721Semaste    return m_fd >= 0;
662254721Semaste}
663254721Semaste
664254721Semaste
665254721Semaste
666254721Semastebool
667254721SemasteProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
668254721Semaste                                                        const FileAction *info,
669254721Semaste                                                        Log *log,
670254721Semaste                                                        Error& error)
671254721Semaste{
672254721Semaste    if (info == NULL)
673254721Semaste        return false;
674254721Semaste
675254721Semaste    switch (info->m_action)
676254721Semaste    {
677254721Semaste        case eFileActionNone:
678254721Semaste            error.Clear();
679254721Semaste            break;
680254721Semaste
681254721Semaste        case eFileActionClose:
682254721Semaste            if (info->m_fd == -1)
683254721Semaste                error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
684254721Semaste            else
685254721Semaste            {
686254721Semaste                error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
687254721Semaste                                eErrorTypePOSIX);
688254721Semaste                if (log && (error.Fail() || log))
689254721Semaste                    error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
690254721Semaste                                   file_actions, info->m_fd);
691254721Semaste            }
692254721Semaste            break;
693254721Semaste
694254721Semaste        case eFileActionDuplicate:
695254721Semaste            if (info->m_fd == -1)
696254721Semaste                error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
697254721Semaste            else if (info->m_arg == -1)
698254721Semaste                error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
699254721Semaste            else
700254721Semaste            {
701254721Semaste                error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
702254721Semaste                                eErrorTypePOSIX);
703254721Semaste                if (log && (error.Fail() || log))
704254721Semaste                    error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
705254721Semaste                                   file_actions, info->m_fd, info->m_arg);
706254721Semaste            }
707254721Semaste            break;
708254721Semaste
709254721Semaste        case eFileActionOpen:
710254721Semaste            if (info->m_fd == -1)
711254721Semaste                error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
712254721Semaste            else
713254721Semaste            {
714254721Semaste                int oflag = info->m_arg;
715254721Semaste
716254721Semaste                mode_t mode = 0;
717254721Semaste
718254721Semaste                if (oflag & O_CREAT)
719254721Semaste                    mode = 0640;
720254721Semaste
721254721Semaste                error.SetError (::posix_spawn_file_actions_addopen (file_actions,
722254721Semaste                                                                    info->m_fd,
723254721Semaste                                                                    info->m_path.c_str(),
724254721Semaste                                                                    oflag,
725254721Semaste                                                                    mode),
726254721Semaste                                eErrorTypePOSIX);
727254721Semaste                if (error.Fail() || log)
728254721Semaste                    error.PutToLog(log,
729254721Semaste                                   "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
730254721Semaste                                   file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
731254721Semaste            }
732254721Semaste            break;
733254721Semaste    }
734254721Semaste    return error.Success();
735254721Semaste}
736254721Semaste
737254721SemasteError
738254721SemasteProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
739254721Semaste{
740254721Semaste    Error error;
741254721Semaste    const int short_option = m_getopt_table[option_idx].val;
742254721Semaste
743254721Semaste    switch (short_option)
744254721Semaste    {
745254721Semaste        case 's':   // Stop at program entry point
746254721Semaste            launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
747254721Semaste            break;
748254721Semaste
749254721Semaste        case 'i':   // STDIN for read only
750254721Semaste            {
751254721Semaste                ProcessLaunchInfo::FileAction action;
752254721Semaste                if (action.Open (STDIN_FILENO, option_arg, true, false))
753254721Semaste                    launch_info.AppendFileAction (action);
754254721Semaste            }
755254721Semaste            break;
756254721Semaste
757254721Semaste        case 'o':   // Open STDOUT for write only
758254721Semaste            {
759254721Semaste                ProcessLaunchInfo::FileAction action;
760254721Semaste                if (action.Open (STDOUT_FILENO, option_arg, false, true))
761254721Semaste                    launch_info.AppendFileAction (action);
762254721Semaste            }
763254721Semaste            break;
764254721Semaste
765254721Semaste        case 'e':   // STDERR for write only
766254721Semaste            {
767254721Semaste                ProcessLaunchInfo::FileAction action;
768254721Semaste                if (action.Open (STDERR_FILENO, option_arg, false, true))
769254721Semaste                    launch_info.AppendFileAction (action);
770254721Semaste            }
771254721Semaste            break;
772254721Semaste
773254721Semaste
774254721Semaste        case 'p':   // Process plug-in name
775254721Semaste            launch_info.SetProcessPluginName (option_arg);
776254721Semaste            break;
777254721Semaste
778254721Semaste        case 'n':   // Disable STDIO
779254721Semaste            {
780254721Semaste                ProcessLaunchInfo::FileAction action;
781254721Semaste                if (action.Open (STDIN_FILENO, "/dev/null", true, false))
782254721Semaste                    launch_info.AppendFileAction (action);
783254721Semaste                if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
784254721Semaste                    launch_info.AppendFileAction (action);
785254721Semaste                if (action.Open (STDERR_FILENO, "/dev/null", false, true))
786254721Semaste                    launch_info.AppendFileAction (action);
787254721Semaste            }
788254721Semaste            break;
789254721Semaste
790254721Semaste        case 'w':
791254721Semaste            launch_info.SetWorkingDirectory (option_arg);
792254721Semaste            break;
793254721Semaste
794254721Semaste        case 't':   // Open process in new terminal window
795254721Semaste            launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
796254721Semaste            break;
797254721Semaste
798254721Semaste        case 'a':
799254721Semaste            if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
800254721Semaste                launch_info.GetArchitecture().SetTriple (option_arg);
801254721Semaste            break;
802254721Semaste
803254721Semaste        case 'A':
804254721Semaste            launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
805254721Semaste            break;
806254721Semaste
807254721Semaste        case 'c':
808254721Semaste            if (option_arg && option_arg[0])
809254721Semaste                launch_info.SetShell (option_arg);
810254721Semaste            else
811254721Semaste                launch_info.SetShell ("/bin/bash");
812254721Semaste            break;
813254721Semaste
814254721Semaste        case 'v':
815254721Semaste            launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
816254721Semaste            break;
817254721Semaste
818254721Semaste        default:
819254721Semaste            error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
820254721Semaste            break;
821254721Semaste
822254721Semaste    }
823254721Semaste    return error;
824254721Semaste}
825254721Semaste
826254721SemasteOptionDefinition
827254721SemasteProcessLaunchCommandOptions::g_option_table[] =
828254721Semaste{
829254721Semaste{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument,       NULL, 0, eArgTypeNone,          "Stop at the entry point of the program when launching a process."},
830254721Semaste{ LLDB_OPT_SET_ALL, false, "disable-aslr",  'A', no_argument,       NULL, 0, eArgTypeNone,          "Disable address space layout randomization when launching a process."},
831254721Semaste{ LLDB_OPT_SET_ALL, false, "plugin",        'p', required_argument, NULL, 0, eArgTypePlugin,        "Name of the process plugin you want to use."},
832254721Semaste{ LLDB_OPT_SET_ALL, false, "working-dir",   'w', required_argument, NULL, 0, eArgTypeDirectoryName,          "Set the current working directory to <path> when running the inferior."},
833254721Semaste{ LLDB_OPT_SET_ALL, false, "arch",          'a', required_argument, NULL, 0, eArgTypeArchitecture,  "Set the architecture for the process to launch when ambiguous."},
834254721Semaste{ LLDB_OPT_SET_ALL, false, "environment",   'v', required_argument, NULL, 0, eArgTypeNone,          "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
835254721Semaste{ LLDB_OPT_SET_ALL, false, "shell",         'c', optional_argument, NULL, 0, eArgTypeFilename,          "Run the process in a shell (not supported on all platforms)."},
836254721Semaste
837254721Semaste{ LLDB_OPT_SET_1  , false, "stdin",         'i', required_argument, NULL, 0, eArgTypeFilename,    "Redirect stdin for the process to <filename>."},
838254721Semaste{ LLDB_OPT_SET_1  , false, "stdout",        'o', required_argument, NULL, 0, eArgTypeFilename,    "Redirect stdout for the process to <filename>."},
839254721Semaste{ LLDB_OPT_SET_1  , false, "stderr",        'e', required_argument, NULL, 0, eArgTypeFilename,    "Redirect stderr for the process to <filename>."},
840254721Semaste
841254721Semaste{ LLDB_OPT_SET_2  , false, "tty",           't', no_argument,       NULL, 0, eArgTypeNone,    "Start the process in a terminal (not supported on all platforms)."},
842254721Semaste
843254721Semaste{ LLDB_OPT_SET_3  , false, "no-stdio",      'n', no_argument,       NULL, 0, eArgTypeNone,    "Do not set up for terminal I/O to go to running process."},
844254721Semaste
845254721Semaste{ 0               , false, NULL,             0,  0,                 NULL, 0, eArgTypeNone,    NULL }
846254721Semaste};
847254721Semaste
848254721Semaste
849254721Semaste
850254721Semastebool
851254721SemasteProcessInstanceInfoMatch::NameMatches (const char *process_name) const
852254721Semaste{
853254721Semaste    if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
854254721Semaste        return true;
855254721Semaste    const char *match_name = m_match_info.GetName();
856254721Semaste    if (!match_name)
857254721Semaste        return true;
858254721Semaste
859254721Semaste    return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
860254721Semaste}
861254721Semaste
862254721Semastebool
863254721SemasteProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
864254721Semaste{
865254721Semaste    if (!NameMatches (proc_info.GetName()))
866254721Semaste        return false;
867254721Semaste
868254721Semaste    if (m_match_info.ProcessIDIsValid() &&
869254721Semaste        m_match_info.GetProcessID() != proc_info.GetProcessID())
870254721Semaste        return false;
871254721Semaste
872254721Semaste    if (m_match_info.ParentProcessIDIsValid() &&
873254721Semaste        m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
874254721Semaste        return false;
875254721Semaste
876254721Semaste    if (m_match_info.UserIDIsValid () &&
877254721Semaste        m_match_info.GetUserID() != proc_info.GetUserID())
878254721Semaste        return false;
879254721Semaste
880254721Semaste    if (m_match_info.GroupIDIsValid () &&
881254721Semaste        m_match_info.GetGroupID() != proc_info.GetGroupID())
882254721Semaste        return false;
883254721Semaste
884254721Semaste    if (m_match_info.EffectiveUserIDIsValid () &&
885254721Semaste        m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
886254721Semaste        return false;
887254721Semaste
888254721Semaste    if (m_match_info.EffectiveGroupIDIsValid () &&
889254721Semaste        m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
890254721Semaste        return false;
891254721Semaste
892254721Semaste    if (m_match_info.GetArchitecture().IsValid() &&
893254721Semaste        !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
894254721Semaste        return false;
895254721Semaste    return true;
896254721Semaste}
897254721Semaste
898254721Semastebool
899254721SemasteProcessInstanceInfoMatch::MatchAllProcesses () const
900254721Semaste{
901254721Semaste    if (m_name_match_type != eNameMatchIgnore)
902254721Semaste        return false;
903254721Semaste
904254721Semaste    if (m_match_info.ProcessIDIsValid())
905254721Semaste        return false;
906254721Semaste
907254721Semaste    if (m_match_info.ParentProcessIDIsValid())
908254721Semaste        return false;
909254721Semaste
910254721Semaste    if (m_match_info.UserIDIsValid ())
911254721Semaste        return false;
912254721Semaste
913254721Semaste    if (m_match_info.GroupIDIsValid ())
914254721Semaste        return false;
915254721Semaste
916254721Semaste    if (m_match_info.EffectiveUserIDIsValid ())
917254721Semaste        return false;
918254721Semaste
919254721Semaste    if (m_match_info.EffectiveGroupIDIsValid ())
920254721Semaste        return false;
921254721Semaste
922254721Semaste    if (m_match_info.GetArchitecture().IsValid())
923254721Semaste        return false;
924254721Semaste
925254721Semaste    if (m_match_all_users)
926254721Semaste        return false;
927254721Semaste
928254721Semaste    return true;
929254721Semaste
930254721Semaste}
931254721Semaste
932254721Semastevoid
933254721SemasteProcessInstanceInfoMatch::Clear()
934254721Semaste{
935254721Semaste    m_match_info.Clear();
936254721Semaste    m_name_match_type = eNameMatchIgnore;
937254721Semaste    m_match_all_users = false;
938254721Semaste}
939254721Semaste
940254721SemasteProcessSP
941254721SemasteProcess::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
942254721Semaste{
943254721Semaste    static uint32_t g_process_unique_id = 0;
944254721Semaste
945254721Semaste    ProcessSP process_sp;
946254721Semaste    ProcessCreateInstance create_callback = NULL;
947254721Semaste    if (plugin_name)
948254721Semaste    {
949254721Semaste        ConstString const_plugin_name(plugin_name);
950254721Semaste        create_callback  = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
951254721Semaste        if (create_callback)
952254721Semaste        {
953254721Semaste            process_sp = create_callback(target, listener, crash_file_path);
954254721Semaste            if (process_sp)
955254721Semaste            {
956254721Semaste                if (process_sp->CanDebug(target, true))
957254721Semaste                {
958254721Semaste                    process_sp->m_process_unique_id = ++g_process_unique_id;
959254721Semaste                }
960254721Semaste                else
961254721Semaste                    process_sp.reset();
962254721Semaste            }
963254721Semaste        }
964254721Semaste    }
965254721Semaste    else
966254721Semaste    {
967254721Semaste        for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
968254721Semaste        {
969254721Semaste            process_sp = create_callback(target, listener, crash_file_path);
970254721Semaste            if (process_sp)
971254721Semaste            {
972254721Semaste                if (process_sp->CanDebug(target, false))
973254721Semaste                {
974254721Semaste                    process_sp->m_process_unique_id = ++g_process_unique_id;
975254721Semaste                    break;
976254721Semaste                }
977254721Semaste                else
978254721Semaste                    process_sp.reset();
979254721Semaste            }
980254721Semaste        }
981254721Semaste    }
982254721Semaste    return process_sp;
983254721Semaste}
984254721Semaste
985254721SemasteConstString &
986254721SemasteProcess::GetStaticBroadcasterClass ()
987254721Semaste{
988254721Semaste    static ConstString class_name ("lldb.process");
989254721Semaste    return class_name;
990254721Semaste}
991254721Semaste
992254721Semaste//----------------------------------------------------------------------
993254721Semaste// Process constructor
994254721Semaste//----------------------------------------------------------------------
995254721SemasteProcess::Process(Target &target, Listener &listener) :
996254721Semaste    ProcessProperties (false),
997254721Semaste    UserID (LLDB_INVALID_PROCESS_ID),
998254721Semaste    Broadcaster (&(target.GetDebugger()), "lldb.process"),
999254721Semaste    m_target (target),
1000254721Semaste    m_public_state (eStateUnloaded),
1001254721Semaste    m_private_state (eStateUnloaded),
1002254721Semaste    m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1003254721Semaste    m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
1004254721Semaste    m_private_state_listener ("lldb.process.internal_state_listener"),
1005254721Semaste    m_private_state_control_wait(),
1006254721Semaste    m_private_state_thread (LLDB_INVALID_HOST_THREAD),
1007254721Semaste    m_mod_id (),
1008254721Semaste    m_process_unique_id(0),
1009254721Semaste    m_thread_index_id (0),
1010254721Semaste    m_thread_id_to_index_id_map (),
1011254721Semaste    m_exit_status (-1),
1012254721Semaste    m_exit_string (),
1013254721Semaste    m_thread_mutex (Mutex::eMutexTypeRecursive),
1014254721Semaste    m_thread_list_real (this),
1015254721Semaste    m_thread_list (this),
1016254721Semaste    m_notifications (),
1017254721Semaste    m_image_tokens (),
1018254721Semaste    m_listener (listener),
1019254721Semaste    m_breakpoint_site_list (),
1020254721Semaste    m_dynamic_checkers_ap (),
1021254721Semaste    m_unix_signals (),
1022254721Semaste    m_abi_sp (),
1023254721Semaste    m_process_input_reader (),
1024254721Semaste    m_stdio_communication ("process.stdio"),
1025254721Semaste    m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
1026254721Semaste    m_stdout_data (),
1027254721Semaste    m_stderr_data (),
1028254721Semaste    m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1029254721Semaste    m_profile_data (),
1030254721Semaste    m_memory_cache (*this),
1031254721Semaste    m_allocated_memory_cache (*this),
1032254721Semaste    m_should_detach (false),
1033254721Semaste    m_next_event_action_ap(),
1034254721Semaste    m_public_run_lock (),
1035254721Semaste    m_private_run_lock (),
1036254721Semaste    m_currently_handling_event(false),
1037254721Semaste    m_finalize_called(false),
1038254721Semaste    m_clear_thread_plans_on_stop (false),
1039254721Semaste    m_last_broadcast_state (eStateInvalid),
1040254721Semaste    m_destroy_in_process (false),
1041254721Semaste    m_can_jit(eCanJITDontKnow)
1042254721Semaste{
1043254721Semaste    CheckInWithManager ();
1044254721Semaste
1045254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1046254721Semaste    if (log)
1047254721Semaste        log->Printf ("%p Process::Process()", this);
1048254721Semaste
1049254721Semaste    SetEventName (eBroadcastBitStateChanged, "state-changed");
1050254721Semaste    SetEventName (eBroadcastBitInterrupt, "interrupt");
1051254721Semaste    SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1052254721Semaste    SetEventName (eBroadcastBitSTDERR, "stderr-available");
1053254721Semaste    SetEventName (eBroadcastBitProfileData, "profile-data-available");
1054254721Semaste
1055254721Semaste    m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop  , "control-stop"  );
1056254721Semaste    m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1057254721Semaste    m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1058254721Semaste
1059254721Semaste    listener.StartListeningForEvents (this,
1060254721Semaste                                      eBroadcastBitStateChanged |
1061254721Semaste                                      eBroadcastBitInterrupt |
1062254721Semaste                                      eBroadcastBitSTDOUT |
1063254721Semaste                                      eBroadcastBitSTDERR |
1064254721Semaste                                      eBroadcastBitProfileData);
1065254721Semaste
1066254721Semaste    m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
1067254721Semaste                                                     eBroadcastBitStateChanged |
1068254721Semaste                                                     eBroadcastBitInterrupt);
1069254721Semaste
1070254721Semaste    m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1071254721Semaste                                                     eBroadcastInternalStateControlStop |
1072254721Semaste                                                     eBroadcastInternalStateControlPause |
1073254721Semaste                                                     eBroadcastInternalStateControlResume);
1074254721Semaste}
1075254721Semaste
1076254721Semaste//----------------------------------------------------------------------
1077254721Semaste// Destructor
1078254721Semaste//----------------------------------------------------------------------
1079254721SemasteProcess::~Process()
1080254721Semaste{
1081254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1082254721Semaste    if (log)
1083254721Semaste        log->Printf ("%p Process::~Process()", this);
1084254721Semaste    StopPrivateStateThread();
1085254721Semaste}
1086254721Semaste
1087254721Semasteconst ProcessPropertiesSP &
1088254721SemasteProcess::GetGlobalProperties()
1089254721Semaste{
1090254721Semaste    static ProcessPropertiesSP g_settings_sp;
1091254721Semaste    if (!g_settings_sp)
1092254721Semaste        g_settings_sp.reset (new ProcessProperties (true));
1093254721Semaste    return g_settings_sp;
1094254721Semaste}
1095254721Semaste
1096254721Semastevoid
1097254721SemasteProcess::Finalize()
1098254721Semaste{
1099254721Semaste    switch (GetPrivateState())
1100254721Semaste    {
1101254721Semaste        case eStateConnected:
1102254721Semaste        case eStateAttaching:
1103254721Semaste        case eStateLaunching:
1104254721Semaste        case eStateStopped:
1105254721Semaste        case eStateRunning:
1106254721Semaste        case eStateStepping:
1107254721Semaste        case eStateCrashed:
1108254721Semaste        case eStateSuspended:
1109254721Semaste            if (GetShouldDetach())
1110254721Semaste            {
1111254721Semaste                // FIXME: This will have to be a process setting:
1112254721Semaste                bool keep_stopped = false;
1113254721Semaste                Detach(keep_stopped);
1114254721Semaste            }
1115254721Semaste            else
1116254721Semaste                Destroy();
1117254721Semaste            break;
1118254721Semaste
1119254721Semaste        case eStateInvalid:
1120254721Semaste        case eStateUnloaded:
1121254721Semaste        case eStateDetached:
1122254721Semaste        case eStateExited:
1123254721Semaste            break;
1124254721Semaste    }
1125254721Semaste
1126254721Semaste    // Clear our broadcaster before we proceed with destroying
1127254721Semaste    Broadcaster::Clear();
1128254721Semaste
1129254721Semaste    // Do any cleanup needed prior to being destructed... Subclasses
1130254721Semaste    // that override this method should call this superclass method as well.
1131254721Semaste
1132254721Semaste    // We need to destroy the loader before the derived Process class gets destroyed
1133254721Semaste    // since it is very likely that undoing the loader will require access to the real process.
1134254721Semaste    m_dynamic_checkers_ap.reset();
1135254721Semaste    m_abi_sp.reset();
1136254721Semaste    m_os_ap.reset();
1137254721Semaste    m_dyld_ap.reset();
1138254721Semaste    m_thread_list_real.Destroy();
1139254721Semaste    m_thread_list.Destroy();
1140254721Semaste    std::vector<Notifications> empty_notifications;
1141254721Semaste    m_notifications.swap(empty_notifications);
1142254721Semaste    m_image_tokens.clear();
1143254721Semaste    m_memory_cache.Clear();
1144254721Semaste    m_allocated_memory_cache.Clear();
1145254721Semaste    m_language_runtimes.clear();
1146254721Semaste    m_next_event_action_ap.reset();
1147254721Semaste//#ifdef LLDB_CONFIGURATION_DEBUG
1148254721Semaste//    StreamFile s(stdout, false);
1149254721Semaste//    EventSP event_sp;
1150254721Semaste//    while (m_private_state_listener.GetNextEvent(event_sp))
1151254721Semaste//    {
1152254721Semaste//        event_sp->Dump (&s);
1153254721Semaste//        s.EOL();
1154254721Semaste//    }
1155254721Semaste//#endif
1156254721Semaste    // We have to be very careful here as the m_private_state_listener might
1157254721Semaste    // contain events that have ProcessSP values in them which can keep this
1158254721Semaste    // process around forever. These events need to be cleared out.
1159254721Semaste    m_private_state_listener.Clear();
1160254721Semaste    m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1161254721Semaste    m_public_run_lock.SetStopped();
1162254721Semaste    m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1163254721Semaste    m_private_run_lock.SetStopped();
1164254721Semaste    m_finalize_called = true;
1165254721Semaste}
1166254721Semaste
1167254721Semastevoid
1168254721SemasteProcess::RegisterNotificationCallbacks (const Notifications& callbacks)
1169254721Semaste{
1170254721Semaste    m_notifications.push_back(callbacks);
1171254721Semaste    if (callbacks.initialize != NULL)
1172254721Semaste        callbacks.initialize (callbacks.baton, this);
1173254721Semaste}
1174254721Semaste
1175254721Semastebool
1176254721SemasteProcess::UnregisterNotificationCallbacks(const Notifications& callbacks)
1177254721Semaste{
1178254721Semaste    std::vector<Notifications>::iterator pos, end = m_notifications.end();
1179254721Semaste    for (pos = m_notifications.begin(); pos != end; ++pos)
1180254721Semaste    {
1181254721Semaste        if (pos->baton == callbacks.baton &&
1182254721Semaste            pos->initialize == callbacks.initialize &&
1183254721Semaste            pos->process_state_changed == callbacks.process_state_changed)
1184254721Semaste        {
1185254721Semaste            m_notifications.erase(pos);
1186254721Semaste            return true;
1187254721Semaste        }
1188254721Semaste    }
1189254721Semaste    return false;
1190254721Semaste}
1191254721Semaste
1192254721Semastevoid
1193254721SemasteProcess::SynchronouslyNotifyStateChanged (StateType state)
1194254721Semaste{
1195254721Semaste    std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1196254721Semaste    for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1197254721Semaste    {
1198254721Semaste        if (notification_pos->process_state_changed)
1199254721Semaste            notification_pos->process_state_changed (notification_pos->baton, this, state);
1200254721Semaste    }
1201254721Semaste}
1202254721Semaste
1203254721Semaste// FIXME: We need to do some work on events before the general Listener sees them.
1204254721Semaste// For instance if we are continuing from a breakpoint, we need to ensure that we do
1205254721Semaste// the little "insert real insn, step & stop" trick.  But we can't do that when the
1206254721Semaste// event is delivered by the broadcaster - since that is done on the thread that is
1207254721Semaste// waiting for new events, so if we needed more than one event for our handling, we would
1208254721Semaste// stall.  So instead we do it when we fetch the event off of the queue.
1209254721Semaste//
1210254721Semaste
1211254721SemasteStateType
1212254721SemasteProcess::GetNextEvent (EventSP &event_sp)
1213254721Semaste{
1214254721Semaste    StateType state = eStateInvalid;
1215254721Semaste
1216254721Semaste    if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1217254721Semaste        state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1218254721Semaste
1219254721Semaste    return state;
1220254721Semaste}
1221254721Semaste
1222254721Semaste
1223254721SemasteStateType
1224254721SemasteProcess::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
1225254721Semaste{
1226254721Semaste    // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1227254721Semaste    // We have to actually check each event, and in the case of a stopped event check the restarted flag
1228254721Semaste    // on the event.
1229254721Semaste    if (event_sp_ptr)
1230254721Semaste        event_sp_ptr->reset();
1231254721Semaste    StateType state = GetState();
1232254721Semaste    // If we are exited or detached, we won't ever get back to any
1233254721Semaste    // other valid state...
1234254721Semaste    if (state == eStateDetached || state == eStateExited)
1235254721Semaste        return state;
1236254721Semaste
1237254721Semaste    while (state != eStateInvalid)
1238254721Semaste    {
1239254721Semaste        EventSP event_sp;
1240254721Semaste        state = WaitForStateChangedEvents (timeout, event_sp);
1241254721Semaste        if (event_sp_ptr && event_sp)
1242254721Semaste            *event_sp_ptr = event_sp;
1243254721Semaste
1244254721Semaste        switch (state)
1245254721Semaste        {
1246254721Semaste        case eStateCrashed:
1247254721Semaste        case eStateDetached:
1248254721Semaste        case eStateExited:
1249254721Semaste        case eStateUnloaded:
1250254721Semaste            return state;
1251254721Semaste        case eStateStopped:
1252254721Semaste            if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1253254721Semaste                continue;
1254254721Semaste            else
1255254721Semaste                return state;
1256254721Semaste        default:
1257254721Semaste            continue;
1258254721Semaste        }
1259254721Semaste    }
1260254721Semaste    return state;
1261254721Semaste}
1262254721Semaste
1263254721Semaste
1264254721SemasteStateType
1265254721SemasteProcess::WaitForState
1266254721Semaste(
1267254721Semaste    const TimeValue *timeout,
1268254721Semaste    const StateType *match_states, const uint32_t num_match_states
1269254721Semaste)
1270254721Semaste{
1271254721Semaste    EventSP event_sp;
1272254721Semaste    uint32_t i;
1273254721Semaste    StateType state = GetState();
1274254721Semaste    while (state != eStateInvalid)
1275254721Semaste    {
1276254721Semaste        // If we are exited or detached, we won't ever get back to any
1277254721Semaste        // other valid state...
1278254721Semaste        if (state == eStateDetached || state == eStateExited)
1279254721Semaste            return state;
1280254721Semaste
1281254721Semaste        state = WaitForStateChangedEvents (timeout, event_sp);
1282254721Semaste
1283254721Semaste        for (i=0; i<num_match_states; ++i)
1284254721Semaste        {
1285254721Semaste            if (match_states[i] == state)
1286254721Semaste                return state;
1287254721Semaste        }
1288254721Semaste    }
1289254721Semaste    return state;
1290254721Semaste}
1291254721Semaste
1292254721Semastebool
1293254721SemasteProcess::HijackProcessEvents (Listener *listener)
1294254721Semaste{
1295254721Semaste    if (listener != NULL)
1296254721Semaste    {
1297254721Semaste        return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1298254721Semaste    }
1299254721Semaste    else
1300254721Semaste        return false;
1301254721Semaste}
1302254721Semaste
1303254721Semastevoid
1304254721SemasteProcess::RestoreProcessEvents ()
1305254721Semaste{
1306254721Semaste    RestoreBroadcaster();
1307254721Semaste}
1308254721Semaste
1309254721Semastebool
1310254721SemasteProcess::HijackPrivateProcessEvents (Listener *listener)
1311254721Semaste{
1312254721Semaste    if (listener != NULL)
1313254721Semaste    {
1314254721Semaste        return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1315254721Semaste    }
1316254721Semaste    else
1317254721Semaste        return false;
1318254721Semaste}
1319254721Semaste
1320254721Semastevoid
1321254721SemasteProcess::RestorePrivateProcessEvents ()
1322254721Semaste{
1323254721Semaste    m_private_state_broadcaster.RestoreBroadcaster();
1324254721Semaste}
1325254721Semaste
1326254721SemasteStateType
1327254721SemasteProcess::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1328254721Semaste{
1329254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1330254721Semaste
1331254721Semaste    if (log)
1332254721Semaste        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1333254721Semaste
1334254721Semaste    StateType state = eStateInvalid;
1335254721Semaste    if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1336254721Semaste                                                       this,
1337254721Semaste                                                       eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1338254721Semaste                                                       event_sp))
1339254721Semaste    {
1340254721Semaste        if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1341254721Semaste            state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1342254721Semaste        else if (log)
1343254721Semaste            log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1344254721Semaste    }
1345254721Semaste
1346254721Semaste    if (log)
1347254721Semaste        log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1348254721Semaste                     __FUNCTION__,
1349254721Semaste                     timeout,
1350254721Semaste                     StateAsCString(state));
1351254721Semaste    return state;
1352254721Semaste}
1353254721Semaste
1354254721SemasteEvent *
1355254721SemasteProcess::PeekAtStateChangedEvents ()
1356254721Semaste{
1357254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1358254721Semaste
1359254721Semaste    if (log)
1360254721Semaste        log->Printf ("Process::%s...", __FUNCTION__);
1361254721Semaste
1362254721Semaste    Event *event_ptr;
1363254721Semaste    event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1364254721Semaste                                                                  eBroadcastBitStateChanged);
1365254721Semaste    if (log)
1366254721Semaste    {
1367254721Semaste        if (event_ptr)
1368254721Semaste        {
1369254721Semaste            log->Printf ("Process::%s (event_ptr) => %s",
1370254721Semaste                         __FUNCTION__,
1371254721Semaste                         StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1372254721Semaste        }
1373254721Semaste        else
1374254721Semaste        {
1375254721Semaste            log->Printf ("Process::%s no events found",
1376254721Semaste                         __FUNCTION__);
1377254721Semaste        }
1378254721Semaste    }
1379254721Semaste    return event_ptr;
1380254721Semaste}
1381254721Semaste
1382254721SemasteStateType
1383254721SemasteProcess::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1384254721Semaste{
1385254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1386254721Semaste
1387254721Semaste    if (log)
1388254721Semaste        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1389254721Semaste
1390254721Semaste    StateType state = eStateInvalid;
1391254721Semaste    if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1392254721Semaste                                                                     &m_private_state_broadcaster,
1393254721Semaste                                                                     eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1394254721Semaste                                                                     event_sp))
1395254721Semaste        if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1396254721Semaste            state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1397254721Semaste
1398254721Semaste    // This is a bit of a hack, but when we wait here we could very well return
1399254721Semaste    // to the command-line, and that could disable the log, which would render the
1400254721Semaste    // log we got above invalid.
1401254721Semaste    if (log)
1402254721Semaste    {
1403254721Semaste        if (state == eStateInvalid)
1404254721Semaste            log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1405254721Semaste        else
1406254721Semaste            log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1407254721Semaste    }
1408254721Semaste    return state;
1409254721Semaste}
1410254721Semaste
1411254721Semastebool
1412254721SemasteProcess::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1413254721Semaste{
1414254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1415254721Semaste
1416254721Semaste    if (log)
1417254721Semaste        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1418254721Semaste
1419254721Semaste    if (control_only)
1420254721Semaste        return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1421254721Semaste    else
1422254721Semaste        return m_private_state_listener.WaitForEvent(timeout, event_sp);
1423254721Semaste}
1424254721Semaste
1425254721Semastebool
1426254721SemasteProcess::IsRunning () const
1427254721Semaste{
1428254721Semaste    return StateIsRunningState (m_public_state.GetValue());
1429254721Semaste}
1430254721Semaste
1431254721Semasteint
1432254721SemasteProcess::GetExitStatus ()
1433254721Semaste{
1434254721Semaste    if (m_public_state.GetValue() == eStateExited)
1435254721Semaste        return m_exit_status;
1436254721Semaste    return -1;
1437254721Semaste}
1438254721Semaste
1439254721Semaste
1440254721Semasteconst char *
1441254721SemasteProcess::GetExitDescription ()
1442254721Semaste{
1443254721Semaste    if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1444254721Semaste        return m_exit_string.c_str();
1445254721Semaste    return NULL;
1446254721Semaste}
1447254721Semaste
1448254721Semastebool
1449254721SemasteProcess::SetExitStatus (int status, const char *cstr)
1450254721Semaste{
1451254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1452254721Semaste    if (log)
1453254721Semaste        log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1454254721Semaste                    status, status,
1455254721Semaste                    cstr ? "\"" : "",
1456254721Semaste                    cstr ? cstr : "NULL",
1457254721Semaste                    cstr ? "\"" : "");
1458254721Semaste
1459254721Semaste    // We were already in the exited state
1460254721Semaste    if (m_private_state.GetValue() == eStateExited)
1461254721Semaste    {
1462254721Semaste        if (log)
1463254721Semaste            log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
1464254721Semaste        return false;
1465254721Semaste    }
1466254721Semaste
1467254721Semaste    m_exit_status = status;
1468254721Semaste    if (cstr)
1469254721Semaste        m_exit_string = cstr;
1470254721Semaste    else
1471254721Semaste        m_exit_string.clear();
1472254721Semaste
1473254721Semaste    DidExit ();
1474254721Semaste
1475254721Semaste    SetPrivateState (eStateExited);
1476254721Semaste    return true;
1477254721Semaste}
1478254721Semaste
1479254721Semaste// This static callback can be used to watch for local child processes on
1480254721Semaste// the current host. The the child process exits, the process will be
1481254721Semaste// found in the global target list (we want to be completely sure that the
1482254721Semaste// lldb_private::Process doesn't go away before we can deliver the signal.
1483254721Semastebool
1484254721SemasteProcess::SetProcessExitStatus (void *callback_baton,
1485254721Semaste                               lldb::pid_t pid,
1486254721Semaste                               bool exited,
1487254721Semaste                               int signo,          // Zero for no signal
1488254721Semaste                               int exit_status     // Exit value of process if signal is zero
1489254721Semaste)
1490254721Semaste{
1491254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1492254721Semaste    if (log)
1493254721Semaste        log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
1494254721Semaste                     callback_baton,
1495254721Semaste                     pid,
1496254721Semaste                     exited,
1497254721Semaste                     signo,
1498254721Semaste                     exit_status);
1499254721Semaste
1500254721Semaste    if (exited)
1501254721Semaste    {
1502254721Semaste        TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
1503254721Semaste        if (target_sp)
1504254721Semaste        {
1505254721Semaste            ProcessSP process_sp (target_sp->GetProcessSP());
1506254721Semaste            if (process_sp)
1507254721Semaste            {
1508254721Semaste                const char *signal_cstr = NULL;
1509254721Semaste                if (signo)
1510254721Semaste                    signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1511254721Semaste
1512254721Semaste                process_sp->SetExitStatus (exit_status, signal_cstr);
1513254721Semaste            }
1514254721Semaste        }
1515254721Semaste        return true;
1516254721Semaste    }
1517254721Semaste    return false;
1518254721Semaste}
1519254721Semaste
1520254721Semaste
1521254721Semastevoid
1522254721SemasteProcess::UpdateThreadListIfNeeded ()
1523254721Semaste{
1524254721Semaste    const uint32_t stop_id = GetStopID();
1525254721Semaste    if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1526254721Semaste    {
1527254721Semaste        const StateType state = GetPrivateState();
1528254721Semaste        if (StateIsStoppedState (state, true))
1529254721Semaste        {
1530254721Semaste            Mutex::Locker locker (m_thread_list.GetMutex ());
1531254721Semaste            // m_thread_list does have its own mutex, but we need to
1532254721Semaste            // hold onto the mutex between the call to UpdateThreadList(...)
1533254721Semaste            // and the os->UpdateThreadList(...) so it doesn't change on us
1534254721Semaste            ThreadList &old_thread_list = m_thread_list;
1535254721Semaste            ThreadList real_thread_list(this);
1536254721Semaste            ThreadList new_thread_list(this);
1537254721Semaste            // Always update the thread list with the protocol specific
1538254721Semaste            // thread list, but only update if "true" is returned
1539254721Semaste            if (UpdateThreadList (m_thread_list_real, real_thread_list))
1540254721Semaste            {
1541254721Semaste                // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1542254721Semaste                // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1543254721Semaste                // shutting us down, causing a deadlock.
1544254721Semaste                if (!m_destroy_in_process)
1545254721Semaste                {
1546254721Semaste                    OperatingSystem *os = GetOperatingSystem ();
1547254721Semaste                    if (os)
1548254721Semaste                    {
1549254721Semaste                        // Clear any old backing threads where memory threads might have been
1550254721Semaste                        // backed by actual threads from the lldb_private::Process subclass
1551254721Semaste                        size_t num_old_threads = old_thread_list.GetSize(false);
1552254721Semaste                        for (size_t i=0; i<num_old_threads; ++i)
1553254721Semaste                            old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1554254721Semaste
1555254721Semaste                        // Now let the OperatingSystem plug-in update the thread list
1556254721Semaste                        os->UpdateThreadList (old_thread_list,  // Old list full of threads created by OS plug-in
1557254721Semaste                                              real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1558254721Semaste                                              new_thread_list); // The new thread list that we will show to the user that gets filled in
1559254721Semaste                    }
1560254721Semaste                    else
1561254721Semaste                    {
1562254721Semaste                        // No OS plug-in, the new thread list is the same as the real thread list
1563254721Semaste                        new_thread_list = real_thread_list;
1564254721Semaste                    }
1565254721Semaste                }
1566254721Semaste
1567254721Semaste                m_thread_list_real.Update(real_thread_list);
1568254721Semaste                m_thread_list.Update (new_thread_list);
1569254721Semaste                m_thread_list.SetStopID (stop_id);
1570254721Semaste            }
1571254721Semaste        }
1572254721Semaste    }
1573254721Semaste}
1574254721Semaste
1575254721SemasteThreadSP
1576254721SemasteProcess::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1577254721Semaste{
1578254721Semaste    OperatingSystem *os = GetOperatingSystem ();
1579254721Semaste    if (os)
1580254721Semaste        return os->CreateThread(tid, context);
1581254721Semaste    return ThreadSP();
1582254721Semaste}
1583254721Semaste
1584254721Semasteuint32_t
1585254721SemasteProcess::GetNextThreadIndexID (uint64_t thread_id)
1586254721Semaste{
1587254721Semaste    return AssignIndexIDToThread(thread_id);
1588254721Semaste}
1589254721Semaste
1590254721Semastebool
1591254721SemasteProcess::HasAssignedIndexIDToThread(uint64_t thread_id)
1592254721Semaste{
1593254721Semaste    std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1594254721Semaste    if (iterator == m_thread_id_to_index_id_map.end())
1595254721Semaste    {
1596254721Semaste        return false;
1597254721Semaste    }
1598254721Semaste    else
1599254721Semaste    {
1600254721Semaste        return true;
1601254721Semaste    }
1602254721Semaste}
1603254721Semaste
1604254721Semasteuint32_t
1605254721SemasteProcess::AssignIndexIDToThread(uint64_t thread_id)
1606254721Semaste{
1607254721Semaste    uint32_t result = 0;
1608254721Semaste    std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1609254721Semaste    if (iterator == m_thread_id_to_index_id_map.end())
1610254721Semaste    {
1611254721Semaste        result = ++m_thread_index_id;
1612254721Semaste        m_thread_id_to_index_id_map[thread_id] = result;
1613254721Semaste    }
1614254721Semaste    else
1615254721Semaste    {
1616254721Semaste        result = iterator->second;
1617254721Semaste    }
1618254721Semaste
1619254721Semaste    return result;
1620254721Semaste}
1621254721Semaste
1622254721SemasteStateType
1623254721SemasteProcess::GetState()
1624254721Semaste{
1625254721Semaste    // If any other threads access this we will need a mutex for it
1626254721Semaste    return m_public_state.GetValue ();
1627254721Semaste}
1628254721Semaste
1629254721Semastevoid
1630254721SemasteProcess::SetPublicState (StateType new_state, bool restarted)
1631254721Semaste{
1632254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1633254721Semaste    if (log)
1634254721Semaste        log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
1635254721Semaste    const StateType old_state = m_public_state.GetValue();
1636254721Semaste    m_public_state.SetValue (new_state);
1637254721Semaste
1638254721Semaste    // On the transition from Run to Stopped, we unlock the writer end of the
1639254721Semaste    // run lock.  The lock gets locked in Resume, which is the public API
1640254721Semaste    // to tell the program to run.
1641254721Semaste    if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1642254721Semaste    {
1643254721Semaste        if (new_state == eStateDetached)
1644254721Semaste        {
1645254721Semaste            if (log)
1646254721Semaste                log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1647254721Semaste            m_public_run_lock.SetStopped();
1648254721Semaste        }
1649254721Semaste        else
1650254721Semaste        {
1651254721Semaste            const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1652254721Semaste            const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1653254721Semaste            if ((old_state_is_stopped != new_state_is_stopped))
1654254721Semaste            {
1655254721Semaste                if (new_state_is_stopped && !restarted)
1656254721Semaste                {
1657254721Semaste                    if (log)
1658254721Semaste                        log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1659254721Semaste                    m_public_run_lock.SetStopped();
1660254721Semaste                }
1661254721Semaste            }
1662254721Semaste        }
1663254721Semaste    }
1664254721Semaste}
1665254721Semaste
1666254721SemasteError
1667254721SemasteProcess::Resume ()
1668254721Semaste{
1669254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1670254721Semaste    if (log)
1671254721Semaste        log->Printf("Process::Resume -- locking run lock");
1672254721Semaste    if (!m_public_run_lock.TrySetRunning())
1673254721Semaste    {
1674254721Semaste        Error error("Resume request failed - process still running.");
1675254721Semaste        if (log)
1676254721Semaste            log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1677254721Semaste        return error;
1678254721Semaste    }
1679254721Semaste    return PrivateResume();
1680254721Semaste}
1681254721Semaste
1682254721SemasteStateType
1683254721SemasteProcess::GetPrivateState ()
1684254721Semaste{
1685254721Semaste    return m_private_state.GetValue();
1686254721Semaste}
1687254721Semaste
1688254721Semastevoid
1689254721SemasteProcess::SetPrivateState (StateType new_state)
1690254721Semaste{
1691254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1692254721Semaste    bool state_changed = false;
1693254721Semaste
1694254721Semaste    if (log)
1695254721Semaste        log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1696254721Semaste
1697254721Semaste    Mutex::Locker thread_locker(m_thread_list.GetMutex());
1698254721Semaste    Mutex::Locker locker(m_private_state.GetMutex());
1699254721Semaste
1700254721Semaste    const StateType old_state = m_private_state.GetValueNoLock ();
1701254721Semaste    state_changed = old_state != new_state;
1702254721Semaste
1703254721Semaste    const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1704254721Semaste    const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1705254721Semaste    if (old_state_is_stopped != new_state_is_stopped)
1706254721Semaste    {
1707254721Semaste        if (new_state_is_stopped)
1708254721Semaste            m_private_run_lock.SetStopped();
1709254721Semaste        else
1710254721Semaste            m_private_run_lock.SetRunning();
1711254721Semaste    }
1712254721Semaste
1713254721Semaste    if (state_changed)
1714254721Semaste    {
1715254721Semaste        m_private_state.SetValueNoLock (new_state);
1716254721Semaste        if (StateIsStoppedState(new_state, false))
1717254721Semaste        {
1718254721Semaste            // Note, this currently assumes that all threads in the list
1719254721Semaste            // stop when the process stops.  In the future we will want to
1720254721Semaste            // support a debugging model where some threads continue to run
1721254721Semaste            // while others are stopped.  When that happens we will either need
1722254721Semaste            // a way for the thread list to identify which threads are stopping
1723254721Semaste            // or create a special thread list containing only threads which
1724254721Semaste            // actually stopped.
1725254721Semaste            //
1726254721Semaste            // The process plugin is responsible for managing the actual
1727254721Semaste            // behavior of the threads and should have stopped any threads
1728254721Semaste            // that are going to stop before we get here.
1729254721Semaste            m_thread_list.DidStop();
1730254721Semaste
1731254721Semaste            m_mod_id.BumpStopID();
1732254721Semaste            m_memory_cache.Clear();
1733254721Semaste            if (log)
1734254721Semaste                log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
1735254721Semaste        }
1736254721Semaste        // Use our target to get a shared pointer to ourselves...
1737254721Semaste        if (m_finalize_called && PrivateStateThreadIsValid() == false)
1738254721Semaste            BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1739254721Semaste        else
1740254721Semaste            m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1741254721Semaste    }
1742254721Semaste    else
1743254721Semaste    {
1744254721Semaste        if (log)
1745254721Semaste            log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
1746254721Semaste    }
1747254721Semaste}
1748254721Semaste
1749254721Semastevoid
1750254721SemasteProcess::SetRunningUserExpression (bool on)
1751254721Semaste{
1752254721Semaste    m_mod_id.SetRunningUserExpression (on);
1753254721Semaste}
1754254721Semaste
1755254721Semasteaddr_t
1756254721SemasteProcess::GetImageInfoAddress()
1757254721Semaste{
1758254721Semaste    return LLDB_INVALID_ADDRESS;
1759254721Semaste}
1760254721Semaste
1761254721Semaste//----------------------------------------------------------------------
1762254721Semaste// LoadImage
1763254721Semaste//
1764254721Semaste// This function provides a default implementation that works for most
1765254721Semaste// unix variants. Any Process subclasses that need to do shared library
1766254721Semaste// loading differently should override LoadImage and UnloadImage and
1767254721Semaste// do what is needed.
1768254721Semaste//----------------------------------------------------------------------
1769254721Semasteuint32_t
1770254721SemasteProcess::LoadImage (const FileSpec &image_spec, Error &error)
1771254721Semaste{
1772254721Semaste    char path[PATH_MAX];
1773254721Semaste    image_spec.GetPath(path, sizeof(path));
1774254721Semaste
1775254721Semaste    DynamicLoader *loader = GetDynamicLoader();
1776254721Semaste    if (loader)
1777254721Semaste    {
1778254721Semaste        error = loader->CanLoadImage();
1779254721Semaste        if (error.Fail())
1780254721Semaste            return LLDB_INVALID_IMAGE_TOKEN;
1781254721Semaste    }
1782254721Semaste
1783254721Semaste    if (error.Success())
1784254721Semaste    {
1785254721Semaste        ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1786254721Semaste
1787254721Semaste        if (thread_sp)
1788254721Semaste        {
1789254721Semaste            StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1790254721Semaste
1791254721Semaste            if (frame_sp)
1792254721Semaste            {
1793254721Semaste                ExecutionContext exe_ctx;
1794254721Semaste                frame_sp->CalculateExecutionContext (exe_ctx);
1795254721Semaste                const bool unwind_on_error = true;
1796254721Semaste                const bool ignore_breakpoints = true;
1797254721Semaste                StreamString expr;
1798254721Semaste                expr.Printf("dlopen (\"%s\", 2)", path);
1799254721Semaste                const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
1800254721Semaste                lldb::ValueObjectSP result_valobj_sp;
1801254721Semaste                ClangUserExpression::Evaluate (exe_ctx,
1802254721Semaste                                               eExecutionPolicyAlways,
1803254721Semaste                                               lldb::eLanguageTypeUnknown,
1804254721Semaste                                               ClangUserExpression::eResultTypeAny,
1805254721Semaste                                               unwind_on_error,
1806254721Semaste                                               ignore_breakpoints,
1807254721Semaste                                               expr.GetData(),
1808254721Semaste                                               prefix,
1809254721Semaste                                               result_valobj_sp,
1810254721Semaste                                               true,
1811254721Semaste                                               ClangUserExpression::kDefaultTimeout);
1812254721Semaste                error = result_valobj_sp->GetError();
1813254721Semaste                if (error.Success())
1814254721Semaste                {
1815254721Semaste                    Scalar scalar;
1816254721Semaste                    if (result_valobj_sp->ResolveValue (scalar))
1817254721Semaste                    {
1818254721Semaste                        addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1819254721Semaste                        if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1820254721Semaste                        {
1821254721Semaste                            uint32_t image_token = m_image_tokens.size();
1822254721Semaste                            m_image_tokens.push_back (image_ptr);
1823254721Semaste                            return image_token;
1824254721Semaste                        }
1825254721Semaste                    }
1826254721Semaste                }
1827254721Semaste            }
1828254721Semaste        }
1829254721Semaste    }
1830254721Semaste    if (!error.AsCString())
1831254721Semaste        error.SetErrorStringWithFormat("unable to load '%s'", path);
1832254721Semaste    return LLDB_INVALID_IMAGE_TOKEN;
1833254721Semaste}
1834254721Semaste
1835254721Semaste//----------------------------------------------------------------------
1836254721Semaste// UnloadImage
1837254721Semaste//
1838254721Semaste// This function provides a default implementation that works for most
1839254721Semaste// unix variants. Any Process subclasses that need to do shared library
1840254721Semaste// loading differently should override LoadImage and UnloadImage and
1841254721Semaste// do what is needed.
1842254721Semaste//----------------------------------------------------------------------
1843254721SemasteError
1844254721SemasteProcess::UnloadImage (uint32_t image_token)
1845254721Semaste{
1846254721Semaste    Error error;
1847254721Semaste    if (image_token < m_image_tokens.size())
1848254721Semaste    {
1849254721Semaste        const addr_t image_addr = m_image_tokens[image_token];
1850254721Semaste        if (image_addr == LLDB_INVALID_ADDRESS)
1851254721Semaste        {
1852254721Semaste            error.SetErrorString("image already unloaded");
1853254721Semaste        }
1854254721Semaste        else
1855254721Semaste        {
1856254721Semaste            DynamicLoader *loader = GetDynamicLoader();
1857254721Semaste            if (loader)
1858254721Semaste                error = loader->CanLoadImage();
1859254721Semaste
1860254721Semaste            if (error.Success())
1861254721Semaste            {
1862254721Semaste                ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1863254721Semaste
1864254721Semaste                if (thread_sp)
1865254721Semaste                {
1866254721Semaste                    StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1867254721Semaste
1868254721Semaste                    if (frame_sp)
1869254721Semaste                    {
1870254721Semaste                        ExecutionContext exe_ctx;
1871254721Semaste                        frame_sp->CalculateExecutionContext (exe_ctx);
1872254721Semaste                        const bool unwind_on_error = true;
1873254721Semaste                        const bool ignore_breakpoints = true;
1874254721Semaste                        StreamString expr;
1875254721Semaste                        expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
1876254721Semaste                        const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1877254721Semaste                        lldb::ValueObjectSP result_valobj_sp;
1878254721Semaste                        ClangUserExpression::Evaluate (exe_ctx,
1879254721Semaste                                                       eExecutionPolicyAlways,
1880254721Semaste                                                       lldb::eLanguageTypeUnknown,
1881254721Semaste                                                       ClangUserExpression::eResultTypeAny,
1882254721Semaste                                                       unwind_on_error,
1883254721Semaste                                                       ignore_breakpoints,
1884254721Semaste                                                       expr.GetData(),
1885254721Semaste                                                       prefix,
1886254721Semaste                                                       result_valobj_sp,
1887254721Semaste                                                       true,
1888254721Semaste                                                       ClangUserExpression::kDefaultTimeout);
1889254721Semaste                        if (result_valobj_sp->GetError().Success())
1890254721Semaste                        {
1891254721Semaste                            Scalar scalar;
1892254721Semaste                            if (result_valobj_sp->ResolveValue (scalar))
1893254721Semaste                            {
1894254721Semaste                                if (scalar.UInt(1))
1895254721Semaste                                {
1896254721Semaste                                    error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1897254721Semaste                                }
1898254721Semaste                                else
1899254721Semaste                                {
1900254721Semaste                                    m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1901254721Semaste                                }
1902254721Semaste                            }
1903254721Semaste                        }
1904254721Semaste                        else
1905254721Semaste                        {
1906254721Semaste                            error = result_valobj_sp->GetError();
1907254721Semaste                        }
1908254721Semaste                    }
1909254721Semaste                }
1910254721Semaste            }
1911254721Semaste        }
1912254721Semaste    }
1913254721Semaste    else
1914254721Semaste    {
1915254721Semaste        error.SetErrorString("invalid image token");
1916254721Semaste    }
1917254721Semaste    return error;
1918254721Semaste}
1919254721Semaste
1920254721Semasteconst lldb::ABISP &
1921254721SemasteProcess::GetABI()
1922254721Semaste{
1923254721Semaste    if (!m_abi_sp)
1924254721Semaste        m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1925254721Semaste    return m_abi_sp;
1926254721Semaste}
1927254721Semaste
1928254721SemasteLanguageRuntime *
1929254721SemasteProcess::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
1930254721Semaste{
1931254721Semaste    LanguageRuntimeCollection::iterator pos;
1932254721Semaste    pos = m_language_runtimes.find (language);
1933254721Semaste    if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
1934254721Semaste    {
1935254721Semaste        lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
1936254721Semaste
1937254721Semaste        m_language_runtimes[language] = runtime_sp;
1938254721Semaste        return runtime_sp.get();
1939254721Semaste    }
1940254721Semaste    else
1941254721Semaste        return (*pos).second.get();
1942254721Semaste}
1943254721Semaste
1944254721SemasteCPPLanguageRuntime *
1945254721SemasteProcess::GetCPPLanguageRuntime (bool retry_if_null)
1946254721Semaste{
1947254721Semaste    LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1948254721Semaste    if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1949254721Semaste        return static_cast<CPPLanguageRuntime *> (runtime);
1950254721Semaste    return NULL;
1951254721Semaste}
1952254721Semaste
1953254721SemasteObjCLanguageRuntime *
1954254721SemasteProcess::GetObjCLanguageRuntime (bool retry_if_null)
1955254721Semaste{
1956254721Semaste    LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1957254721Semaste    if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1958254721Semaste        return static_cast<ObjCLanguageRuntime *> (runtime);
1959254721Semaste    return NULL;
1960254721Semaste}
1961254721Semaste
1962254721Semastebool
1963254721SemasteProcess::IsPossibleDynamicValue (ValueObject& in_value)
1964254721Semaste{
1965254721Semaste    if (in_value.IsDynamic())
1966254721Semaste        return false;
1967254721Semaste    LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1968254721Semaste
1969254721Semaste    if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1970254721Semaste    {
1971254721Semaste        LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1972254721Semaste        return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1973254721Semaste    }
1974254721Semaste
1975254721Semaste    LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1976254721Semaste    if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1977254721Semaste        return true;
1978254721Semaste
1979254721Semaste    LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1980254721Semaste    return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1981254721Semaste}
1982254721Semaste
1983254721SemasteBreakpointSiteList &
1984254721SemasteProcess::GetBreakpointSiteList()
1985254721Semaste{
1986254721Semaste    return m_breakpoint_site_list;
1987254721Semaste}
1988254721Semaste
1989254721Semasteconst BreakpointSiteList &
1990254721SemasteProcess::GetBreakpointSiteList() const
1991254721Semaste{
1992254721Semaste    return m_breakpoint_site_list;
1993254721Semaste}
1994254721Semaste
1995254721Semaste
1996254721Semastevoid
1997254721SemasteProcess::DisableAllBreakpointSites ()
1998254721Semaste{
1999254721Semaste    m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2000254721Semaste//        bp_site->SetEnabled(true);
2001254721Semaste        DisableBreakpointSite(bp_site);
2002254721Semaste    });
2003254721Semaste}
2004254721Semaste
2005254721SemasteError
2006254721SemasteProcess::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2007254721Semaste{
2008254721Semaste    Error error (DisableBreakpointSiteByID (break_id));
2009254721Semaste
2010254721Semaste    if (error.Success())
2011254721Semaste        m_breakpoint_site_list.Remove(break_id);
2012254721Semaste
2013254721Semaste    return error;
2014254721Semaste}
2015254721Semaste
2016254721SemasteError
2017254721SemasteProcess::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2018254721Semaste{
2019254721Semaste    Error error;
2020254721Semaste    BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2021254721Semaste    if (bp_site_sp)
2022254721Semaste    {
2023254721Semaste        if (bp_site_sp->IsEnabled())
2024254721Semaste            error = DisableBreakpointSite (bp_site_sp.get());
2025254721Semaste    }
2026254721Semaste    else
2027254721Semaste    {
2028254721Semaste        error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2029254721Semaste    }
2030254721Semaste
2031254721Semaste    return error;
2032254721Semaste}
2033254721Semaste
2034254721SemasteError
2035254721SemasteProcess::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2036254721Semaste{
2037254721Semaste    Error error;
2038254721Semaste    BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2039254721Semaste    if (bp_site_sp)
2040254721Semaste    {
2041254721Semaste        if (!bp_site_sp->IsEnabled())
2042254721Semaste            error = EnableBreakpointSite (bp_site_sp.get());
2043254721Semaste    }
2044254721Semaste    else
2045254721Semaste    {
2046254721Semaste        error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2047254721Semaste    }
2048254721Semaste    return error;
2049254721Semaste}
2050254721Semaste
2051254721Semastelldb::break_id_t
2052254721SemasteProcess::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
2053254721Semaste{
2054254721Semaste    const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2055254721Semaste    if (load_addr != LLDB_INVALID_ADDRESS)
2056254721Semaste    {
2057254721Semaste        BreakpointSiteSP bp_site_sp;
2058254721Semaste
2059254721Semaste        // Look up this breakpoint site.  If it exists, then add this new owner, otherwise
2060254721Semaste        // create a new breakpoint site and add it.
2061254721Semaste
2062254721Semaste        bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2063254721Semaste
2064254721Semaste        if (bp_site_sp)
2065254721Semaste        {
2066254721Semaste            bp_site_sp->AddOwner (owner);
2067254721Semaste            owner->SetBreakpointSite (bp_site_sp);
2068254721Semaste            return bp_site_sp->GetID();
2069254721Semaste        }
2070254721Semaste        else
2071254721Semaste        {
2072254721Semaste            bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
2073254721Semaste            if (bp_site_sp)
2074254721Semaste            {
2075254721Semaste                if (EnableBreakpointSite (bp_site_sp.get()).Success())
2076254721Semaste                {
2077254721Semaste                    owner->SetBreakpointSite (bp_site_sp);
2078254721Semaste                    return m_breakpoint_site_list.Add (bp_site_sp);
2079254721Semaste                }
2080254721Semaste            }
2081254721Semaste        }
2082254721Semaste    }
2083254721Semaste    // We failed to enable the breakpoint
2084254721Semaste    return LLDB_INVALID_BREAK_ID;
2085254721Semaste
2086254721Semaste}
2087254721Semaste
2088254721Semastevoid
2089254721SemasteProcess::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2090254721Semaste{
2091254721Semaste    uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2092254721Semaste    if (num_owners == 0)
2093254721Semaste    {
2094254721Semaste        // Don't try to disable the site if we don't have a live process anymore.
2095254721Semaste        if (IsAlive())
2096254721Semaste            DisableBreakpointSite (bp_site_sp.get());
2097254721Semaste        m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2098254721Semaste    }
2099254721Semaste}
2100254721Semaste
2101254721Semaste
2102254721Semastesize_t
2103254721SemasteProcess::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2104254721Semaste{
2105254721Semaste    size_t bytes_removed = 0;
2106254721Semaste    BreakpointSiteList bp_sites_in_range;
2107254721Semaste
2108254721Semaste    if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
2109254721Semaste    {
2110254721Semaste        bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2111254721Semaste            if (bp_site->GetType() == BreakpointSite::eSoftware)
2112254721Semaste            {
2113254721Semaste                addr_t intersect_addr;
2114254721Semaste                size_t intersect_size;
2115254721Semaste                size_t opcode_offset;
2116254721Semaste                if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
2117254721Semaste                {
2118254721Semaste                    assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2119254721Semaste                    assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
2120254721Semaste                    assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2121254721Semaste                    size_t buf_offset = intersect_addr - bp_addr;
2122254721Semaste                    ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
2123254721Semaste                }
2124254721Semaste            }
2125254721Semaste        });
2126254721Semaste    }
2127254721Semaste    return bytes_removed;
2128254721Semaste}
2129254721Semaste
2130254721Semaste
2131254721Semaste
2132254721Semastesize_t
2133254721SemasteProcess::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2134254721Semaste{
2135254721Semaste    PlatformSP platform_sp (m_target.GetPlatform());
2136254721Semaste    if (platform_sp)
2137254721Semaste        return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2138254721Semaste    return 0;
2139254721Semaste}
2140254721Semaste
2141254721SemasteError
2142254721SemasteProcess::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2143254721Semaste{
2144254721Semaste    Error error;
2145254721Semaste    assert (bp_site != NULL);
2146254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2147254721Semaste    const addr_t bp_addr = bp_site->GetLoadAddress();
2148254721Semaste    if (log)
2149254721Semaste        log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
2150254721Semaste    if (bp_site->IsEnabled())
2151254721Semaste    {
2152254721Semaste        if (log)
2153254721Semaste            log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
2154254721Semaste        return error;
2155254721Semaste    }
2156254721Semaste
2157254721Semaste    if (bp_addr == LLDB_INVALID_ADDRESS)
2158254721Semaste    {
2159254721Semaste        error.SetErrorString("BreakpointSite contains an invalid load address.");
2160254721Semaste        return error;
2161254721Semaste    }
2162254721Semaste    // Ask the lldb::Process subclass to fill in the correct software breakpoint
2163254721Semaste    // trap for the breakpoint site
2164254721Semaste    const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2165254721Semaste
2166254721Semaste    if (bp_opcode_size == 0)
2167254721Semaste    {
2168254721Semaste        error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
2169254721Semaste    }
2170254721Semaste    else
2171254721Semaste    {
2172254721Semaste        const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2173254721Semaste
2174254721Semaste        if (bp_opcode_bytes == NULL)
2175254721Semaste        {
2176254721Semaste            error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2177254721Semaste            return error;
2178254721Semaste        }
2179254721Semaste
2180254721Semaste        // Save the original opcode by reading it
2181254721Semaste        if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2182254721Semaste        {
2183254721Semaste            // Write a software breakpoint in place of the original opcode
2184254721Semaste            if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2185254721Semaste            {
2186254721Semaste                uint8_t verify_bp_opcode_bytes[64];
2187254721Semaste                if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2188254721Semaste                {
2189254721Semaste                    if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2190254721Semaste                    {
2191254721Semaste                        bp_site->SetEnabled(true);
2192254721Semaste                        bp_site->SetType (BreakpointSite::eSoftware);
2193254721Semaste                        if (log)
2194254721Semaste                            log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
2195254721Semaste                                         bp_site->GetID(),
2196254721Semaste                                         (uint64_t)bp_addr);
2197254721Semaste                    }
2198254721Semaste                    else
2199254721Semaste                        error.SetErrorString("failed to verify the breakpoint trap in memory.");
2200254721Semaste                }
2201254721Semaste                else
2202254721Semaste                    error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2203254721Semaste            }
2204254721Semaste            else
2205254721Semaste                error.SetErrorString("Unable to write breakpoint trap to memory.");
2206254721Semaste        }
2207254721Semaste        else
2208254721Semaste            error.SetErrorString("Unable to read memory at breakpoint address.");
2209254721Semaste    }
2210254721Semaste    if (log && error.Fail())
2211254721Semaste        log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2212254721Semaste                     bp_site->GetID(),
2213254721Semaste                     (uint64_t)bp_addr,
2214254721Semaste                     error.AsCString());
2215254721Semaste    return error;
2216254721Semaste}
2217254721Semaste
2218254721SemasteError
2219254721SemasteProcess::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2220254721Semaste{
2221254721Semaste    Error error;
2222254721Semaste    assert (bp_site != NULL);
2223254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2224254721Semaste    addr_t bp_addr = bp_site->GetLoadAddress();
2225254721Semaste    lldb::user_id_t breakID = bp_site->GetID();
2226254721Semaste    if (log)
2227254721Semaste        log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
2228254721Semaste
2229254721Semaste    if (bp_site->IsHardware())
2230254721Semaste    {
2231254721Semaste        error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2232254721Semaste    }
2233254721Semaste    else if (bp_site->IsEnabled())
2234254721Semaste    {
2235254721Semaste        const size_t break_op_size = bp_site->GetByteSize();
2236254721Semaste        const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2237254721Semaste        if (break_op_size > 0)
2238254721Semaste        {
2239254721Semaste            // Clear a software breakoint instruction
2240254721Semaste            uint8_t curr_break_op[8];
2241254721Semaste            assert (break_op_size <= sizeof(curr_break_op));
2242254721Semaste            bool break_op_found = false;
2243254721Semaste
2244254721Semaste            // Read the breakpoint opcode
2245254721Semaste            if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2246254721Semaste            {
2247254721Semaste                bool verify = false;
2248254721Semaste                // Make sure we have the a breakpoint opcode exists at this address
2249254721Semaste                if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2250254721Semaste                {
2251254721Semaste                    break_op_found = true;
2252254721Semaste                    // We found a valid breakpoint opcode at this address, now restore
2253254721Semaste                    // the saved opcode.
2254254721Semaste                    if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2255254721Semaste                    {
2256254721Semaste                        verify = true;
2257254721Semaste                    }
2258254721Semaste                    else
2259254721Semaste                        error.SetErrorString("Memory write failed when restoring original opcode.");
2260254721Semaste                }
2261254721Semaste                else
2262254721Semaste                {
2263254721Semaste                    error.SetErrorString("Original breakpoint trap is no longer in memory.");
2264254721Semaste                    // Set verify to true and so we can check if the original opcode has already been restored
2265254721Semaste                    verify = true;
2266254721Semaste                }
2267254721Semaste
2268254721Semaste                if (verify)
2269254721Semaste                {
2270254721Semaste                    uint8_t verify_opcode[8];
2271254721Semaste                    assert (break_op_size < sizeof(verify_opcode));
2272254721Semaste                    // Verify that our original opcode made it back to the inferior
2273254721Semaste                    if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2274254721Semaste                    {
2275254721Semaste                        // compare the memory we just read with the original opcode
2276254721Semaste                        if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2277254721Semaste                        {
2278254721Semaste                            // SUCCESS
2279254721Semaste                            bp_site->SetEnabled(false);
2280254721Semaste                            if (log)
2281254721Semaste                                log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2282254721Semaste                            return error;
2283254721Semaste                        }
2284254721Semaste                        else
2285254721Semaste                        {
2286254721Semaste                            if (break_op_found)
2287254721Semaste                                error.SetErrorString("Failed to restore original opcode.");
2288254721Semaste                        }
2289254721Semaste                    }
2290254721Semaste                    else
2291254721Semaste                        error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2292254721Semaste                }
2293254721Semaste            }
2294254721Semaste            else
2295254721Semaste                error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2296254721Semaste        }
2297254721Semaste    }
2298254721Semaste    else
2299254721Semaste    {
2300254721Semaste        if (log)
2301254721Semaste            log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2302254721Semaste        return error;
2303254721Semaste    }
2304254721Semaste
2305254721Semaste    if (log)
2306254721Semaste        log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2307254721Semaste                     bp_site->GetID(),
2308254721Semaste                     (uint64_t)bp_addr,
2309254721Semaste                     error.AsCString());
2310254721Semaste    return error;
2311254721Semaste
2312254721Semaste}
2313254721Semaste
2314254721Semaste// Uncomment to verify memory caching works after making changes to caching code
2315254721Semaste//#define VERIFY_MEMORY_READS
2316254721Semaste
2317254721Semastesize_t
2318254721SemasteProcess::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2319254721Semaste{
2320254721Semaste    if (!GetDisableMemoryCache())
2321254721Semaste    {
2322254721Semaste#if defined (VERIFY_MEMORY_READS)
2323254721Semaste        // Memory caching is enabled, with debug verification
2324254721Semaste
2325254721Semaste        if (buf && size)
2326254721Semaste        {
2327254721Semaste            // Uncomment the line below to make sure memory caching is working.
2328254721Semaste            // I ran this through the test suite and got no assertions, so I am
2329254721Semaste            // pretty confident this is working well. If any changes are made to
2330254721Semaste            // memory caching, uncomment the line below and test your changes!
2331254721Semaste
2332254721Semaste            // Verify all memory reads by using the cache first, then redundantly
2333254721Semaste            // reading the same memory from the inferior and comparing to make sure
2334254721Semaste            // everything is exactly the same.
2335254721Semaste            std::string verify_buf (size, '\0');
2336254721Semaste            assert (verify_buf.size() == size);
2337254721Semaste            const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2338254721Semaste            Error verify_error;
2339254721Semaste            const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2340254721Semaste            assert (cache_bytes_read == verify_bytes_read);
2341254721Semaste            assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2342254721Semaste            assert (verify_error.Success() == error.Success());
2343254721Semaste            return cache_bytes_read;
2344254721Semaste        }
2345254721Semaste        return 0;
2346254721Semaste#else // !defined(VERIFY_MEMORY_READS)
2347254721Semaste        // Memory caching is enabled, without debug verification
2348254721Semaste
2349254721Semaste        return m_memory_cache.Read (addr, buf, size, error);
2350254721Semaste#endif // defined (VERIFY_MEMORY_READS)
2351254721Semaste    }
2352254721Semaste    else
2353254721Semaste    {
2354254721Semaste        // Memory caching is disabled
2355254721Semaste
2356254721Semaste        return ReadMemoryFromInferior (addr, buf, size, error);
2357254721Semaste    }
2358254721Semaste}
2359254721Semaste
2360254721Semastesize_t
2361254721SemasteProcess::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2362254721Semaste{
2363254721Semaste    char buf[256];
2364254721Semaste    out_str.clear();
2365254721Semaste    addr_t curr_addr = addr;
2366254721Semaste    while (1)
2367254721Semaste    {
2368254721Semaste        size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2369254721Semaste        if (length == 0)
2370254721Semaste            break;
2371254721Semaste        out_str.append(buf, length);
2372254721Semaste        // If we got "length - 1" bytes, we didn't get the whole C string, we
2373254721Semaste        // need to read some more characters
2374254721Semaste        if (length == sizeof(buf) - 1)
2375254721Semaste            curr_addr += length;
2376254721Semaste        else
2377254721Semaste            break;
2378254721Semaste    }
2379254721Semaste    return out_str.size();
2380254721Semaste}
2381254721Semaste
2382254721Semaste
2383254721Semastesize_t
2384254721SemasteProcess::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2385254721Semaste                                size_t type_width)
2386254721Semaste{
2387254721Semaste    size_t total_bytes_read = 0;
2388254721Semaste    if (dst && max_bytes && type_width && max_bytes >= type_width)
2389254721Semaste    {
2390254721Semaste        // Ensure a null terminator independent of the number of bytes that is read.
2391254721Semaste        memset (dst, 0, max_bytes);
2392254721Semaste        size_t bytes_left = max_bytes - type_width;
2393254721Semaste
2394254721Semaste        const char terminator[4] = {'\0', '\0', '\0', '\0'};
2395254721Semaste        assert(sizeof(terminator) >= type_width &&
2396254721Semaste               "Attempting to validate a string with more than 4 bytes per character!");
2397254721Semaste
2398254721Semaste        addr_t curr_addr = addr;
2399254721Semaste        const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2400254721Semaste        char *curr_dst = dst;
2401254721Semaste
2402254721Semaste        error.Clear();
2403254721Semaste        while (bytes_left > 0 && error.Success())
2404254721Semaste        {
2405254721Semaste            addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2406254721Semaste            addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2407254721Semaste            size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2408254721Semaste
2409254721Semaste            if (bytes_read == 0)
2410254721Semaste                break;
2411254721Semaste
2412254721Semaste            // Search for a null terminator of correct size and alignment in bytes_read
2413254721Semaste            size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2414254721Semaste            for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2415254721Semaste                if (::strncmp(&dst[i], terminator, type_width) == 0)
2416254721Semaste                {
2417254721Semaste                    error.Clear();
2418254721Semaste                    return i;
2419254721Semaste                }
2420254721Semaste
2421254721Semaste            total_bytes_read += bytes_read;
2422254721Semaste            curr_dst += bytes_read;
2423254721Semaste            curr_addr += bytes_read;
2424254721Semaste            bytes_left -= bytes_read;
2425254721Semaste        }
2426254721Semaste    }
2427254721Semaste    else
2428254721Semaste    {
2429254721Semaste        if (max_bytes)
2430254721Semaste            error.SetErrorString("invalid arguments");
2431254721Semaste    }
2432254721Semaste    return total_bytes_read;
2433254721Semaste}
2434254721Semaste
2435254721Semaste// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2436254721Semaste// null terminators.
2437254721Semastesize_t
2438254721SemasteProcess::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
2439254721Semaste{
2440254721Semaste    size_t total_cstr_len = 0;
2441254721Semaste    if (dst && dst_max_len)
2442254721Semaste    {
2443254721Semaste        result_error.Clear();
2444254721Semaste        // NULL out everything just to be safe
2445254721Semaste        memset (dst, 0, dst_max_len);
2446254721Semaste        Error error;
2447254721Semaste        addr_t curr_addr = addr;
2448254721Semaste        const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2449254721Semaste        size_t bytes_left = dst_max_len - 1;
2450254721Semaste        char *curr_dst = dst;
2451254721Semaste
2452254721Semaste        while (bytes_left > 0)
2453254721Semaste        {
2454254721Semaste            addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2455254721Semaste            addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2456254721Semaste            size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2457254721Semaste
2458254721Semaste            if (bytes_read == 0)
2459254721Semaste            {
2460254721Semaste                result_error = error;
2461254721Semaste                dst[total_cstr_len] = '\0';
2462254721Semaste                break;
2463254721Semaste            }
2464254721Semaste            const size_t len = strlen(curr_dst);
2465254721Semaste
2466254721Semaste            total_cstr_len += len;
2467254721Semaste
2468254721Semaste            if (len < bytes_to_read)
2469254721Semaste                break;
2470254721Semaste
2471254721Semaste            curr_dst += bytes_read;
2472254721Semaste            curr_addr += bytes_read;
2473254721Semaste            bytes_left -= bytes_read;
2474254721Semaste        }
2475254721Semaste    }
2476254721Semaste    else
2477254721Semaste    {
2478254721Semaste        if (dst == NULL)
2479254721Semaste            result_error.SetErrorString("invalid arguments");
2480254721Semaste        else
2481254721Semaste            result_error.Clear();
2482254721Semaste    }
2483254721Semaste    return total_cstr_len;
2484254721Semaste}
2485254721Semaste
2486254721Semastesize_t
2487254721SemasteProcess::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2488254721Semaste{
2489254721Semaste    if (buf == NULL || size == 0)
2490254721Semaste        return 0;
2491254721Semaste
2492254721Semaste    size_t bytes_read = 0;
2493254721Semaste    uint8_t *bytes = (uint8_t *)buf;
2494254721Semaste
2495254721Semaste    while (bytes_read < size)
2496254721Semaste    {
2497254721Semaste        const size_t curr_size = size - bytes_read;
2498254721Semaste        const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2499254721Semaste                                                     bytes + bytes_read,
2500254721Semaste                                                     curr_size,
2501254721Semaste                                                     error);
2502254721Semaste        bytes_read += curr_bytes_read;
2503254721Semaste        if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2504254721Semaste            break;
2505254721Semaste    }
2506254721Semaste
2507254721Semaste    // Replace any software breakpoint opcodes that fall into this range back
2508254721Semaste    // into "buf" before we return
2509254721Semaste    if (bytes_read > 0)
2510254721Semaste        RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2511254721Semaste    return bytes_read;
2512254721Semaste}
2513254721Semaste
2514254721Semasteuint64_t
2515254721SemasteProcess::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
2516254721Semaste{
2517254721Semaste    Scalar scalar;
2518254721Semaste    if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2519254721Semaste        return scalar.ULongLong(fail_value);
2520254721Semaste    return fail_value;
2521254721Semaste}
2522254721Semaste
2523254721Semasteaddr_t
2524254721SemasteProcess::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2525254721Semaste{
2526254721Semaste    Scalar scalar;
2527254721Semaste    if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2528254721Semaste        return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2529254721Semaste    return LLDB_INVALID_ADDRESS;
2530254721Semaste}
2531254721Semaste
2532254721Semaste
2533254721Semastebool
2534254721SemasteProcess::WritePointerToMemory (lldb::addr_t vm_addr,
2535254721Semaste                               lldb::addr_t ptr_value,
2536254721Semaste                               Error &error)
2537254721Semaste{
2538254721Semaste    Scalar scalar;
2539254721Semaste    const uint32_t addr_byte_size = GetAddressByteSize();
2540254721Semaste    if (addr_byte_size <= 4)
2541254721Semaste        scalar = (uint32_t)ptr_value;
2542254721Semaste    else
2543254721Semaste        scalar = ptr_value;
2544254721Semaste    return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
2545254721Semaste}
2546254721Semaste
2547254721Semastesize_t
2548254721SemasteProcess::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2549254721Semaste{
2550254721Semaste    size_t bytes_written = 0;
2551254721Semaste    const uint8_t *bytes = (const uint8_t *)buf;
2552254721Semaste
2553254721Semaste    while (bytes_written < size)
2554254721Semaste    {
2555254721Semaste        const size_t curr_size = size - bytes_written;
2556254721Semaste        const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2557254721Semaste                                                         bytes + bytes_written,
2558254721Semaste                                                         curr_size,
2559254721Semaste                                                         error);
2560254721Semaste        bytes_written += curr_bytes_written;
2561254721Semaste        if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2562254721Semaste            break;
2563254721Semaste    }
2564254721Semaste    return bytes_written;
2565254721Semaste}
2566254721Semaste
2567254721Semastesize_t
2568254721SemasteProcess::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2569254721Semaste{
2570254721Semaste#if defined (ENABLE_MEMORY_CACHING)
2571254721Semaste    m_memory_cache.Flush (addr, size);
2572254721Semaste#endif
2573254721Semaste
2574254721Semaste    if (buf == NULL || size == 0)
2575254721Semaste        return 0;
2576254721Semaste
2577254721Semaste    m_mod_id.BumpMemoryID();
2578254721Semaste
2579254721Semaste    // We need to write any data that would go where any current software traps
2580254721Semaste    // (enabled software breakpoints) any software traps (breakpoints) that we
2581254721Semaste    // may have placed in our tasks memory.
2582254721Semaste
2583254721Semaste    BreakpointSiteList bp_sites_in_range;
2584254721Semaste
2585254721Semaste    if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
2586254721Semaste    {
2587254721Semaste        // No breakpoint sites overlap
2588254721Semaste        if (bp_sites_in_range.IsEmpty())
2589254721Semaste            return WriteMemoryPrivate (addr, buf, size, error);
2590254721Semaste        else
2591254721Semaste        {
2592254721Semaste            const uint8_t *ubuf = (const uint8_t *)buf;
2593254721Semaste            uint64_t bytes_written = 0;
2594254721Semaste
2595254721Semaste            bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2596254721Semaste
2597254721Semaste                if (error.Success())
2598254721Semaste                {
2599254721Semaste                    addr_t intersect_addr;
2600254721Semaste                    size_t intersect_size;
2601254721Semaste                    size_t opcode_offset;
2602254721Semaste                    const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2603254721Semaste                    assert(intersects);
2604254721Semaste                    assert(addr <= intersect_addr && intersect_addr < addr + size);
2605254721Semaste                    assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2606254721Semaste                    assert(opcode_offset + intersect_size <= bp->GetByteSize());
2607254721Semaste
2608254721Semaste                    // Check for bytes before this breakpoint
2609254721Semaste                    const addr_t curr_addr = addr + bytes_written;
2610254721Semaste                    if (intersect_addr > curr_addr)
2611254721Semaste                    {
2612254721Semaste                        // There are some bytes before this breakpoint that we need to
2613254721Semaste                        // just write to memory
2614254721Semaste                        size_t curr_size = intersect_addr - curr_addr;
2615254721Semaste                        size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2616254721Semaste                                                                        ubuf + bytes_written,
2617254721Semaste                                                                        curr_size,
2618254721Semaste                                                                        error);
2619254721Semaste                        bytes_written += curr_bytes_written;
2620254721Semaste                        if (curr_bytes_written != curr_size)
2621254721Semaste                        {
2622254721Semaste                            // We weren't able to write all of the requested bytes, we
2623254721Semaste                            // are done looping and will return the number of bytes that
2624254721Semaste                            // we have written so far.
2625254721Semaste                            if (error.Success())
2626254721Semaste                                error.SetErrorToGenericError();
2627254721Semaste                        }
2628254721Semaste                    }
2629254721Semaste                    // Now write any bytes that would cover up any software breakpoints
2630254721Semaste                    // directly into the breakpoint opcode buffer
2631254721Semaste                    ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2632254721Semaste                    bytes_written += intersect_size;
2633254721Semaste                }
2634254721Semaste            });
2635254721Semaste
2636254721Semaste            if (bytes_written < size)
2637254721Semaste                bytes_written += WriteMemoryPrivate (addr + bytes_written,
2638254721Semaste                                                     ubuf + bytes_written,
2639254721Semaste                                                     size - bytes_written,
2640254721Semaste                                                     error);
2641254721Semaste        }
2642254721Semaste    }
2643254721Semaste    else
2644254721Semaste    {
2645254721Semaste        return WriteMemoryPrivate (addr, buf, size, error);
2646254721Semaste    }
2647254721Semaste
2648254721Semaste    // Write any remaining bytes after the last breakpoint if we have any left
2649254721Semaste    return 0; //bytes_written;
2650254721Semaste}
2651254721Semaste
2652254721Semastesize_t
2653254721SemasteProcess::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
2654254721Semaste{
2655254721Semaste    if (byte_size == UINT32_MAX)
2656254721Semaste        byte_size = scalar.GetByteSize();
2657254721Semaste    if (byte_size > 0)
2658254721Semaste    {
2659254721Semaste        uint8_t buf[32];
2660254721Semaste        const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2661254721Semaste        if (mem_size > 0)
2662254721Semaste            return WriteMemory(addr, buf, mem_size, error);
2663254721Semaste        else
2664254721Semaste            error.SetErrorString ("failed to get scalar as memory data");
2665254721Semaste    }
2666254721Semaste    else
2667254721Semaste    {
2668254721Semaste        error.SetErrorString ("invalid scalar value");
2669254721Semaste    }
2670254721Semaste    return 0;
2671254721Semaste}
2672254721Semaste
2673254721Semastesize_t
2674254721SemasteProcess::ReadScalarIntegerFromMemory (addr_t addr,
2675254721Semaste                                      uint32_t byte_size,
2676254721Semaste                                      bool is_signed,
2677254721Semaste                                      Scalar &scalar,
2678254721Semaste                                      Error &error)
2679254721Semaste{
2680254721Semaste    uint64_t uval = 0;
2681254721Semaste    if (byte_size == 0)
2682254721Semaste    {
2683254721Semaste        error.SetErrorString ("byte size is zero");
2684254721Semaste    }
2685254721Semaste    else if (byte_size & (byte_size - 1))
2686254721Semaste    {
2687254721Semaste        error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2688254721Semaste    }
2689254721Semaste    else if (byte_size <= sizeof(uval))
2690254721Semaste    {
2691254721Semaste        const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2692254721Semaste        if (bytes_read == byte_size)
2693254721Semaste        {
2694254721Semaste            DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2695254721Semaste            lldb::offset_t offset = 0;
2696254721Semaste            if (byte_size <= 4)
2697254721Semaste                scalar = data.GetMaxU32 (&offset, byte_size);
2698254721Semaste            else
2699254721Semaste                scalar = data.GetMaxU64 (&offset, byte_size);
2700254721Semaste            if (is_signed)
2701254721Semaste                scalar.SignExtend(byte_size * 8);
2702254721Semaste            return bytes_read;
2703254721Semaste        }
2704254721Semaste    }
2705254721Semaste    else
2706254721Semaste    {
2707254721Semaste        error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2708254721Semaste    }
2709254721Semaste    return 0;
2710254721Semaste}
2711254721Semaste
2712254721Semaste#define USE_ALLOCATE_MEMORY_CACHE 1
2713254721Semasteaddr_t
2714254721SemasteProcess::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2715254721Semaste{
2716254721Semaste    if (GetPrivateState() != eStateStopped)
2717254721Semaste        return LLDB_INVALID_ADDRESS;
2718254721Semaste
2719254721Semaste#if defined (USE_ALLOCATE_MEMORY_CACHE)
2720254721Semaste    return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2721254721Semaste#else
2722254721Semaste    addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2723254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2724254721Semaste    if (log)
2725254721Semaste        log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
2726254721Semaste                    size,
2727254721Semaste                    GetPermissionsAsCString (permissions),
2728254721Semaste                    (uint64_t)allocated_addr,
2729254721Semaste                    m_mod_id.GetStopID(),
2730254721Semaste                    m_mod_id.GetMemoryID());
2731254721Semaste    return allocated_addr;
2732254721Semaste#endif
2733254721Semaste}
2734254721Semaste
2735254721Semastebool
2736254721SemasteProcess::CanJIT ()
2737254721Semaste{
2738254721Semaste    if (m_can_jit == eCanJITDontKnow)
2739254721Semaste    {
2740254721Semaste        Error err;
2741254721Semaste
2742254721Semaste        uint64_t allocated_memory = AllocateMemory(8,
2743254721Semaste                                                   ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2744254721Semaste                                                   err);
2745254721Semaste
2746254721Semaste        if (err.Success())
2747254721Semaste            m_can_jit = eCanJITYes;
2748254721Semaste        else
2749254721Semaste            m_can_jit = eCanJITNo;
2750254721Semaste
2751254721Semaste        DeallocateMemory (allocated_memory);
2752254721Semaste    }
2753254721Semaste
2754254721Semaste    return m_can_jit == eCanJITYes;
2755254721Semaste}
2756254721Semaste
2757254721Semastevoid
2758254721SemasteProcess::SetCanJIT (bool can_jit)
2759254721Semaste{
2760254721Semaste    m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2761254721Semaste}
2762254721Semaste
2763254721SemasteError
2764254721SemasteProcess::DeallocateMemory (addr_t ptr)
2765254721Semaste{
2766254721Semaste    Error error;
2767254721Semaste#if defined (USE_ALLOCATE_MEMORY_CACHE)
2768254721Semaste    if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2769254721Semaste    {
2770254721Semaste        error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2771254721Semaste    }
2772254721Semaste#else
2773254721Semaste    error = DoDeallocateMemory (ptr);
2774254721Semaste
2775254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2776254721Semaste    if (log)
2777254721Semaste        log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2778254721Semaste                    ptr,
2779254721Semaste                    error.AsCString("SUCCESS"),
2780254721Semaste                    m_mod_id.GetStopID(),
2781254721Semaste                    m_mod_id.GetMemoryID());
2782254721Semaste#endif
2783254721Semaste    return error;
2784254721Semaste}
2785254721Semaste
2786254721Semaste
2787254721SemasteModuleSP
2788254721SemasteProcess::ReadModuleFromMemory (const FileSpec& file_spec,
2789254721Semaste                               lldb::addr_t header_addr)
2790254721Semaste{
2791254721Semaste    ModuleSP module_sp (new Module (file_spec, ArchSpec()));
2792254721Semaste    if (module_sp)
2793254721Semaste    {
2794254721Semaste        Error error;
2795254721Semaste        ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2796254721Semaste        if (objfile)
2797254721Semaste            return module_sp;
2798254721Semaste    }
2799254721Semaste    return ModuleSP();
2800254721Semaste}
2801254721Semaste
2802254721SemasteError
2803254721SemasteProcess::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
2804254721Semaste{
2805254721Semaste    Error error;
2806254721Semaste    error.SetErrorString("watchpoints are not supported");
2807254721Semaste    return error;
2808254721Semaste}
2809254721Semaste
2810254721SemasteError
2811254721SemasteProcess::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
2812254721Semaste{
2813254721Semaste    Error error;
2814254721Semaste    error.SetErrorString("watchpoints are not supported");
2815254721Semaste    return error;
2816254721Semaste}
2817254721Semaste
2818254721SemasteStateType
2819254721SemasteProcess::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2820254721Semaste{
2821254721Semaste    StateType state;
2822254721Semaste    // Now wait for the process to launch and return control to us, and then
2823254721Semaste    // call DidLaunch:
2824254721Semaste    while (1)
2825254721Semaste    {
2826254721Semaste        event_sp.reset();
2827254721Semaste        state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2828254721Semaste
2829254721Semaste        if (StateIsStoppedState(state, false))
2830254721Semaste            break;
2831254721Semaste
2832254721Semaste        // If state is invalid, then we timed out
2833254721Semaste        if (state == eStateInvalid)
2834254721Semaste            break;
2835254721Semaste
2836254721Semaste        if (event_sp)
2837254721Semaste            HandlePrivateEvent (event_sp);
2838254721Semaste    }
2839254721Semaste    return state;
2840254721Semaste}
2841254721Semaste
2842254721SemasteError
2843254721SemasteProcess::Launch (const ProcessLaunchInfo &launch_info)
2844254721Semaste{
2845254721Semaste    Error error;
2846254721Semaste    m_abi_sp.reset();
2847254721Semaste    m_dyld_ap.reset();
2848254721Semaste    m_os_ap.reset();
2849254721Semaste    m_process_input_reader.reset();
2850254721Semaste
2851254721Semaste    Module *exe_module = m_target.GetExecutableModulePointer();
2852254721Semaste    if (exe_module)
2853254721Semaste    {
2854254721Semaste        char local_exec_file_path[PATH_MAX];
2855254721Semaste        char platform_exec_file_path[PATH_MAX];
2856254721Semaste        exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2857254721Semaste        exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
2858254721Semaste        if (exe_module->GetFileSpec().Exists())
2859254721Semaste        {
2860254721Semaste            if (PrivateStateThreadIsValid ())
2861254721Semaste                PausePrivateStateThread ();
2862254721Semaste
2863254721Semaste            error = WillLaunch (exe_module);
2864254721Semaste            if (error.Success())
2865254721Semaste            {
2866254721Semaste                const bool restarted = false;
2867254721Semaste                SetPublicState (eStateLaunching, restarted);
2868254721Semaste                m_should_detach = false;
2869254721Semaste
2870254721Semaste                if (m_public_run_lock.TrySetRunning())
2871254721Semaste                {
2872254721Semaste                    // Now launch using these arguments.
2873254721Semaste                    error = DoLaunch (exe_module, launch_info);
2874254721Semaste                }
2875254721Semaste                else
2876254721Semaste                {
2877254721Semaste                    // This shouldn't happen
2878254721Semaste                    error.SetErrorString("failed to acquire process run lock");
2879254721Semaste                }
2880254721Semaste
2881254721Semaste                if (error.Fail())
2882254721Semaste                {
2883254721Semaste                    if (GetID() != LLDB_INVALID_PROCESS_ID)
2884254721Semaste                    {
2885254721Semaste                        SetID (LLDB_INVALID_PROCESS_ID);
2886254721Semaste                        const char *error_string = error.AsCString();
2887254721Semaste                        if (error_string == NULL)
2888254721Semaste                            error_string = "launch failed";
2889254721Semaste                        SetExitStatus (-1, error_string);
2890254721Semaste                    }
2891254721Semaste                }
2892254721Semaste                else
2893254721Semaste                {
2894254721Semaste                    EventSP event_sp;
2895254721Semaste                    TimeValue timeout_time;
2896254721Semaste                    timeout_time = TimeValue::Now();
2897254721Semaste                    timeout_time.OffsetWithSeconds(10);
2898254721Semaste                    StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
2899254721Semaste
2900254721Semaste                    if (state == eStateInvalid || event_sp.get() == NULL)
2901254721Semaste                    {
2902254721Semaste                        // We were able to launch the process, but we failed to
2903254721Semaste                        // catch the initial stop.
2904254721Semaste                        SetExitStatus (0, "failed to catch stop after launch");
2905254721Semaste                        Destroy();
2906254721Semaste                    }
2907254721Semaste                    else if (state == eStateStopped || state == eStateCrashed)
2908254721Semaste                    {
2909254721Semaste
2910254721Semaste                        DidLaunch ();
2911254721Semaste
2912254721Semaste                        DynamicLoader *dyld = GetDynamicLoader ();
2913254721Semaste                        if (dyld)
2914254721Semaste                            dyld->DidLaunch();
2915254721Semaste
2916254721Semaste                        m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2917254721Semaste                        // This delays passing the stopped event to listeners till DidLaunch gets
2918254721Semaste                        // a chance to complete...
2919254721Semaste                        HandlePrivateEvent (event_sp);
2920254721Semaste
2921254721Semaste                        if (PrivateStateThreadIsValid ())
2922254721Semaste                            ResumePrivateStateThread ();
2923254721Semaste                        else
2924254721Semaste                            StartPrivateStateThread ();
2925254721Semaste                    }
2926254721Semaste                    else if (state == eStateExited)
2927254721Semaste                    {
2928254721Semaste                        // We exited while trying to launch somehow.  Don't call DidLaunch as that's
2929254721Semaste                        // not likely to work, and return an invalid pid.
2930254721Semaste                        HandlePrivateEvent (event_sp);
2931254721Semaste                    }
2932254721Semaste                }
2933254721Semaste            }
2934254721Semaste        }
2935254721Semaste        else
2936254721Semaste        {
2937254721Semaste            error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
2938254721Semaste        }
2939254721Semaste    }
2940254721Semaste    return error;
2941254721Semaste}
2942254721Semaste
2943254721Semaste
2944254721SemasteError
2945254721SemasteProcess::LoadCore ()
2946254721Semaste{
2947254721Semaste    Error error = DoLoadCore();
2948254721Semaste    if (error.Success())
2949254721Semaste    {
2950254721Semaste        if (PrivateStateThreadIsValid ())
2951254721Semaste            ResumePrivateStateThread ();
2952254721Semaste        else
2953254721Semaste            StartPrivateStateThread ();
2954254721Semaste
2955254721Semaste        DynamicLoader *dyld = GetDynamicLoader ();
2956254721Semaste        if (dyld)
2957254721Semaste            dyld->DidAttach();
2958254721Semaste
2959254721Semaste        m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2960254721Semaste        // We successfully loaded a core file, now pretend we stopped so we can
2961254721Semaste        // show all of the threads in the core file and explore the crashed
2962254721Semaste        // state.
2963254721Semaste        SetPrivateState (eStateStopped);
2964254721Semaste
2965254721Semaste    }
2966254721Semaste    return error;
2967254721Semaste}
2968254721Semaste
2969254721SemasteDynamicLoader *
2970254721SemasteProcess::GetDynamicLoader ()
2971254721Semaste{
2972254721Semaste    if (m_dyld_ap.get() == NULL)
2973254721Semaste        m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2974254721Semaste    return m_dyld_ap.get();
2975254721Semaste}
2976254721Semaste
2977254721Semaste
2978254721SemasteProcess::NextEventAction::EventActionResult
2979254721SemasteProcess::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
2980254721Semaste{
2981254721Semaste    StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2982254721Semaste    switch (state)
2983254721Semaste    {
2984254721Semaste        case eStateRunning:
2985254721Semaste        case eStateConnected:
2986254721Semaste            return eEventActionRetry;
2987254721Semaste
2988254721Semaste        case eStateStopped:
2989254721Semaste        case eStateCrashed:
2990254721Semaste            {
2991254721Semaste                // During attach, prior to sending the eStateStopped event,
2992254721Semaste                // lldb_private::Process subclasses must set the new process ID.
2993254721Semaste                assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2994254721Semaste                // We don't want these events to be reported, so go set the ShouldReportStop here:
2995254721Semaste                m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2996254721Semaste
2997254721Semaste                if (m_exec_count > 0)
2998254721Semaste                {
2999254721Semaste                    --m_exec_count;
3000254721Semaste                    RequestResume();
3001254721Semaste                    return eEventActionRetry;
3002254721Semaste                }
3003254721Semaste                else
3004254721Semaste                {
3005254721Semaste                    m_process->CompleteAttach ();
3006254721Semaste                    return eEventActionSuccess;
3007254721Semaste                }
3008254721Semaste            }
3009254721Semaste            break;
3010254721Semaste
3011254721Semaste        default:
3012254721Semaste        case eStateExited:
3013254721Semaste        case eStateInvalid:
3014254721Semaste            break;
3015254721Semaste    }
3016254721Semaste
3017254721Semaste    m_exit_string.assign ("No valid Process");
3018254721Semaste    return eEventActionExit;
3019254721Semaste}
3020254721Semaste
3021254721SemasteProcess::NextEventAction::EventActionResult
3022254721SemasteProcess::AttachCompletionHandler::HandleBeingInterrupted()
3023254721Semaste{
3024254721Semaste    return eEventActionSuccess;
3025254721Semaste}
3026254721Semaste
3027254721Semasteconst char *
3028254721SemasteProcess::AttachCompletionHandler::GetExitString ()
3029254721Semaste{
3030254721Semaste    return m_exit_string.c_str();
3031254721Semaste}
3032254721Semaste
3033254721SemasteError
3034254721SemasteProcess::Attach (ProcessAttachInfo &attach_info)
3035254721Semaste{
3036254721Semaste    m_abi_sp.reset();
3037254721Semaste    m_process_input_reader.reset();
3038254721Semaste    m_dyld_ap.reset();
3039254721Semaste    m_os_ap.reset();
3040254721Semaste
3041254721Semaste    lldb::pid_t attach_pid = attach_info.GetProcessID();
3042254721Semaste    Error error;
3043254721Semaste    if (attach_pid == LLDB_INVALID_PROCESS_ID)
3044254721Semaste    {
3045254721Semaste        char process_name[PATH_MAX];
3046254721Semaste
3047254721Semaste        if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
3048254721Semaste        {
3049254721Semaste            const bool wait_for_launch = attach_info.GetWaitForLaunch();
3050254721Semaste
3051254721Semaste            if (wait_for_launch)
3052254721Semaste            {
3053254721Semaste                error = WillAttachToProcessWithName(process_name, wait_for_launch);
3054254721Semaste                if (error.Success())
3055254721Semaste                {
3056254721Semaste                    if (m_public_run_lock.TrySetRunning())
3057254721Semaste                    {
3058254721Semaste                        m_should_detach = true;
3059254721Semaste                        const bool restarted = false;
3060254721Semaste                        SetPublicState (eStateAttaching, restarted);
3061254721Semaste                        // Now attach using these arguments.
3062254721Semaste                        error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3063254721Semaste                    }
3064254721Semaste                    else
3065254721Semaste                    {
3066254721Semaste                        // This shouldn't happen
3067254721Semaste                        error.SetErrorString("failed to acquire process run lock");
3068254721Semaste                    }
3069254721Semaste
3070254721Semaste                    if (error.Fail())
3071254721Semaste                    {
3072254721Semaste                        if (GetID() != LLDB_INVALID_PROCESS_ID)
3073254721Semaste                        {
3074254721Semaste                            SetID (LLDB_INVALID_PROCESS_ID);
3075254721Semaste                            if (error.AsCString() == NULL)
3076254721Semaste                                error.SetErrorString("attach failed");
3077254721Semaste
3078254721Semaste                            SetExitStatus(-1, error.AsCString());
3079254721Semaste                        }
3080254721Semaste                    }
3081254721Semaste                    else
3082254721Semaste                    {
3083254721Semaste                        SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3084254721Semaste                        StartPrivateStateThread();
3085254721Semaste                    }
3086254721Semaste                    return error;
3087254721Semaste                }
3088254721Semaste            }
3089254721Semaste            else
3090254721Semaste            {
3091254721Semaste                ProcessInstanceInfoList process_infos;
3092254721Semaste                PlatformSP platform_sp (m_target.GetPlatform ());
3093254721Semaste
3094254721Semaste                if (platform_sp)
3095254721Semaste                {
3096254721Semaste                    ProcessInstanceInfoMatch match_info;
3097254721Semaste                    match_info.GetProcessInfo() = attach_info;
3098254721Semaste                    match_info.SetNameMatchType (eNameMatchEquals);
3099254721Semaste                    platform_sp->FindProcesses (match_info, process_infos);
3100254721Semaste                    const uint32_t num_matches = process_infos.GetSize();
3101254721Semaste                    if (num_matches == 1)
3102254721Semaste                    {
3103254721Semaste                        attach_pid = process_infos.GetProcessIDAtIndex(0);
3104254721Semaste                        // Fall through and attach using the above process ID
3105254721Semaste                    }
3106254721Semaste                    else
3107254721Semaste                    {
3108254721Semaste                        match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3109254721Semaste                        if (num_matches > 1)
3110254721Semaste                            error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3111254721Semaste                        else
3112254721Semaste                            error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3113254721Semaste                    }
3114254721Semaste                }
3115254721Semaste                else
3116254721Semaste                {
3117254721Semaste                    error.SetErrorString ("invalid platform, can't find processes by name");
3118254721Semaste                    return error;
3119254721Semaste                }
3120254721Semaste            }
3121254721Semaste        }
3122254721Semaste        else
3123254721Semaste        {
3124254721Semaste            error.SetErrorString ("invalid process name");
3125254721Semaste        }
3126254721Semaste    }
3127254721Semaste
3128254721Semaste    if (attach_pid != LLDB_INVALID_PROCESS_ID)
3129254721Semaste    {
3130254721Semaste        error = WillAttachToProcessWithID(attach_pid);
3131254721Semaste        if (error.Success())
3132254721Semaste        {
3133254721Semaste
3134254721Semaste            if (m_public_run_lock.TrySetRunning())
3135254721Semaste            {
3136254721Semaste                // Now attach using these arguments.
3137254721Semaste                m_should_detach = true;
3138254721Semaste                const bool restarted = false;
3139254721Semaste                SetPublicState (eStateAttaching, restarted);
3140254721Semaste                error = DoAttachToProcessWithID (attach_pid, attach_info);
3141254721Semaste            }
3142254721Semaste            else
3143254721Semaste            {
3144254721Semaste                // This shouldn't happen
3145254721Semaste                error.SetErrorString("failed to acquire process run lock");
3146254721Semaste            }
3147254721Semaste
3148254721Semaste            if (error.Success())
3149254721Semaste            {
3150254721Semaste
3151254721Semaste                SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3152254721Semaste                StartPrivateStateThread();
3153254721Semaste            }
3154254721Semaste            else
3155254721Semaste            {
3156254721Semaste                if (GetID() != LLDB_INVALID_PROCESS_ID)
3157254721Semaste                {
3158254721Semaste                    SetID (LLDB_INVALID_PROCESS_ID);
3159254721Semaste                    const char *error_string = error.AsCString();
3160254721Semaste                    if (error_string == NULL)
3161254721Semaste                        error_string = "attach failed";
3162254721Semaste
3163254721Semaste                    SetExitStatus(-1, error_string);
3164254721Semaste                }
3165254721Semaste            }
3166254721Semaste        }
3167254721Semaste    }
3168254721Semaste    return error;
3169254721Semaste}
3170254721Semaste
3171254721Semastevoid
3172254721SemasteProcess::CompleteAttach ()
3173254721Semaste{
3174254721Semaste    // Let the process subclass figure out at much as it can about the process
3175254721Semaste    // before we go looking for a dynamic loader plug-in.
3176254721Semaste    DidAttach();
3177254721Semaste
3178254721Semaste    // We just attached.  If we have a platform, ask it for the process architecture, and if it isn't
3179254721Semaste    // the same as the one we've already set, switch architectures.
3180254721Semaste    PlatformSP platform_sp (m_target.GetPlatform ());
3181254721Semaste    assert (platform_sp.get());
3182254721Semaste    if (platform_sp)
3183254721Semaste    {
3184254721Semaste        const ArchSpec &target_arch = m_target.GetArchitecture();
3185254721Semaste        if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
3186254721Semaste        {
3187254721Semaste            ArchSpec platform_arch;
3188254721Semaste            platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3189254721Semaste            if (platform_sp)
3190254721Semaste            {
3191254721Semaste                m_target.SetPlatform (platform_sp);
3192254721Semaste                m_target.SetArchitecture(platform_arch);
3193254721Semaste            }
3194254721Semaste        }
3195254721Semaste        else
3196254721Semaste        {
3197254721Semaste            ProcessInstanceInfo process_info;
3198254721Semaste            platform_sp->GetProcessInfo (GetID(), process_info);
3199254721Semaste            const ArchSpec &process_arch = process_info.GetArchitecture();
3200254721Semaste            if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
3201254721Semaste                m_target.SetArchitecture (process_arch);
3202254721Semaste        }
3203254721Semaste    }
3204254721Semaste
3205254721Semaste    // We have completed the attach, now it is time to find the dynamic loader
3206254721Semaste    // plug-in
3207254721Semaste    DynamicLoader *dyld = GetDynamicLoader ();
3208254721Semaste    if (dyld)
3209254721Semaste        dyld->DidAttach();
3210254721Semaste
3211254721Semaste    m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3212254721Semaste    // Figure out which one is the executable, and set that in our target:
3213254721Semaste    const ModuleList &target_modules = m_target.GetImages();
3214254721Semaste    Mutex::Locker modules_locker(target_modules.GetMutex());
3215254721Semaste    size_t num_modules = target_modules.GetSize();
3216254721Semaste    ModuleSP new_executable_module_sp;
3217254721Semaste
3218254721Semaste    for (size_t i = 0; i < num_modules; i++)
3219254721Semaste    {
3220254721Semaste        ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
3221254721Semaste        if (module_sp && module_sp->IsExecutable())
3222254721Semaste        {
3223254721Semaste            if (m_target.GetExecutableModulePointer() != module_sp.get())
3224254721Semaste                new_executable_module_sp = module_sp;
3225254721Semaste            break;
3226254721Semaste        }
3227254721Semaste    }
3228254721Semaste    if (new_executable_module_sp)
3229254721Semaste        m_target.SetExecutableModule (new_executable_module_sp, false);
3230254721Semaste}
3231254721Semaste
3232254721SemasteError
3233254721SemasteProcess::ConnectRemote (Stream *strm, const char *remote_url)
3234254721Semaste{
3235254721Semaste    m_abi_sp.reset();
3236254721Semaste    m_process_input_reader.reset();
3237254721Semaste
3238254721Semaste    // Find the process and its architecture.  Make sure it matches the architecture
3239254721Semaste    // of the current Target, and if not adjust it.
3240254721Semaste
3241254721Semaste    Error error (DoConnectRemote (strm, remote_url));
3242254721Semaste    if (error.Success())
3243254721Semaste    {
3244254721Semaste        if (GetID() != LLDB_INVALID_PROCESS_ID)
3245254721Semaste        {
3246254721Semaste            EventSP event_sp;
3247254721Semaste            StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3248254721Semaste
3249254721Semaste            if (state == eStateStopped || state == eStateCrashed)
3250254721Semaste            {
3251254721Semaste                // If we attached and actually have a process on the other end, then
3252254721Semaste                // this ended up being the equivalent of an attach.
3253254721Semaste                CompleteAttach ();
3254254721Semaste
3255254721Semaste                // This delays passing the stopped event to listeners till
3256254721Semaste                // CompleteAttach gets a chance to complete...
3257254721Semaste                HandlePrivateEvent (event_sp);
3258254721Semaste
3259254721Semaste            }
3260254721Semaste        }
3261254721Semaste
3262254721Semaste        if (PrivateStateThreadIsValid ())
3263254721Semaste            ResumePrivateStateThread ();
3264254721Semaste        else
3265254721Semaste            StartPrivateStateThread ();
3266254721Semaste    }
3267254721Semaste    return error;
3268254721Semaste}
3269254721Semaste
3270254721Semaste
3271254721SemasteError
3272254721SemasteProcess::PrivateResume ()
3273254721Semaste{
3274254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
3275254721Semaste    if (log)
3276254721Semaste        log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
3277254721Semaste                    m_mod_id.GetStopID(),
3278254721Semaste                    StateAsCString(m_public_state.GetValue()),
3279254721Semaste                    StateAsCString(m_private_state.GetValue()));
3280254721Semaste
3281254721Semaste    Error error (WillResume());
3282254721Semaste    // Tell the process it is about to resume before the thread list
3283254721Semaste    if (error.Success())
3284254721Semaste    {
3285254721Semaste        // Now let the thread list know we are about to resume so it
3286254721Semaste        // can let all of our threads know that they are about to be
3287254721Semaste        // resumed. Threads will each be called with
3288254721Semaste        // Thread::WillResume(StateType) where StateType contains the state
3289254721Semaste        // that they are supposed to have when the process is resumed
3290254721Semaste        // (suspended/running/stepping). Threads should also check
3291254721Semaste        // their resume signal in lldb::Thread::GetResumeSignal()
3292254721Semaste        // to see if they are supposed to start back up with a signal.
3293254721Semaste        if (m_thread_list.WillResume())
3294254721Semaste        {
3295254721Semaste            // Last thing, do the PreResumeActions.
3296254721Semaste            if (!RunPreResumeActions())
3297254721Semaste            {
3298254721Semaste                error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
3299254721Semaste            }
3300254721Semaste            else
3301254721Semaste            {
3302254721Semaste                m_mod_id.BumpResumeID();
3303254721Semaste                error = DoResume();
3304254721Semaste                if (error.Success())
3305254721Semaste                {
3306254721Semaste                    DidResume();
3307254721Semaste                    m_thread_list.DidResume();
3308254721Semaste                    if (log)
3309254721Semaste                        log->Printf ("Process thinks the process has resumed.");
3310254721Semaste                }
3311254721Semaste            }
3312254721Semaste        }
3313254721Semaste        else
3314254721Semaste        {
3315254721Semaste            // Somebody wanted to run without running.  So generate a continue & a stopped event,
3316254721Semaste            // and let the world handle them.
3317254721Semaste            if (log)
3318254721Semaste                log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3319254721Semaste
3320254721Semaste            SetPrivateState(eStateRunning);
3321254721Semaste            SetPrivateState(eStateStopped);
3322254721Semaste        }
3323254721Semaste    }
3324254721Semaste    else if (log)
3325254721Semaste        log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
3326254721Semaste    return error;
3327254721Semaste}
3328254721Semaste
3329254721SemasteError
3330254721SemasteProcess::Halt (bool clear_thread_plans)
3331254721Semaste{
3332254721Semaste    // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3333254721Semaste    // in case it was already set and some thread plan logic calls halt on its
3334254721Semaste    // own.
3335254721Semaste    m_clear_thread_plans_on_stop |= clear_thread_plans;
3336254721Semaste
3337254721Semaste    // First make sure we aren't in the middle of handling an event, or we might restart.  This is pretty weak, since
3338254721Semaste    // we could just straightaway get another event.  It just narrows the window...
3339254721Semaste    m_currently_handling_event.WaitForValueEqualTo(false);
3340254721Semaste
3341254721Semaste
3342254721Semaste    // Pause our private state thread so we can ensure no one else eats
3343254721Semaste    // the stop event out from under us.
3344254721Semaste    Listener halt_listener ("lldb.process.halt_listener");
3345254721Semaste    HijackPrivateProcessEvents(&halt_listener);
3346254721Semaste
3347254721Semaste    EventSP event_sp;
3348254721Semaste    Error error (WillHalt());
3349254721Semaste
3350254721Semaste    if (error.Success())
3351254721Semaste    {
3352254721Semaste
3353254721Semaste        bool caused_stop = false;
3354254721Semaste
3355254721Semaste        // Ask the process subclass to actually halt our process
3356254721Semaste        error = DoHalt(caused_stop);
3357254721Semaste        if (error.Success())
3358254721Semaste        {
3359254721Semaste            if (m_public_state.GetValue() == eStateAttaching)
3360254721Semaste            {
3361254721Semaste                SetExitStatus(SIGKILL, "Cancelled async attach.");
3362254721Semaste                Destroy ();
3363254721Semaste            }
3364254721Semaste            else
3365254721Semaste            {
3366254721Semaste                // If "caused_stop" is true, then DoHalt stopped the process. If
3367254721Semaste                // "caused_stop" is false, the process was already stopped.
3368254721Semaste                // If the DoHalt caused the process to stop, then we want to catch
3369254721Semaste                // this event and set the interrupted bool to true before we pass
3370254721Semaste                // this along so clients know that the process was interrupted by
3371254721Semaste                // a halt command.
3372254721Semaste                if (caused_stop)
3373254721Semaste                {
3374254721Semaste                    // Wait for 1 second for the process to stop.
3375254721Semaste                    TimeValue timeout_time;
3376254721Semaste                    timeout_time = TimeValue::Now();
3377254721Semaste                    timeout_time.OffsetWithSeconds(1);
3378254721Semaste                    bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3379254721Semaste                    StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3380254721Semaste
3381254721Semaste                    if (!got_event || state == eStateInvalid)
3382254721Semaste                    {
3383254721Semaste                        // We timeout out and didn't get a stop event...
3384254721Semaste                        error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
3385254721Semaste                    }
3386254721Semaste                    else
3387254721Semaste                    {
3388254721Semaste                        if (StateIsStoppedState (state, false))
3389254721Semaste                        {
3390254721Semaste                            // We caused the process to interrupt itself, so mark this
3391254721Semaste                            // as such in the stop event so clients can tell an interrupted
3392254721Semaste                            // process from a natural stop
3393254721Semaste                            ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3394254721Semaste                        }
3395254721Semaste                        else
3396254721Semaste                        {
3397254721Semaste                            Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3398254721Semaste                            if (log)
3399254721Semaste                                log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3400254721Semaste                            error.SetErrorString ("Did not get stopped event after halt.");
3401254721Semaste                        }
3402254721Semaste                    }
3403254721Semaste                }
3404254721Semaste                DidHalt();
3405254721Semaste            }
3406254721Semaste        }
3407254721Semaste    }
3408254721Semaste    // Resume our private state thread before we post the event (if any)
3409254721Semaste    RestorePrivateProcessEvents();
3410254721Semaste
3411254721Semaste    // Post any event we might have consumed. If all goes well, we will have
3412254721Semaste    // stopped the process, intercepted the event and set the interrupted
3413254721Semaste    // bool in the event.  Post it to the private event queue and that will end up
3414254721Semaste    // correctly setting the state.
3415254721Semaste    if (event_sp)
3416254721Semaste        m_private_state_broadcaster.BroadcastEvent(event_sp);
3417254721Semaste
3418254721Semaste    return error;
3419254721Semaste}
3420254721Semaste
3421254721SemasteError
3422254721SemasteProcess::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3423254721Semaste{
3424254721Semaste    Error error;
3425254721Semaste    if (m_public_state.GetValue() == eStateRunning)
3426254721Semaste    {
3427254721Semaste        Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3428254721Semaste        if (log)
3429254721Semaste            log->Printf("Process::Destroy() About to halt.");
3430254721Semaste        error = Halt();
3431254721Semaste        if (error.Success())
3432254721Semaste        {
3433254721Semaste            // Consume the halt event.
3434254721Semaste            TimeValue timeout (TimeValue::Now());
3435254721Semaste            timeout.OffsetWithSeconds(1);
3436254721Semaste            StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3437254721Semaste
3438254721Semaste            // If the process exited while we were waiting for it to stop, put the exited event into
3439254721Semaste            // the shared pointer passed in and return.  Our caller doesn't need to do anything else, since
3440254721Semaste            // they don't have a process anymore...
3441254721Semaste
3442254721Semaste            if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3443254721Semaste            {
3444254721Semaste                if (log)
3445254721Semaste                    log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3446254721Semaste                return error;
3447254721Semaste            }
3448254721Semaste            else
3449254721Semaste                exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3450254721Semaste
3451254721Semaste            if (state != eStateStopped)
3452254721Semaste            {
3453254721Semaste                if (log)
3454254721Semaste                    log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3455254721Semaste                // If we really couldn't stop the process then we should just error out here, but if the
3456254721Semaste                // lower levels just bobbled sending the event and we really are stopped, then continue on.
3457254721Semaste                StateType private_state = m_private_state.GetValue();
3458254721Semaste                if (private_state != eStateStopped)
3459254721Semaste                {
3460254721Semaste                    return error;
3461254721Semaste                }
3462254721Semaste            }
3463254721Semaste        }
3464254721Semaste        else
3465254721Semaste        {
3466254721Semaste            if (log)
3467254721Semaste                log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3468254721Semaste        }
3469254721Semaste    }
3470254721Semaste    return error;
3471254721Semaste}
3472254721Semaste
3473254721SemasteError
3474254721SemasteProcess::Detach (bool keep_stopped)
3475254721Semaste{
3476254721Semaste    EventSP exit_event_sp;
3477254721Semaste    Error error;
3478254721Semaste    m_destroy_in_process = true;
3479254721Semaste
3480254721Semaste    error = WillDetach();
3481254721Semaste
3482254721Semaste    if (error.Success())
3483254721Semaste    {
3484254721Semaste        if (DetachRequiresHalt())
3485254721Semaste        {
3486254721Semaste            error = HaltForDestroyOrDetach (exit_event_sp);
3487254721Semaste            if (!error.Success())
3488254721Semaste            {
3489254721Semaste                m_destroy_in_process = false;
3490254721Semaste                return error;
3491254721Semaste            }
3492254721Semaste            else if (exit_event_sp)
3493254721Semaste            {
3494254721Semaste                // We shouldn't need to do anything else here.  There's no process left to detach from...
3495254721Semaste                StopPrivateStateThread();
3496254721Semaste                m_destroy_in_process = false;
3497254721Semaste                return error;
3498254721Semaste            }
3499254721Semaste        }
3500254721Semaste
3501254721Semaste        error = DoDetach(keep_stopped);
3502254721Semaste        if (error.Success())
3503254721Semaste        {
3504254721Semaste            DidDetach();
3505254721Semaste            StopPrivateStateThread();
3506254721Semaste        }
3507254721Semaste        else
3508254721Semaste        {
3509254721Semaste            return error;
3510254721Semaste        }
3511254721Semaste    }
3512254721Semaste    m_destroy_in_process = false;
3513254721Semaste
3514254721Semaste    // If we exited when we were waiting for a process to stop, then
3515254721Semaste    // forward the event here so we don't lose the event
3516254721Semaste    if (exit_event_sp)
3517254721Semaste    {
3518254721Semaste        // Directly broadcast our exited event because we shut down our
3519254721Semaste        // private state thread above
3520254721Semaste        BroadcastEvent(exit_event_sp);
3521254721Semaste    }
3522254721Semaste
3523254721Semaste    // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3524254721Semaste    // the last events through the event system, in which case we might strand the write lock.  Unlock
3525254721Semaste    // it here so when we do to tear down the process we don't get an error destroying the lock.
3526254721Semaste
3527254721Semaste    m_public_run_lock.SetStopped();
3528254721Semaste    return error;
3529254721Semaste}
3530254721Semaste
3531254721SemasteError
3532254721SemasteProcess::Destroy ()
3533254721Semaste{
3534254721Semaste
3535254721Semaste    // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3536254721Semaste    // that might hinder the destruction.  Remember to set this back to false when we are done.  That way if the attempt
3537254721Semaste    // failed and the process stays around for some reason it won't be in a confused state.
3538254721Semaste
3539254721Semaste    m_destroy_in_process = true;
3540254721Semaste
3541254721Semaste    Error error (WillDestroy());
3542254721Semaste    if (error.Success())
3543254721Semaste    {
3544254721Semaste        EventSP exit_event_sp;
3545254721Semaste        if (DestroyRequiresHalt())
3546254721Semaste        {
3547254721Semaste            error = HaltForDestroyOrDetach(exit_event_sp);
3548254721Semaste        }
3549254721Semaste
3550254721Semaste        if (m_public_state.GetValue() != eStateRunning)
3551254721Semaste        {
3552254721Semaste            // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3553254721Semaste            // kill it, we don't want it hitting a breakpoint...
3554254721Semaste            // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3555254721Semaste            // we're not going to have much luck doing this now.
3556254721Semaste            m_thread_list.DiscardThreadPlans();
3557254721Semaste            DisableAllBreakpointSites();
3558254721Semaste        }
3559254721Semaste
3560254721Semaste        error = DoDestroy();
3561254721Semaste        if (error.Success())
3562254721Semaste        {
3563254721Semaste            DidDestroy();
3564254721Semaste            StopPrivateStateThread();
3565254721Semaste        }
3566254721Semaste        m_stdio_communication.StopReadThread();
3567254721Semaste        m_stdio_communication.Disconnect();
3568254721Semaste        if (m_process_input_reader && m_process_input_reader->IsActive())
3569254721Semaste            m_target.GetDebugger().PopInputReader (m_process_input_reader);
3570254721Semaste        if (m_process_input_reader)
3571254721Semaste            m_process_input_reader.reset();
3572254721Semaste
3573254721Semaste        // If we exited when we were waiting for a process to stop, then
3574254721Semaste        // forward the event here so we don't lose the event
3575254721Semaste        if (exit_event_sp)
3576254721Semaste        {
3577254721Semaste            // Directly broadcast our exited event because we shut down our
3578254721Semaste            // private state thread above
3579254721Semaste            BroadcastEvent(exit_event_sp);
3580254721Semaste        }
3581254721Semaste
3582254721Semaste        // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3583254721Semaste        // the last events through the event system, in which case we might strand the write lock.  Unlock
3584254721Semaste        // it here so when we do to tear down the process we don't get an error destroying the lock.
3585254721Semaste        m_public_run_lock.SetStopped();
3586254721Semaste    }
3587254721Semaste
3588254721Semaste    m_destroy_in_process = false;
3589254721Semaste
3590254721Semaste    return error;
3591254721Semaste}
3592254721Semaste
3593254721SemasteError
3594254721SemasteProcess::Signal (int signal)
3595254721Semaste{
3596254721Semaste    Error error (WillSignal());
3597254721Semaste    if (error.Success())
3598254721Semaste    {
3599254721Semaste        error = DoSignal(signal);
3600254721Semaste        if (error.Success())
3601254721Semaste            DidSignal();
3602254721Semaste    }
3603254721Semaste    return error;
3604254721Semaste}
3605254721Semaste
3606254721Semastelldb::ByteOrder
3607254721SemasteProcess::GetByteOrder () const
3608254721Semaste{
3609254721Semaste    return m_target.GetArchitecture().GetByteOrder();
3610254721Semaste}
3611254721Semaste
3612254721Semasteuint32_t
3613254721SemasteProcess::GetAddressByteSize () const
3614254721Semaste{
3615254721Semaste    return m_target.GetArchitecture().GetAddressByteSize();
3616254721Semaste}
3617254721Semaste
3618254721Semaste
3619254721Semastebool
3620254721SemasteProcess::ShouldBroadcastEvent (Event *event_ptr)
3621254721Semaste{
3622254721Semaste    const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3623254721Semaste    bool return_value = true;
3624254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
3625254721Semaste
3626254721Semaste    switch (state)
3627254721Semaste    {
3628254721Semaste        case eStateConnected:
3629254721Semaste        case eStateAttaching:
3630254721Semaste        case eStateLaunching:
3631254721Semaste        case eStateDetached:
3632254721Semaste        case eStateExited:
3633254721Semaste        case eStateUnloaded:
3634254721Semaste            // These events indicate changes in the state of the debugging session, always report them.
3635254721Semaste            return_value = true;
3636254721Semaste            break;
3637254721Semaste        case eStateInvalid:
3638254721Semaste            // We stopped for no apparent reason, don't report it.
3639254721Semaste            return_value = false;
3640254721Semaste            break;
3641254721Semaste        case eStateRunning:
3642254721Semaste        case eStateStepping:
3643254721Semaste            // If we've started the target running, we handle the cases where we
3644254721Semaste            // are already running and where there is a transition from stopped to
3645254721Semaste            // running differently.
3646254721Semaste            // running -> running: Automatically suppress extra running events
3647254721Semaste            // stopped -> running: Report except when there is one or more no votes
3648254721Semaste            //     and no yes votes.
3649254721Semaste            SynchronouslyNotifyStateChanged (state);
3650254721Semaste            switch (m_last_broadcast_state)
3651254721Semaste            {
3652254721Semaste                case eStateRunning:
3653254721Semaste                case eStateStepping:
3654254721Semaste                    // We always suppress multiple runnings with no PUBLIC stop in between.
3655254721Semaste                    return_value = false;
3656254721Semaste                    break;
3657254721Semaste                default:
3658254721Semaste                    // TODO: make this work correctly. For now always report
3659254721Semaste                    // run if we aren't running so we don't miss any runnning
3660254721Semaste                    // events. If I run the lldb/test/thread/a.out file and
3661254721Semaste                    // break at main.cpp:58, run and hit the breakpoints on
3662254721Semaste                    // multiple threads, then somehow during the stepping over
3663254721Semaste                    // of all breakpoints no run gets reported.
3664254721Semaste
3665254721Semaste                    // This is a transition from stop to run.
3666254721Semaste                    switch (m_thread_list.ShouldReportRun (event_ptr))
3667254721Semaste                    {
3668254721Semaste                        case eVoteYes:
3669254721Semaste                        case eVoteNoOpinion:
3670254721Semaste                            return_value = true;
3671254721Semaste                            break;
3672254721Semaste                        case eVoteNo:
3673254721Semaste                            return_value = false;
3674254721Semaste                            break;
3675254721Semaste                    }
3676254721Semaste                    break;
3677254721Semaste            }
3678254721Semaste            break;
3679254721Semaste        case eStateStopped:
3680254721Semaste        case eStateCrashed:
3681254721Semaste        case eStateSuspended:
3682254721Semaste        {
3683254721Semaste            // We've stopped.  First see if we're going to restart the target.
3684254721Semaste            // If we are going to stop, then we always broadcast the event.
3685254721Semaste            // If we aren't going to stop, let the thread plans decide if we're going to report this event.
3686254721Semaste            // If no thread has an opinion, we don't report it.
3687254721Semaste
3688254721Semaste            RefreshStateAfterStop ();
3689254721Semaste            if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
3690254721Semaste            {
3691254721Semaste                if (log)
3692254721Semaste                    log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3693254721Semaste                                 event_ptr,
3694254721Semaste                                 StateAsCString(state));
3695254721Semaste                return_value = true;
3696254721Semaste            }
3697254721Semaste            else
3698254721Semaste            {
3699254721Semaste                bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3700254721Semaste                bool should_resume = false;
3701254721Semaste
3702254721Semaste                // It makes no sense to ask "ShouldStop" if we've already been restarted...
3703254721Semaste                // Asking the thread list is also not likely to go well, since we are running again.
3704254721Semaste                // So in that case just report the event.
3705254721Semaste
3706254721Semaste                if (!was_restarted)
3707254721Semaste                    should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3708254721Semaste
3709254721Semaste                if (was_restarted || should_resume || m_resume_requested)
3710254721Semaste                {
3711254721Semaste                    Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3712254721Semaste                    if (log)
3713254721Semaste                        log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3714254721Semaste                                     should_resume,
3715254721Semaste                                     StateAsCString(state),
3716254721Semaste                                     was_restarted,
3717254721Semaste                                     stop_vote);
3718254721Semaste
3719254721Semaste                    switch (stop_vote)
3720254721Semaste                    {
3721254721Semaste                        case eVoteYes:
3722254721Semaste                            return_value = true;
3723254721Semaste                            break;
3724254721Semaste                        case eVoteNoOpinion:
3725254721Semaste                        case eVoteNo:
3726254721Semaste                            return_value = false;
3727254721Semaste                            break;
3728254721Semaste                    }
3729254721Semaste
3730254721Semaste                    if (!was_restarted)
3731254721Semaste                    {
3732254721Semaste                        if (log)
3733254721Semaste                            log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3734254721Semaste                        ProcessEventData::SetRestartedInEvent(event_ptr, true);
3735254721Semaste                        PrivateResume ();
3736254721Semaste                    }
3737254721Semaste
3738254721Semaste                }
3739254721Semaste                else
3740254721Semaste                {
3741254721Semaste                    return_value = true;
3742254721Semaste                    SynchronouslyNotifyStateChanged (state);
3743254721Semaste                }
3744254721Semaste            }
3745254721Semaste        }
3746254721Semaste        break;
3747254721Semaste    }
3748254721Semaste
3749254721Semaste    // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3750254721Semaste    // But we only coalesce against events we actually broadcast.  So we use m_last_broadcast_state
3751254721Semaste    // to track that.  NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3752254721Semaste    // because the PublicState reflects the last event pulled off the queue, and there may be several
3753254721Semaste    // events stacked up on the queue unserviced.  So the PublicState may not reflect the last broadcasted event
3754254721Semaste    // yet.  m_last_broadcast_state gets updated here.
3755254721Semaste
3756254721Semaste    if (return_value)
3757254721Semaste        m_last_broadcast_state = state;
3758254721Semaste
3759254721Semaste    if (log)
3760254721Semaste        log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3761254721Semaste                     event_ptr,
3762254721Semaste                     StateAsCString(state),
3763254721Semaste                     StateAsCString(m_last_broadcast_state),
3764254721Semaste                     return_value ? "YES" : "NO");
3765254721Semaste    return return_value;
3766254721Semaste}
3767254721Semaste
3768254721Semaste
3769254721Semastebool
3770254721SemasteProcess::StartPrivateStateThread (bool force)
3771254721Semaste{
3772254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3773254721Semaste
3774254721Semaste    bool already_running = PrivateStateThreadIsValid ();
3775254721Semaste    if (log)
3776254721Semaste        log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3777254721Semaste
3778254721Semaste    if (!force && already_running)
3779254721Semaste        return true;
3780254721Semaste
3781254721Semaste    // Create a thread that watches our internal state and controls which
3782254721Semaste    // events make it to clients (into the DCProcess event queue).
3783254721Semaste    char thread_name[1024];
3784254721Semaste    if (already_running)
3785254721Semaste        snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3786254721Semaste    else
3787254721Semaste        snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3788254721Semaste
3789254721Semaste    // Create the private state thread, and start it running.
3790254721Semaste    m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
3791254721Semaste    bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3792254721Semaste    if (success)
3793254721Semaste    {
3794254721Semaste        ResumePrivateStateThread();
3795254721Semaste        return true;
3796254721Semaste    }
3797254721Semaste    else
3798254721Semaste        return false;
3799254721Semaste}
3800254721Semaste
3801254721Semastevoid
3802254721SemasteProcess::PausePrivateStateThread ()
3803254721Semaste{
3804254721Semaste    ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3805254721Semaste}
3806254721Semaste
3807254721Semastevoid
3808254721SemasteProcess::ResumePrivateStateThread ()
3809254721Semaste{
3810254721Semaste    ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3811254721Semaste}
3812254721Semaste
3813254721Semastevoid
3814254721SemasteProcess::StopPrivateStateThread ()
3815254721Semaste{
3816254721Semaste    if (PrivateStateThreadIsValid ())
3817254721Semaste        ControlPrivateStateThread (eBroadcastInternalStateControlStop);
3818254721Semaste    else
3819254721Semaste    {
3820254721Semaste        Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3821254721Semaste        if (log)
3822254721Semaste            log->Printf ("Went to stop the private state thread, but it was already invalid.");
3823254721Semaste    }
3824254721Semaste}
3825254721Semaste
3826254721Semastevoid
3827254721SemasteProcess::ControlPrivateStateThread (uint32_t signal)
3828254721Semaste{
3829254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3830254721Semaste
3831254721Semaste    assert (signal == eBroadcastInternalStateControlStop ||
3832254721Semaste            signal == eBroadcastInternalStateControlPause ||
3833254721Semaste            signal == eBroadcastInternalStateControlResume);
3834254721Semaste
3835254721Semaste    if (log)
3836254721Semaste        log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
3837254721Semaste
3838254721Semaste    // Signal the private state thread. First we should copy this is case the
3839254721Semaste    // thread starts exiting since the private state thread will NULL this out
3840254721Semaste    // when it exits
3841254721Semaste    const lldb::thread_t private_state_thread = m_private_state_thread;
3842254721Semaste    if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
3843254721Semaste    {
3844254721Semaste        TimeValue timeout_time;
3845254721Semaste        bool timed_out;
3846254721Semaste
3847254721Semaste        m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3848254721Semaste
3849254721Semaste        timeout_time = TimeValue::Now();
3850254721Semaste        timeout_time.OffsetWithSeconds(2);
3851254721Semaste        if (log)
3852254721Semaste            log->Printf ("Sending control event of type: %d.", signal);
3853254721Semaste        m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3854254721Semaste        m_private_state_control_wait.SetValue (false, eBroadcastNever);
3855254721Semaste
3856254721Semaste        if (signal == eBroadcastInternalStateControlStop)
3857254721Semaste        {
3858254721Semaste            if (timed_out)
3859254721Semaste            {
3860254721Semaste                Error error;
3861254721Semaste                Host::ThreadCancel (private_state_thread, &error);
3862254721Semaste                if (log)
3863254721Semaste                    log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3864254721Semaste            }
3865254721Semaste            else
3866254721Semaste            {
3867254721Semaste                if (log)
3868254721Semaste                    log->Printf ("The control event killed the private state thread without having to cancel.");
3869254721Semaste            }
3870254721Semaste
3871254721Semaste            thread_result_t result = NULL;
3872254721Semaste            Host::ThreadJoin (private_state_thread, &result, NULL);
3873254721Semaste            m_private_state_thread = LLDB_INVALID_HOST_THREAD;
3874254721Semaste        }
3875254721Semaste    }
3876254721Semaste    else
3877254721Semaste    {
3878254721Semaste        if (log)
3879254721Semaste            log->Printf ("Private state thread already dead, no need to signal it to stop.");
3880254721Semaste    }
3881254721Semaste}
3882254721Semaste
3883254721Semastevoid
3884254721SemasteProcess::SendAsyncInterrupt ()
3885254721Semaste{
3886254721Semaste    if (PrivateStateThreadIsValid())
3887254721Semaste        m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3888254721Semaste    else
3889254721Semaste        BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3890254721Semaste}
3891254721Semaste
3892254721Semastevoid
3893254721SemasteProcess::HandlePrivateEvent (EventSP &event_sp)
3894254721Semaste{
3895254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3896254721Semaste    m_resume_requested = false;
3897254721Semaste
3898254721Semaste    m_currently_handling_event.SetValue(true, eBroadcastNever);
3899254721Semaste
3900254721Semaste    const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3901254721Semaste
3902254721Semaste    // First check to see if anybody wants a shot at this event:
3903254721Semaste    if (m_next_event_action_ap.get() != NULL)
3904254721Semaste    {
3905254721Semaste        NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
3906254721Semaste        if (log)
3907254721Semaste            log->Printf ("Ran next event action, result was %d.", action_result);
3908254721Semaste
3909254721Semaste        switch (action_result)
3910254721Semaste        {
3911254721Semaste            case NextEventAction::eEventActionSuccess:
3912254721Semaste                SetNextEventAction(NULL);
3913254721Semaste                break;
3914254721Semaste
3915254721Semaste            case NextEventAction::eEventActionRetry:
3916254721Semaste                break;
3917254721Semaste
3918254721Semaste            case NextEventAction::eEventActionExit:
3919254721Semaste                // Handle Exiting Here.  If we already got an exited event,
3920254721Semaste                // we should just propagate it.  Otherwise, swallow this event,
3921254721Semaste                // and set our state to exit so the next event will kill us.
3922254721Semaste                if (new_state != eStateExited)
3923254721Semaste                {
3924254721Semaste                    // FIXME: should cons up an exited event, and discard this one.
3925254721Semaste                    SetExitStatus(0, m_next_event_action_ap->GetExitString());
3926254721Semaste                    m_currently_handling_event.SetValue(false, eBroadcastAlways);
3927254721Semaste                    SetNextEventAction(NULL);
3928254721Semaste                    return;
3929254721Semaste                }
3930254721Semaste                SetNextEventAction(NULL);
3931254721Semaste                break;
3932254721Semaste        }
3933254721Semaste    }
3934254721Semaste
3935254721Semaste    // See if we should broadcast this state to external clients?
3936254721Semaste    const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
3937254721Semaste
3938254721Semaste    if (should_broadcast)
3939254721Semaste    {
3940254721Semaste        if (log)
3941254721Semaste        {
3942254721Semaste            log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
3943254721Semaste                         __FUNCTION__,
3944254721Semaste                         GetID(),
3945254721Semaste                         StateAsCString(new_state),
3946254721Semaste                         StateAsCString (GetState ()),
3947254721Semaste                         IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
3948254721Semaste        }
3949254721Semaste        Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3950254721Semaste        if (StateIsRunningState (new_state))
3951254721Semaste            PushProcessInputReader ();
3952254721Semaste        else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3953254721Semaste            PopProcessInputReader ();
3954254721Semaste
3955254721Semaste        BroadcastEvent (event_sp);
3956254721Semaste    }
3957254721Semaste    else
3958254721Semaste    {
3959254721Semaste        if (log)
3960254721Semaste        {
3961254721Semaste            log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
3962254721Semaste                         __FUNCTION__,
3963254721Semaste                         GetID(),
3964254721Semaste                         StateAsCString(new_state),
3965254721Semaste                         StateAsCString (GetState ()));
3966254721Semaste        }
3967254721Semaste    }
3968254721Semaste    m_currently_handling_event.SetValue(false, eBroadcastAlways);
3969254721Semaste}
3970254721Semaste
3971254721Semastevoid *
3972254721SemasteProcess::PrivateStateThread (void *arg)
3973254721Semaste{
3974254721Semaste    Process *proc = static_cast<Process*> (arg);
3975254721Semaste    void *result = proc->RunPrivateStateThread ();
3976254721Semaste    return result;
3977254721Semaste}
3978254721Semaste
3979254721Semastevoid *
3980254721SemasteProcess::RunPrivateStateThread ()
3981254721Semaste{
3982254721Semaste    bool control_only = true;
3983254721Semaste    m_private_state_control_wait.SetValue (false, eBroadcastNever);
3984254721Semaste
3985254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3986254721Semaste    if (log)
3987254721Semaste        log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
3988254721Semaste
3989254721Semaste    bool exit_now = false;
3990254721Semaste    while (!exit_now)
3991254721Semaste    {
3992254721Semaste        EventSP event_sp;
3993254721Semaste        WaitForEventsPrivate (NULL, event_sp, control_only);
3994254721Semaste        if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3995254721Semaste        {
3996254721Semaste            if (log)
3997254721Semaste                log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3998254721Semaste
3999254721Semaste            switch (event_sp->GetType())
4000254721Semaste            {
4001254721Semaste            case eBroadcastInternalStateControlStop:
4002254721Semaste                exit_now = true;
4003254721Semaste                break;      // doing any internal state managment below
4004254721Semaste
4005254721Semaste            case eBroadcastInternalStateControlPause:
4006254721Semaste                control_only = true;
4007254721Semaste                break;
4008254721Semaste
4009254721Semaste            case eBroadcastInternalStateControlResume:
4010254721Semaste                control_only = false;
4011254721Semaste                break;
4012254721Semaste            }
4013254721Semaste
4014254721Semaste            m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4015254721Semaste            continue;
4016254721Semaste        }
4017254721Semaste        else if (event_sp->GetType() == eBroadcastBitInterrupt)
4018254721Semaste        {
4019254721Semaste            if (m_public_state.GetValue() == eStateAttaching)
4020254721Semaste            {
4021254721Semaste                if (log)
4022254721Semaste                    log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
4023254721Semaste                BroadcastEvent (eBroadcastBitInterrupt, NULL);
4024254721Semaste            }
4025254721Semaste            else
4026254721Semaste            {
4027254721Semaste                if (log)
4028254721Semaste                    log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
4029254721Semaste                Halt();
4030254721Semaste            }
4031254721Semaste            continue;
4032254721Semaste        }
4033254721Semaste
4034254721Semaste        const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4035254721Semaste
4036254721Semaste        if (internal_state != eStateInvalid)
4037254721Semaste        {
4038254721Semaste            if (m_clear_thread_plans_on_stop &&
4039254721Semaste                StateIsStoppedState(internal_state, true))
4040254721Semaste            {
4041254721Semaste                m_clear_thread_plans_on_stop = false;
4042254721Semaste                m_thread_list.DiscardThreadPlans();
4043254721Semaste            }
4044254721Semaste            HandlePrivateEvent (event_sp);
4045254721Semaste        }
4046254721Semaste
4047254721Semaste        if (internal_state == eStateInvalid ||
4048254721Semaste            internal_state == eStateExited  ||
4049254721Semaste            internal_state == eStateDetached )
4050254721Semaste        {
4051254721Semaste            if (log)
4052254721Semaste                log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
4053254721Semaste
4054254721Semaste            break;
4055254721Semaste        }
4056254721Semaste    }
4057254721Semaste
4058254721Semaste    // Verify log is still enabled before attempting to write to it...
4059254721Semaste    if (log)
4060254721Semaste        log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
4061254721Semaste
4062254721Semaste    m_public_run_lock.SetStopped();
4063254721Semaste    m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4064254721Semaste    m_private_state_thread = LLDB_INVALID_HOST_THREAD;
4065254721Semaste    return NULL;
4066254721Semaste}
4067254721Semaste
4068254721Semaste//------------------------------------------------------------------
4069254721Semaste// Process Event Data
4070254721Semaste//------------------------------------------------------------------
4071254721Semaste
4072254721SemasteProcess::ProcessEventData::ProcessEventData () :
4073254721Semaste    EventData (),
4074254721Semaste    m_process_sp (),
4075254721Semaste    m_state (eStateInvalid),
4076254721Semaste    m_restarted (false),
4077254721Semaste    m_update_state (0),
4078254721Semaste    m_interrupted (false)
4079254721Semaste{
4080254721Semaste}
4081254721Semaste
4082254721SemasteProcess::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4083254721Semaste    EventData (),
4084254721Semaste    m_process_sp (process_sp),
4085254721Semaste    m_state (state),
4086254721Semaste    m_restarted (false),
4087254721Semaste    m_update_state (0),
4088254721Semaste    m_interrupted (false)
4089254721Semaste{
4090254721Semaste}
4091254721Semaste
4092254721SemasteProcess::ProcessEventData::~ProcessEventData()
4093254721Semaste{
4094254721Semaste}
4095254721Semaste
4096254721Semasteconst ConstString &
4097254721SemasteProcess::ProcessEventData::GetFlavorString ()
4098254721Semaste{
4099254721Semaste    static ConstString g_flavor ("Process::ProcessEventData");
4100254721Semaste    return g_flavor;
4101254721Semaste}
4102254721Semaste
4103254721Semasteconst ConstString &
4104254721SemasteProcess::ProcessEventData::GetFlavor () const
4105254721Semaste{
4106254721Semaste    return ProcessEventData::GetFlavorString ();
4107254721Semaste}
4108254721Semaste
4109254721Semastevoid
4110254721SemasteProcess::ProcessEventData::DoOnRemoval (Event *event_ptr)
4111254721Semaste{
4112254721Semaste    // This function gets called twice for each event, once when the event gets pulled
4113254721Semaste    // off of the private process event queue, and then any number of times, first when it gets pulled off of
4114254721Semaste    // the public event queue, then other times when we're pretending that this is where we stopped at the
4115254721Semaste    // end of expression evaluation.  m_update_state is used to distinguish these
4116254721Semaste    // three cases; it is 0 when we're just pulling it off for private handling,
4117254721Semaste    // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
4118254721Semaste    if (m_update_state != 1)
4119254721Semaste        return;
4120254721Semaste
4121254721Semaste    m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4122254721Semaste
4123254721Semaste    // If we're stopped and haven't restarted, then do the breakpoint commands here:
4124254721Semaste    if (m_state == eStateStopped && ! m_restarted)
4125254721Semaste    {
4126254721Semaste        ThreadList &curr_thread_list = m_process_sp->GetThreadList();
4127254721Semaste        uint32_t num_threads = curr_thread_list.GetSize();
4128254721Semaste        uint32_t idx;
4129254721Semaste
4130254721Semaste        // The actions might change one of the thread's stop_info's opinions about whether we should
4131254721Semaste        // stop the process, so we need to query that as we go.
4132254721Semaste
4133254721Semaste        // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4134254721Semaste        // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4135254721Semaste        // that would cause our iteration here to crash.  We could make a copy of the thread list, but we'd really like
4136254721Semaste        // 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
4137254721Semaste        // against this list & bag out if anything differs.
4138254721Semaste        std::vector<uint32_t> thread_index_array(num_threads);
4139254721Semaste        for (idx = 0; idx < num_threads; ++idx)
4140254721Semaste            thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4141254721Semaste
4142254721Semaste        // Use this to track whether we should continue from here.  We will only continue the target running if
4143254721Semaste        // no thread says we should stop.  Of course if some thread's PerformAction actually sets the target running,
4144254721Semaste        // then it doesn't matter what the other threads say...
4145254721Semaste
4146254721Semaste        bool still_should_stop = false;
4147254721Semaste
4148254721Semaste        // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4149254721Semaste        // valid stop reason.  In that case we should just stop, because we have no way of telling what the right
4150254721Semaste        // thing to do is, and it's better to let the user decide than continue behind their backs.
4151254721Semaste
4152254721Semaste        bool does_anybody_have_an_opinion = false;
4153254721Semaste
4154254721Semaste        for (idx = 0; idx < num_threads; ++idx)
4155254721Semaste        {
4156254721Semaste            curr_thread_list = m_process_sp->GetThreadList();
4157254721Semaste            if (curr_thread_list.GetSize() != num_threads)
4158254721Semaste            {
4159254721Semaste                Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4160254721Semaste                if (log)
4161254721Semaste                    log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
4162254721Semaste                break;
4163254721Semaste            }
4164254721Semaste
4165254721Semaste            lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4166254721Semaste
4167254721Semaste            if (thread_sp->GetIndexID() != thread_index_array[idx])
4168254721Semaste            {
4169254721Semaste                Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4170254721Semaste                if (log)
4171254721Semaste                    log->Printf("The thread at position %u changed from %u to %u while processing event.",
4172254721Semaste                                idx,
4173254721Semaste                                thread_index_array[idx],
4174254721Semaste                                thread_sp->GetIndexID());
4175254721Semaste                break;
4176254721Semaste            }
4177254721Semaste
4178254721Semaste            StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
4179254721Semaste            if (stop_info_sp && stop_info_sp->IsValid())
4180254721Semaste            {
4181254721Semaste                does_anybody_have_an_opinion = true;
4182254721Semaste                bool this_thread_wants_to_stop;
4183254721Semaste                if (stop_info_sp->GetOverrideShouldStop())
4184254721Semaste                {
4185254721Semaste                    this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4186254721Semaste                }
4187254721Semaste                else
4188254721Semaste                {
4189254721Semaste                    stop_info_sp->PerformAction(event_ptr);
4190254721Semaste                    // The stop action might restart the target.  If it does, then we want to mark that in the
4191254721Semaste                    // event so that whoever is receiving it will know to wait for the running event and reflect
4192254721Semaste                    // that state appropriately.
4193254721Semaste                    // We also need to stop processing actions, since they aren't expecting the target to be running.
4194254721Semaste
4195254721Semaste                    // FIXME: we might have run.
4196254721Semaste                    if (stop_info_sp->HasTargetRunSinceMe())
4197254721Semaste                    {
4198254721Semaste                        SetRestarted (true);
4199254721Semaste                        break;
4200254721Semaste                    }
4201254721Semaste
4202254721Semaste                    this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4203254721Semaste                }
4204254721Semaste
4205254721Semaste                if (still_should_stop == false)
4206254721Semaste                    still_should_stop = this_thread_wants_to_stop;
4207254721Semaste            }
4208254721Semaste        }
4209254721Semaste
4210254721Semaste
4211254721Semaste        if (!GetRestarted())
4212254721Semaste        {
4213254721Semaste            if (!still_should_stop && does_anybody_have_an_opinion)
4214254721Semaste            {
4215254721Semaste                // We've been asked to continue, so do that here.
4216254721Semaste                SetRestarted(true);
4217254721Semaste                // Use the public resume method here, since this is just
4218254721Semaste                // extending a public resume.
4219254721Semaste                m_process_sp->PrivateResume();
4220254721Semaste            }
4221254721Semaste            else
4222254721Semaste            {
4223254721Semaste                // If we didn't restart, run the Stop Hooks here:
4224254721Semaste                // They might also restart the target, so watch for that.
4225254721Semaste                m_process_sp->GetTarget().RunStopHooks();
4226254721Semaste                if (m_process_sp->GetPrivateState() == eStateRunning)
4227254721Semaste                    SetRestarted(true);
4228254721Semaste            }
4229254721Semaste        }
4230254721Semaste    }
4231254721Semaste}
4232254721Semaste
4233254721Semastevoid
4234254721SemasteProcess::ProcessEventData::Dump (Stream *s) const
4235254721Semaste{
4236254721Semaste    if (m_process_sp)
4237254721Semaste        s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
4238254721Semaste
4239254721Semaste    s->Printf("state = %s", StateAsCString(GetState()));
4240254721Semaste}
4241254721Semaste
4242254721Semasteconst Process::ProcessEventData *
4243254721SemasteProcess::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4244254721Semaste{
4245254721Semaste    if (event_ptr)
4246254721Semaste    {
4247254721Semaste        const EventData *event_data = event_ptr->GetData();
4248254721Semaste        if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4249254721Semaste            return static_cast <const ProcessEventData *> (event_ptr->GetData());
4250254721Semaste    }
4251254721Semaste    return NULL;
4252254721Semaste}
4253254721Semaste
4254254721SemasteProcessSP
4255254721SemasteProcess::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4256254721Semaste{
4257254721Semaste    ProcessSP process_sp;
4258254721Semaste    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4259254721Semaste    if (data)
4260254721Semaste        process_sp = data->GetProcessSP();
4261254721Semaste    return process_sp;
4262254721Semaste}
4263254721Semaste
4264254721SemasteStateType
4265254721SemasteProcess::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4266254721Semaste{
4267254721Semaste    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4268254721Semaste    if (data == NULL)
4269254721Semaste        return eStateInvalid;
4270254721Semaste    else
4271254721Semaste        return data->GetState();
4272254721Semaste}
4273254721Semaste
4274254721Semastebool
4275254721SemasteProcess::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4276254721Semaste{
4277254721Semaste    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4278254721Semaste    if (data == NULL)
4279254721Semaste        return false;
4280254721Semaste    else
4281254721Semaste        return data->GetRestarted();
4282254721Semaste}
4283254721Semaste
4284254721Semastevoid
4285254721SemasteProcess::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4286254721Semaste{
4287254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4288254721Semaste    if (data != NULL)
4289254721Semaste        data->SetRestarted(new_value);
4290254721Semaste}
4291254721Semaste
4292254721Semastesize_t
4293254721SemasteProcess::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4294254721Semaste{
4295254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4296254721Semaste    if (data != NULL)
4297254721Semaste        return data->GetNumRestartedReasons();
4298254721Semaste    else
4299254721Semaste        return 0;
4300254721Semaste}
4301254721Semaste
4302254721Semasteconst char *
4303254721SemasteProcess::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4304254721Semaste{
4305254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4306254721Semaste    if (data != NULL)
4307254721Semaste        return data->GetRestartedReasonAtIndex(idx);
4308254721Semaste    else
4309254721Semaste        return NULL;
4310254721Semaste}
4311254721Semaste
4312254721Semastevoid
4313254721SemasteProcess::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4314254721Semaste{
4315254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4316254721Semaste    if (data != NULL)
4317254721Semaste        data->AddRestartedReason(reason);
4318254721Semaste}
4319254721Semaste
4320254721Semastebool
4321254721SemasteProcess::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4322254721Semaste{
4323254721Semaste    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4324254721Semaste    if (data == NULL)
4325254721Semaste        return false;
4326254721Semaste    else
4327254721Semaste        return data->GetInterrupted ();
4328254721Semaste}
4329254721Semaste
4330254721Semastevoid
4331254721SemasteProcess::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4332254721Semaste{
4333254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4334254721Semaste    if (data != NULL)
4335254721Semaste        data->SetInterrupted(new_value);
4336254721Semaste}
4337254721Semaste
4338254721Semastebool
4339254721SemasteProcess::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4340254721Semaste{
4341254721Semaste    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4342254721Semaste    if (data)
4343254721Semaste    {
4344254721Semaste        data->SetUpdateStateOnRemoval();
4345254721Semaste        return true;
4346254721Semaste    }
4347254721Semaste    return false;
4348254721Semaste}
4349254721Semaste
4350254721Semastelldb::TargetSP
4351254721SemasteProcess::CalculateTarget ()
4352254721Semaste{
4353254721Semaste    return m_target.shared_from_this();
4354254721Semaste}
4355254721Semaste
4356254721Semastevoid
4357254721SemasteProcess::CalculateExecutionContext (ExecutionContext &exe_ctx)
4358254721Semaste{
4359254721Semaste    exe_ctx.SetTargetPtr (&m_target);
4360254721Semaste    exe_ctx.SetProcessPtr (this);
4361254721Semaste    exe_ctx.SetThreadPtr(NULL);
4362254721Semaste    exe_ctx.SetFramePtr (NULL);
4363254721Semaste}
4364254721Semaste
4365254721Semaste//uint32_t
4366254721Semaste//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4367254721Semaste//{
4368254721Semaste//    return 0;
4369254721Semaste//}
4370254721Semaste//
4371254721Semaste//ArchSpec
4372254721Semaste//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4373254721Semaste//{
4374254721Semaste//    return Host::GetArchSpecForExistingProcess (pid);
4375254721Semaste//}
4376254721Semaste//
4377254721Semaste//ArchSpec
4378254721Semaste//Process::GetArchSpecForExistingProcess (const char *process_name)
4379254721Semaste//{
4380254721Semaste//    return Host::GetArchSpecForExistingProcess (process_name);
4381254721Semaste//}
4382254721Semaste//
4383254721Semastevoid
4384254721SemasteProcess::AppendSTDOUT (const char * s, size_t len)
4385254721Semaste{
4386254721Semaste    Mutex::Locker locker (m_stdio_communication_mutex);
4387254721Semaste    m_stdout_data.append (s, len);
4388254721Semaste    BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
4389254721Semaste}
4390254721Semaste
4391254721Semastevoid
4392254721SemasteProcess::AppendSTDERR (const char * s, size_t len)
4393254721Semaste{
4394254721Semaste    Mutex::Locker locker (m_stdio_communication_mutex);
4395254721Semaste    m_stderr_data.append (s, len);
4396254721Semaste    BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
4397254721Semaste}
4398254721Semaste
4399254721Semastevoid
4400254721SemasteProcess::BroadcastAsyncProfileData(const std::string &one_profile_data)
4401254721Semaste{
4402254721Semaste    Mutex::Locker locker (m_profile_data_comm_mutex);
4403254721Semaste    m_profile_data.push_back(one_profile_data);
4404254721Semaste    BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4405254721Semaste}
4406254721Semaste
4407254721Semastesize_t
4408254721SemasteProcess::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4409254721Semaste{
4410254721Semaste    Mutex::Locker locker(m_profile_data_comm_mutex);
4411254721Semaste    if (m_profile_data.empty())
4412254721Semaste        return 0;
4413254721Semaste
4414254721Semaste    std::string &one_profile_data = m_profile_data.front();
4415254721Semaste    size_t bytes_available = one_profile_data.size();
4416254721Semaste    if (bytes_available > 0)
4417254721Semaste    {
4418254721Semaste        Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4419254721Semaste        if (log)
4420254721Semaste            log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4421254721Semaste        if (bytes_available > buf_size)
4422254721Semaste        {
4423254721Semaste            memcpy(buf, one_profile_data.c_str(), buf_size);
4424254721Semaste            one_profile_data.erase(0, buf_size);
4425254721Semaste            bytes_available = buf_size;
4426254721Semaste        }
4427254721Semaste        else
4428254721Semaste        {
4429254721Semaste            memcpy(buf, one_profile_data.c_str(), bytes_available);
4430254721Semaste            m_profile_data.erase(m_profile_data.begin());
4431254721Semaste        }
4432254721Semaste    }
4433254721Semaste    return bytes_available;
4434254721Semaste}
4435254721Semaste
4436254721Semaste
4437254721Semaste//------------------------------------------------------------------
4438254721Semaste// Process STDIO
4439254721Semaste//------------------------------------------------------------------
4440254721Semaste
4441254721Semastesize_t
4442254721SemasteProcess::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4443254721Semaste{
4444254721Semaste    Mutex::Locker locker(m_stdio_communication_mutex);
4445254721Semaste    size_t bytes_available = m_stdout_data.size();
4446254721Semaste    if (bytes_available > 0)
4447254721Semaste    {
4448254721Semaste        Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4449254721Semaste        if (log)
4450254721Semaste            log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4451254721Semaste        if (bytes_available > buf_size)
4452254721Semaste        {
4453254721Semaste            memcpy(buf, m_stdout_data.c_str(), buf_size);
4454254721Semaste            m_stdout_data.erase(0, buf_size);
4455254721Semaste            bytes_available = buf_size;
4456254721Semaste        }
4457254721Semaste        else
4458254721Semaste        {
4459254721Semaste            memcpy(buf, m_stdout_data.c_str(), bytes_available);
4460254721Semaste            m_stdout_data.clear();
4461254721Semaste        }
4462254721Semaste    }
4463254721Semaste    return bytes_available;
4464254721Semaste}
4465254721Semaste
4466254721Semaste
4467254721Semastesize_t
4468254721SemasteProcess::GetSTDERR (char *buf, size_t buf_size, Error &error)
4469254721Semaste{
4470254721Semaste    Mutex::Locker locker(m_stdio_communication_mutex);
4471254721Semaste    size_t bytes_available = m_stderr_data.size();
4472254721Semaste    if (bytes_available > 0)
4473254721Semaste    {
4474254721Semaste        Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4475254721Semaste        if (log)
4476254721Semaste            log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4477254721Semaste        if (bytes_available > buf_size)
4478254721Semaste        {
4479254721Semaste            memcpy(buf, m_stderr_data.c_str(), buf_size);
4480254721Semaste            m_stderr_data.erase(0, buf_size);
4481254721Semaste            bytes_available = buf_size;
4482254721Semaste        }
4483254721Semaste        else
4484254721Semaste        {
4485254721Semaste            memcpy(buf, m_stderr_data.c_str(), bytes_available);
4486254721Semaste            m_stderr_data.clear();
4487254721Semaste        }
4488254721Semaste    }
4489254721Semaste    return bytes_available;
4490254721Semaste}
4491254721Semaste
4492254721Semastevoid
4493254721SemasteProcess::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4494254721Semaste{
4495254721Semaste    Process *process = (Process *) baton;
4496254721Semaste    process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4497254721Semaste}
4498254721Semaste
4499254721Semastesize_t
4500254721SemasteProcess::ProcessInputReaderCallback (void *baton,
4501254721Semaste                                     InputReader &reader,
4502254721Semaste                                     lldb::InputReaderAction notification,
4503254721Semaste                                     const char *bytes,
4504254721Semaste                                     size_t bytes_len)
4505254721Semaste{
4506254721Semaste    Process *process = (Process *) baton;
4507254721Semaste
4508254721Semaste    switch (notification)
4509254721Semaste    {
4510254721Semaste    case eInputReaderActivate:
4511254721Semaste        break;
4512254721Semaste
4513254721Semaste    case eInputReaderDeactivate:
4514254721Semaste        break;
4515254721Semaste
4516254721Semaste    case eInputReaderReactivate:
4517254721Semaste        break;
4518254721Semaste
4519254721Semaste    case eInputReaderAsynchronousOutputWritten:
4520254721Semaste        break;
4521254721Semaste
4522254721Semaste    case eInputReaderGotToken:
4523254721Semaste        {
4524254721Semaste            Error error;
4525254721Semaste            process->PutSTDIN (bytes, bytes_len, error);
4526254721Semaste        }
4527254721Semaste        break;
4528254721Semaste
4529254721Semaste    case eInputReaderInterrupt:
4530254721Semaste        process->SendAsyncInterrupt();
4531254721Semaste        break;
4532254721Semaste
4533254721Semaste    case eInputReaderEndOfFile:
4534254721Semaste        process->AppendSTDOUT ("^D", 2);
4535254721Semaste        break;
4536254721Semaste
4537254721Semaste    case eInputReaderDone:
4538254721Semaste        break;
4539254721Semaste
4540254721Semaste    }
4541254721Semaste
4542254721Semaste    return bytes_len;
4543254721Semaste}
4544254721Semaste
4545254721Semastevoid
4546254721SemasteProcess::ResetProcessInputReader ()
4547254721Semaste{
4548254721Semaste    m_process_input_reader.reset();
4549254721Semaste}
4550254721Semaste
4551254721Semastevoid
4552254721SemasteProcess::SetSTDIOFileDescriptor (int file_descriptor)
4553254721Semaste{
4554254721Semaste    // First set up the Read Thread for reading/handling process I/O
4555254721Semaste
4556254721Semaste    std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4557254721Semaste
4558254721Semaste    if (conn_ap.get())
4559254721Semaste    {
4560254721Semaste        m_stdio_communication.SetConnection (conn_ap.release());
4561254721Semaste        if (m_stdio_communication.IsConnected())
4562254721Semaste        {
4563254721Semaste            m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4564254721Semaste            m_stdio_communication.StartReadThread();
4565254721Semaste
4566254721Semaste            // Now read thread is set up, set up input reader.
4567254721Semaste
4568254721Semaste            if (!m_process_input_reader.get())
4569254721Semaste            {
4570254721Semaste                m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4571254721Semaste                Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4572254721Semaste                                                               this,
4573254721Semaste                                                               eInputReaderGranularityByte,
4574254721Semaste                                                               NULL,
4575254721Semaste                                                               NULL,
4576254721Semaste                                                               false));
4577254721Semaste
4578254721Semaste                if  (err.Fail())
4579254721Semaste                    m_process_input_reader.reset();
4580254721Semaste            }
4581254721Semaste        }
4582254721Semaste    }
4583254721Semaste}
4584254721Semaste
4585254721Semastevoid
4586254721SemasteProcess::PushProcessInputReader ()
4587254721Semaste{
4588254721Semaste    if (m_process_input_reader && !m_process_input_reader->IsActive())
4589254721Semaste        m_target.GetDebugger().PushInputReader (m_process_input_reader);
4590254721Semaste}
4591254721Semaste
4592254721Semastevoid
4593254721SemasteProcess::PopProcessInputReader ()
4594254721Semaste{
4595254721Semaste    if (m_process_input_reader && m_process_input_reader->IsActive())
4596254721Semaste        m_target.GetDebugger().PopInputReader (m_process_input_reader);
4597254721Semaste}
4598254721Semaste
4599254721Semaste// The process needs to know about installed plug-ins
4600254721Semastevoid
4601254721SemasteProcess::SettingsInitialize ()
4602254721Semaste{
4603254721Semaste//    static std::vector<OptionEnumValueElement> g_plugins;
4604254721Semaste//
4605254721Semaste//    int i=0;
4606254721Semaste//    const char *name;
4607254721Semaste//    OptionEnumValueElement option_enum;
4608254721Semaste//    while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4609254721Semaste//    {
4610254721Semaste//        if (name)
4611254721Semaste//        {
4612254721Semaste//            option_enum.value = i;
4613254721Semaste//            option_enum.string_value = name;
4614254721Semaste//            option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4615254721Semaste//            g_plugins.push_back (option_enum);
4616254721Semaste//        }
4617254721Semaste//        ++i;
4618254721Semaste//    }
4619254721Semaste//    option_enum.value = 0;
4620254721Semaste//    option_enum.string_value = NULL;
4621254721Semaste//    option_enum.usage = NULL;
4622254721Semaste//    g_plugins.push_back (option_enum);
4623254721Semaste//
4624254721Semaste//    for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4625254721Semaste//    {
4626254721Semaste//        if (::strcmp (name, "plugin") == 0)
4627254721Semaste//        {
4628254721Semaste//            SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4629254721Semaste//            break;
4630254721Semaste//        }
4631254721Semaste//    }
4632254721Semaste//
4633254721Semaste    Thread::SettingsInitialize ();
4634254721Semaste}
4635254721Semaste
4636254721Semastevoid
4637254721SemasteProcess::SettingsTerminate ()
4638254721Semaste{
4639254721Semaste    Thread::SettingsTerminate ();
4640254721Semaste}
4641254721Semaste
4642254721SemasteExecutionResults
4643254721SemasteProcess::RunThreadPlan (ExecutionContext &exe_ctx,
4644254721Semaste                        lldb::ThreadPlanSP &thread_plan_sp,
4645254721Semaste                        bool stop_others,
4646254721Semaste                        bool run_others,
4647254721Semaste                        bool unwind_on_error,
4648254721Semaste                        bool ignore_breakpoints,
4649254721Semaste                        uint32_t timeout_usec,
4650254721Semaste                        Stream &errors)
4651254721Semaste{
4652254721Semaste    ExecutionResults return_value = eExecutionSetupError;
4653254721Semaste
4654254721Semaste    if (thread_plan_sp.get() == NULL)
4655254721Semaste    {
4656254721Semaste        errors.Printf("RunThreadPlan called with empty thread plan.");
4657254721Semaste        return eExecutionSetupError;
4658254721Semaste    }
4659254721Semaste
4660254721Semaste    if (!thread_plan_sp->ValidatePlan(NULL))
4661254721Semaste    {
4662254721Semaste        errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4663254721Semaste        return eExecutionSetupError;
4664254721Semaste    }
4665254721Semaste
4666254721Semaste    if (exe_ctx.GetProcessPtr() != this)
4667254721Semaste    {
4668254721Semaste        errors.Printf("RunThreadPlan called on wrong process.");
4669254721Semaste        return eExecutionSetupError;
4670254721Semaste    }
4671254721Semaste
4672254721Semaste    Thread *thread = exe_ctx.GetThreadPtr();
4673254721Semaste    if (thread == NULL)
4674254721Semaste    {
4675254721Semaste        errors.Printf("RunThreadPlan called with invalid thread.");
4676254721Semaste        return eExecutionSetupError;
4677254721Semaste    }
4678254721Semaste
4679254721Semaste    // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4680254721Semaste    // For that to be true the plan can't be private - since private plans suppress themselves in the
4681254721Semaste    // GetCompletedPlan call.
4682254721Semaste
4683254721Semaste    bool orig_plan_private = thread_plan_sp->GetPrivate();
4684254721Semaste    thread_plan_sp->SetPrivate(false);
4685254721Semaste
4686254721Semaste    if (m_private_state.GetValue() != eStateStopped)
4687254721Semaste    {
4688254721Semaste        errors.Printf ("RunThreadPlan called while the private state was not stopped.");
4689254721Semaste        return eExecutionSetupError;
4690254721Semaste    }
4691254721Semaste
4692254721Semaste    // Save the thread & frame from the exe_ctx for restoration after we run
4693254721Semaste    const uint32_t thread_idx_id = thread->GetIndexID();
4694254721Semaste    StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4695254721Semaste    if (!selected_frame_sp)
4696254721Semaste    {
4697254721Semaste        thread->SetSelectedFrame(0);
4698254721Semaste        selected_frame_sp = thread->GetSelectedFrame();
4699254721Semaste        if (!selected_frame_sp)
4700254721Semaste        {
4701254721Semaste            errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4702254721Semaste            return eExecutionSetupError;
4703254721Semaste        }
4704254721Semaste    }
4705254721Semaste
4706254721Semaste    StackID ctx_frame_id = selected_frame_sp->GetStackID();
4707254721Semaste
4708254721Semaste    // N.B. Running the target may unset the currently selected thread and frame.  We don't want to do that either,
4709254721Semaste    // so we should arrange to reset them as well.
4710254721Semaste
4711254721Semaste    lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4712254721Semaste
4713254721Semaste    uint32_t selected_tid;
4714254721Semaste    StackID selected_stack_id;
4715254721Semaste    if (selected_thread_sp)
4716254721Semaste    {
4717254721Semaste        selected_tid = selected_thread_sp->GetIndexID();
4718254721Semaste        selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4719254721Semaste    }
4720254721Semaste    else
4721254721Semaste    {
4722254721Semaste        selected_tid = LLDB_INVALID_THREAD_ID;
4723254721Semaste    }
4724254721Semaste
4725254721Semaste    lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
4726254721Semaste    lldb::StateType old_state;
4727254721Semaste    lldb::ThreadPlanSP stopper_base_plan_sp;
4728254721Semaste
4729254721Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4730254721Semaste    if (Host::GetCurrentThread() == m_private_state_thread)
4731254721Semaste    {
4732254721Semaste        // Yikes, we are running on the private state thread!  So we can't wait for public events on this thread, since
4733254721Semaste        // we are the thread that is generating public events.
4734254721Semaste        // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
4735254721Semaste        // we are fielding public events here.
4736254721Semaste        if (log)
4737254721Semaste            log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4738254721Semaste
4739254721Semaste
4740254721Semaste        backup_private_state_thread = m_private_state_thread;
4741254721Semaste
4742254721Semaste        // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4743254721Semaste        // returning control here.
4744254721Semaste        // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4745254721Semaste        // event before deciding to stop, and we don't want that.  So we insert a "stopper" base plan on the stack
4746254721Semaste        // before the plan we want to run.  Since base plans always stop and return control to the user, that will
4747254721Semaste        // do just what we want.
4748254721Semaste        stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4749254721Semaste        thread->QueueThreadPlan (stopper_base_plan_sp, false);
4750254721Semaste        // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4751254721Semaste        old_state = m_public_state.GetValue();
4752254721Semaste        m_public_state.SetValueNoLock(eStateStopped);
4753254721Semaste
4754254721Semaste        // Now spin up the private state thread:
4755254721Semaste        StartPrivateStateThread(true);
4756254721Semaste    }
4757254721Semaste
4758254721Semaste    thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
4759254721Semaste
4760254721Semaste    Listener listener("lldb.process.listener.run-thread-plan");
4761254721Semaste
4762254721Semaste    lldb::EventSP event_to_broadcast_sp;
4763254721Semaste
4764254721Semaste    {
4765254721Semaste        // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4766254721Semaste        // restored on exit to the function.
4767254721Semaste        //
4768254721Semaste        // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4769254721Semaste        // is put into event_to_broadcast_sp for rebroadcasting.
4770254721Semaste
4771254721Semaste        ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
4772254721Semaste
4773254721Semaste        if (log)
4774254721Semaste        {
4775254721Semaste            StreamString s;
4776254721Semaste            thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4777254721Semaste            log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
4778254721Semaste                         thread->GetIndexID(),
4779254721Semaste                         thread->GetID(),
4780254721Semaste                         s.GetData());
4781254721Semaste        }
4782254721Semaste
4783254721Semaste        bool got_event;
4784254721Semaste        lldb::EventSP event_sp;
4785254721Semaste        lldb::StateType stop_state = lldb::eStateInvalid;
4786254721Semaste
4787254721Semaste        TimeValue* timeout_ptr = NULL;
4788254721Semaste        TimeValue real_timeout;
4789254721Semaste
4790254721Semaste        bool before_first_timeout = true;  // This is set to false the first time that we have to halt the target.
4791254721Semaste        bool do_resume = true;
4792254721Semaste        bool handle_running_event = true;
4793254721Semaste        const uint64_t default_one_thread_timeout_usec = 250000;
4794254721Semaste
4795254721Semaste        // This is just for accounting:
4796254721Semaste        uint32_t num_resumes = 0;
4797254721Semaste
4798254721Semaste        TimeValue one_thread_timeout = TimeValue::Now();
4799254721Semaste        TimeValue final_timeout = one_thread_timeout;
4800254721Semaste
4801254721Semaste        if (run_others)
4802254721Semaste        {
4803254721Semaste            // If we are running all threads then we take half the time to run all threads, bounded by
4804254721Semaste            // .25 sec.
4805254721Semaste            if (timeout_usec == 0)
4806254721Semaste                one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4807254721Semaste            else
4808254721Semaste            {
4809254721Semaste                uint64_t computed_timeout = timeout_usec / 2;
4810254721Semaste                if (computed_timeout > default_one_thread_timeout_usec)
4811254721Semaste                    computed_timeout = default_one_thread_timeout_usec;
4812254721Semaste                one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4813254721Semaste            }
4814254721Semaste            final_timeout.OffsetWithMicroSeconds (timeout_usec);
4815254721Semaste        }
4816254721Semaste        else
4817254721Semaste        {
4818254721Semaste            if (timeout_usec != 0)
4819254721Semaste                final_timeout.OffsetWithMicroSeconds(timeout_usec);
4820254721Semaste        }
4821254721Semaste
4822254721Semaste        // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4823254721Semaste        // So don't call return anywhere within it.
4824254721Semaste
4825254721Semaste        while (1)
4826254721Semaste        {
4827254721Semaste            // We usually want to resume the process if we get to the top of the loop.
4828254721Semaste            // The only exception is if we get two running events with no intervening
4829254721Semaste            // stop, which can happen, we will just wait for then next stop event.
4830254721Semaste            if (log)
4831254721Semaste                log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4832254721Semaste                             do_resume,
4833254721Semaste                             handle_running_event,
4834254721Semaste                             before_first_timeout);
4835254721Semaste
4836254721Semaste            if (do_resume || handle_running_event)
4837254721Semaste            {
4838254721Semaste                // Do the initial resume and wait for the running event before going further.
4839254721Semaste
4840254721Semaste                if (do_resume)
4841254721Semaste                {
4842254721Semaste                    num_resumes++;
4843254721Semaste                    Error resume_error = PrivateResume ();
4844254721Semaste                    if (!resume_error.Success())
4845254721Semaste                    {
4846254721Semaste                        errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4847254721Semaste                                      num_resumes,
4848254721Semaste                                      resume_error.AsCString());
4849254721Semaste                        return_value = eExecutionSetupError;
4850254721Semaste                        break;
4851254721Semaste                    }
4852254721Semaste                }
4853254721Semaste
4854254721Semaste                TimeValue resume_timeout = TimeValue::Now();
4855254721Semaste                resume_timeout.OffsetWithMicroSeconds(500000);
4856254721Semaste
4857254721Semaste                got_event = listener.WaitForEvent(&resume_timeout, event_sp);
4858254721Semaste                if (!got_event)
4859254721Semaste                {
4860254721Semaste                    if (log)
4861254721Semaste                        log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4862254721Semaste                                        num_resumes);
4863254721Semaste
4864254721Semaste                    errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
4865254721Semaste                    return_value = eExecutionSetupError;
4866254721Semaste                    break;
4867254721Semaste                }
4868254721Semaste
4869254721Semaste                stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4870254721Semaste
4871254721Semaste                if (stop_state != eStateRunning)
4872254721Semaste                {
4873254721Semaste                    bool restarted = false;
4874254721Semaste
4875254721Semaste                    if (stop_state == eStateStopped)
4876254721Semaste                    {
4877254721Semaste                        restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4878254721Semaste                        if (log)
4879254721Semaste                            log->Printf("Process::RunThreadPlan(): didn't get running event after "
4880254721Semaste                                        "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4881254721Semaste                                        num_resumes,
4882254721Semaste                                        StateAsCString(stop_state),
4883254721Semaste                                        restarted,
4884254721Semaste                                        do_resume,
4885254721Semaste                                        handle_running_event);
4886254721Semaste                    }
4887254721Semaste
4888254721Semaste                    if (restarted)
4889254721Semaste                    {
4890254721Semaste                        // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4891254721Semaste                        // event here.  But if I do, the best thing is to Halt and then get out of here.
4892254721Semaste                        Halt();
4893254721Semaste                    }
4894254721Semaste
4895254721Semaste                    errors.Printf("Didn't get running event after initial resume, got %s instead.",
4896254721Semaste                                  StateAsCString(stop_state));
4897254721Semaste                    return_value = eExecutionSetupError;
4898254721Semaste                    break;
4899254721Semaste                }
4900254721Semaste
4901254721Semaste                if (log)
4902254721Semaste                    log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4903254721Semaste                // We need to call the function synchronously, so spin waiting for it to return.
4904254721Semaste                // If we get interrupted while executing, we're going to lose our context, and
4905254721Semaste                // won't be able to gather the result at this point.
4906254721Semaste                // We set the timeout AFTER the resume, since the resume takes some time and we
4907254721Semaste                // don't want to charge that to the timeout.
4908254721Semaste            }
4909254721Semaste            else
4910254721Semaste            {
4911254721Semaste                if (log)
4912254721Semaste                    log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
4913254721Semaste            }
4914254721Semaste
4915254721Semaste            if (before_first_timeout)
4916254721Semaste            {
4917254721Semaste                if (run_others)
4918254721Semaste                    timeout_ptr = &one_thread_timeout;
4919254721Semaste                else
4920254721Semaste                {
4921254721Semaste                    if (timeout_usec == 0)
4922254721Semaste                        timeout_ptr = NULL;
4923254721Semaste                    else
4924254721Semaste                        timeout_ptr = &final_timeout;
4925254721Semaste                }
4926254721Semaste            }
4927254721Semaste            else
4928254721Semaste            {
4929254721Semaste                if (timeout_usec == 0)
4930254721Semaste                    timeout_ptr = NULL;
4931254721Semaste                else
4932254721Semaste                    timeout_ptr = &final_timeout;
4933254721Semaste            }
4934254721Semaste
4935254721Semaste            do_resume = true;
4936254721Semaste            handle_running_event = true;
4937254721Semaste
4938254721Semaste            // Now wait for the process to stop again:
4939254721Semaste            event_sp.reset();
4940254721Semaste
4941254721Semaste            if (log)
4942254721Semaste            {
4943254721Semaste                if (timeout_ptr)
4944254721Semaste                {
4945254721Semaste                    log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
4946254721Semaste                                 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4947254721Semaste                                 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
4948254721Semaste                }
4949254721Semaste                else
4950254721Semaste                {
4951254721Semaste                    log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4952254721Semaste                }
4953254721Semaste            }
4954254721Semaste
4955254721Semaste            got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4956254721Semaste
4957254721Semaste            if (got_event)
4958254721Semaste            {
4959254721Semaste                if (event_sp.get())
4960254721Semaste                {
4961254721Semaste                    bool keep_going = false;
4962254721Semaste                    if (event_sp->GetType() == eBroadcastBitInterrupt)
4963254721Semaste                    {
4964254721Semaste                        Halt();
4965254721Semaste                        return_value = eExecutionInterrupted;
4966254721Semaste                        errors.Printf ("Execution halted by user interrupt.");
4967254721Semaste                        if (log)
4968254721Semaste                            log->Printf ("Process::RunThreadPlan(): Got  interrupted by eBroadcastBitInterrupted, exiting.");
4969254721Semaste                        break;
4970254721Semaste                    }
4971254721Semaste                    else
4972254721Semaste                    {
4973254721Semaste                        stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4974254721Semaste                        if (log)
4975254721Semaste                            log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4976254721Semaste
4977254721Semaste                        switch (stop_state)
4978254721Semaste                        {
4979254721Semaste                        case lldb::eStateStopped:
4980254721Semaste                            {
4981254721Semaste                                // We stopped, figure out what we are going to do now.
4982254721Semaste                                ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4983254721Semaste                                if (!thread_sp)
4984254721Semaste                                {
4985254721Semaste                                    // Ooh, our thread has vanished.  Unlikely that this was successful execution...
4986254721Semaste                                    if (log)
4987254721Semaste                                        log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4988254721Semaste                                    return_value = eExecutionInterrupted;
4989254721Semaste                                }
4990254721Semaste                                else
4991254721Semaste                                {
4992254721Semaste                                    // If we were restarted, we just need to go back up to fetch another event.
4993254721Semaste                                    if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4994254721Semaste                                    {
4995254721Semaste                                        if (log)
4996254721Semaste                                        {
4997254721Semaste                                            log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4998254721Semaste                                        }
4999254721Semaste                                       keep_going = true;
5000254721Semaste                                       do_resume = false;
5001254721Semaste                                       handle_running_event = true;
5002254721Semaste
5003254721Semaste                                    }
5004254721Semaste                                    else
5005254721Semaste                                    {
5006254721Semaste
5007254721Semaste                                        StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5008254721Semaste                                        StopReason stop_reason = eStopReasonInvalid;
5009254721Semaste                                        if (stop_info_sp)
5010254721Semaste                                             stop_reason = stop_info_sp->GetStopReason();
5011254721Semaste
5012254721Semaste
5013254721Semaste                                        // FIXME: We only check if the stop reason is plan complete, should we make sure that
5014254721Semaste                                        // it is OUR plan that is complete?
5015254721Semaste                                        if (stop_reason == eStopReasonPlanComplete)
5016254721Semaste                                        {
5017254721Semaste                                            if (log)
5018254721Semaste                                                log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5019254721Semaste                                            // Now mark this plan as private so it doesn't get reported as the stop reason
5020254721Semaste                                            // after this point.
5021254721Semaste                                            if (thread_plan_sp)
5022254721Semaste                                                thread_plan_sp->SetPrivate (orig_plan_private);
5023254721Semaste                                            return_value = eExecutionCompleted;
5024254721Semaste                                        }
5025254721Semaste                                        else
5026254721Semaste                                        {
5027254721Semaste                                            // Something restarted the target, so just wait for it to stop for real.
5028254721Semaste                                            if (stop_reason == eStopReasonBreakpoint)
5029254721Semaste                                            {
5030254721Semaste                                                if (log)
5031254721Semaste                                                    log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
5032254721Semaste                                                return_value = eExecutionHitBreakpoint;
5033254721Semaste                                                if (!ignore_breakpoints)
5034254721Semaste                                                {
5035254721Semaste                                                    event_to_broadcast_sp = event_sp;
5036254721Semaste                                                }
5037254721Semaste                                            }
5038254721Semaste                                            else
5039254721Semaste                                            {
5040254721Semaste                                                if (log)
5041254721Semaste                                                    log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
5042254721Semaste                                                if (!unwind_on_error)
5043254721Semaste                                                    event_to_broadcast_sp = event_sp;
5044254721Semaste                                                return_value = eExecutionInterrupted;
5045254721Semaste                                            }
5046254721Semaste                                        }
5047254721Semaste                                    }
5048254721Semaste                                }
5049254721Semaste                            }
5050254721Semaste                            break;
5051254721Semaste
5052254721Semaste                        case lldb::eStateRunning:
5053254721Semaste                            // This shouldn't really happen, but sometimes we do get two running events without an
5054254721Semaste                            // intervening stop, and in that case we should just go back to waiting for the stop.
5055254721Semaste                            do_resume = false;
5056254721Semaste                            keep_going = true;
5057254721Semaste                            handle_running_event = false;
5058254721Semaste                            break;
5059254721Semaste
5060254721Semaste                        default:
5061254721Semaste                            if (log)
5062254721Semaste                                log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5063254721Semaste
5064254721Semaste                            if (stop_state == eStateExited)
5065254721Semaste                                event_to_broadcast_sp = event_sp;
5066254721Semaste
5067254721Semaste                            errors.Printf ("Execution stopped with unexpected state.\n");
5068254721Semaste                            return_value = eExecutionInterrupted;
5069254721Semaste                            break;
5070254721Semaste                        }
5071254721Semaste                    }
5072254721Semaste
5073254721Semaste                    if (keep_going)
5074254721Semaste                        continue;
5075254721Semaste                    else
5076254721Semaste                        break;
5077254721Semaste                }
5078254721Semaste                else
5079254721Semaste                {
5080254721Semaste                    if (log)
5081254721Semaste                        log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null.  How odd...");
5082254721Semaste                    return_value = eExecutionInterrupted;
5083254721Semaste                    break;
5084254721Semaste                }
5085254721Semaste            }
5086254721Semaste            else
5087254721Semaste            {
5088254721Semaste                // If we didn't get an event that means we've timed out...
5089254721Semaste                // We will interrupt the process here.  Depending on what we were asked to do we will
5090254721Semaste                // either exit, or try with all threads running for the same timeout.
5091254721Semaste
5092254721Semaste                if (log) {
5093254721Semaste                    if (run_others)
5094254721Semaste                    {
5095254721Semaste                        uint64_t remaining_time = final_timeout - TimeValue::Now();
5096254721Semaste                        if (before_first_timeout)
5097254721Semaste                            log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5098254721Semaste                                         "running till  for %" PRId64 " usec with all threads enabled.",
5099254721Semaste                                         remaining_time);
5100254721Semaste                        else
5101254721Semaste                            log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
5102254721Semaste                                         "and timeout: %d timed out, abandoning execution.",
5103254721Semaste                                         timeout_usec);
5104254721Semaste                    }
5105254721Semaste                    else
5106254721Semaste                        log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
5107254721Semaste                                     "abandoning execution.",
5108254721Semaste                                     timeout_usec);
5109254721Semaste                }
5110254721Semaste
5111254721Semaste                // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5112254721Semaste                // could have stopped.  That's fine, Halt will figure that out and send the appropriate Stopped event.
5113254721Semaste                // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.)  In
5114254721Semaste                // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5115254721Semaste                // stopped event.  That's what this while loop does.
5116254721Semaste
5117254721Semaste                bool back_to_top = true;
5118254721Semaste                uint32_t try_halt_again = 0;
5119254721Semaste                bool do_halt = true;
5120254721Semaste                const uint32_t num_retries = 5;
5121254721Semaste                while (try_halt_again < num_retries)
5122254721Semaste                {
5123254721Semaste                    Error halt_error;
5124254721Semaste                    if (do_halt)
5125254721Semaste                    {
5126254721Semaste                        if (log)
5127254721Semaste                            log->Printf ("Process::RunThreadPlan(): Running Halt.");
5128254721Semaste                        halt_error = Halt();
5129254721Semaste                    }
5130254721Semaste                    if (halt_error.Success())
5131254721Semaste                    {
5132254721Semaste                        if (log)
5133254721Semaste                            log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5134254721Semaste
5135254721Semaste                        real_timeout = TimeValue::Now();
5136254721Semaste                        real_timeout.OffsetWithMicroSeconds(500000);
5137254721Semaste
5138254721Semaste                        got_event = listener.WaitForEvent(&real_timeout, event_sp);
5139254721Semaste
5140254721Semaste                        if (got_event)
5141254721Semaste                        {
5142254721Semaste                            stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5143254721Semaste                            if (log)
5144254721Semaste                            {
5145254721Semaste                                log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5146254721Semaste                                if (stop_state == lldb::eStateStopped
5147254721Semaste                                    && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5148254721Semaste                                    log->PutCString ("    Event was the Halt interruption event.");
5149254721Semaste                            }
5150254721Semaste
5151254721Semaste                            if (stop_state == lldb::eStateStopped)
5152254721Semaste                            {
5153254721Semaste                                // Between the time we initiated the Halt and the time we delivered it, the process could have
5154254721Semaste                                // already finished its job.  Check that here:
5155254721Semaste
5156254721Semaste                                if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5157254721Semaste                                {
5158254721Semaste                                    if (log)
5159254721Semaste                                        log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done.  "
5160254721Semaste                                                     "Exiting wait loop.");
5161254721Semaste                                    return_value = eExecutionCompleted;
5162254721Semaste                                    back_to_top = false;
5163254721Semaste                                    break;
5164254721Semaste                                }
5165254721Semaste
5166254721Semaste                                if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5167254721Semaste                                {
5168254721Semaste                                    if (log)
5169254721Semaste                                        log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again...  "
5170254721Semaste                                                     "Exiting wait loop.");
5171254721Semaste                                    try_halt_again++;
5172254721Semaste                                    do_halt = false;
5173254721Semaste                                    continue;
5174254721Semaste                                }
5175254721Semaste
5176254721Semaste                                if (!run_others)
5177254721Semaste                                {
5178254721Semaste                                    if (log)
5179254721Semaste                                        log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5180254721Semaste                                    return_value = eExecutionInterrupted;
5181254721Semaste                                    back_to_top = false;
5182254721Semaste                                    break;
5183254721Semaste                                }
5184254721Semaste
5185254721Semaste                                if (before_first_timeout)
5186254721Semaste                                {
5187254721Semaste                                    // Set all the other threads to run, and return to the top of the loop, which will continue;
5188254721Semaste                                    before_first_timeout = false;
5189254721Semaste                                    thread_plan_sp->SetStopOthers (false);
5190254721Semaste                                    if (log)
5191254721Semaste                                        log->PutCString ("Process::RunThreadPlan(): about to resume.");
5192254721Semaste
5193254721Semaste                                    back_to_top = true;
5194254721Semaste                                    break;
5195254721Semaste                                }
5196254721Semaste                                else
5197254721Semaste                                {
5198254721Semaste                                    // Running all threads failed, so return Interrupted.
5199254721Semaste                                    if (log)
5200254721Semaste                                        log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5201254721Semaste                                    return_value = eExecutionInterrupted;
5202254721Semaste                                    back_to_top = false;
5203254721Semaste                                    break;
5204254721Semaste                                }
5205254721Semaste                            }
5206254721Semaste                        }
5207254721Semaste                        else
5208254721Semaste                        {   if (log)
5209254721Semaste                                log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event.  "
5210254721Semaste                                        "I'm getting out of here passing Interrupted.");
5211254721Semaste                            return_value = eExecutionInterrupted;
5212254721Semaste                            back_to_top = false;
5213254721Semaste                            break;
5214254721Semaste                        }
5215254721Semaste                    }
5216254721Semaste                    else
5217254721Semaste                    {
5218254721Semaste                        try_halt_again++;
5219254721Semaste                        continue;
5220254721Semaste                    }
5221254721Semaste                }
5222254721Semaste
5223254721Semaste                if (!back_to_top || try_halt_again > num_retries)
5224254721Semaste                    break;
5225254721Semaste                else
5226254721Semaste                    continue;
5227254721Semaste            }
5228254721Semaste        }  // END WAIT LOOP
5229254721Semaste
5230254721Semaste        // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5231254721Semaste        if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5232254721Semaste        {
5233254721Semaste            StopPrivateStateThread();
5234254721Semaste            Error error;
5235254721Semaste            m_private_state_thread = backup_private_state_thread;
5236254721Semaste            if (stopper_base_plan_sp)
5237254721Semaste            {
5238254721Semaste                thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5239254721Semaste            }
5240254721Semaste            m_public_state.SetValueNoLock(old_state);
5241254721Semaste
5242254721Semaste        }
5243254721Semaste
5244254721Semaste        // Restore the thread state if we are going to discard the plan execution.  There are three cases where this
5245254721Semaste        // could happen:
5246254721Semaste        // 1) The execution successfully completed
5247254721Semaste        // 2) We hit a breakpoint, and ignore_breakpoints was true
5248254721Semaste        // 3) We got some other error, and discard_on_error was true
5249254721Semaste        bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5250254721Semaste                             || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
5251254721Semaste
5252254721Semaste        if (return_value == eExecutionCompleted
5253254721Semaste            || should_unwind)
5254254721Semaste        {
5255254721Semaste            thread_plan_sp->RestoreThreadState();
5256254721Semaste        }
5257254721Semaste
5258254721Semaste        // Now do some processing on the results of the run:
5259254721Semaste        if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
5260254721Semaste        {
5261254721Semaste            if (log)
5262254721Semaste            {
5263254721Semaste                StreamString s;
5264254721Semaste                if (event_sp)
5265254721Semaste                    event_sp->Dump (&s);
5266254721Semaste                else
5267254721Semaste                {
5268254721Semaste                    log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5269254721Semaste                }
5270254721Semaste
5271254721Semaste                StreamString ts;
5272254721Semaste
5273254721Semaste                const char *event_explanation = NULL;
5274254721Semaste
5275254721Semaste                do
5276254721Semaste                {
5277254721Semaste                    if (!event_sp)
5278254721Semaste                    {
5279254721Semaste                        event_explanation = "<no event>";
5280254721Semaste                        break;
5281254721Semaste                    }
5282254721Semaste                    else if (event_sp->GetType() == eBroadcastBitInterrupt)
5283254721Semaste                    {
5284254721Semaste                        event_explanation = "<user interrupt>";
5285254721Semaste                        break;
5286254721Semaste                    }
5287254721Semaste                    else
5288254721Semaste                    {
5289254721Semaste                        const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5290254721Semaste
5291254721Semaste                        if (!event_data)
5292254721Semaste                        {
5293254721Semaste                            event_explanation = "<no event data>";
5294254721Semaste                            break;
5295254721Semaste                        }
5296254721Semaste
5297254721Semaste                        Process *process = event_data->GetProcessSP().get();
5298254721Semaste
5299254721Semaste                        if (!process)
5300254721Semaste                        {
5301254721Semaste                            event_explanation = "<no process>";
5302254721Semaste                            break;
5303254721Semaste                        }
5304254721Semaste
5305254721Semaste                        ThreadList &thread_list = process->GetThreadList();
5306254721Semaste
5307254721Semaste                        uint32_t num_threads = thread_list.GetSize();
5308254721Semaste                        uint32_t thread_index;
5309254721Semaste
5310254721Semaste                        ts.Printf("<%u threads> ", num_threads);
5311254721Semaste
5312254721Semaste                        for (thread_index = 0;
5313254721Semaste                             thread_index < num_threads;
5314254721Semaste                             ++thread_index)
5315254721Semaste                        {
5316254721Semaste                            Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5317254721Semaste
5318254721Semaste                            if (!thread)
5319254721Semaste                            {
5320254721Semaste                                ts.Printf("<?> ");
5321254721Semaste                                continue;
5322254721Semaste                            }
5323254721Semaste
5324254721Semaste                            ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5325254721Semaste                            RegisterContext *register_context = thread->GetRegisterContext().get();
5326254721Semaste
5327254721Semaste                            if (register_context)
5328254721Semaste                                ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5329254721Semaste                            else
5330254721Semaste                                ts.Printf("[ip unknown] ");
5331254721Semaste
5332254721Semaste                            lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5333254721Semaste                            if (stop_info_sp)
5334254721Semaste                            {
5335254721Semaste                                const char *stop_desc = stop_info_sp->GetDescription();
5336254721Semaste                                if (stop_desc)
5337254721Semaste                                    ts.PutCString (stop_desc);
5338254721Semaste                            }
5339254721Semaste                            ts.Printf(">");
5340254721Semaste                        }
5341254721Semaste
5342254721Semaste                        event_explanation = ts.GetData();
5343254721Semaste                    }
5344254721Semaste                } while (0);
5345254721Semaste
5346254721Semaste                if (event_explanation)
5347254721Semaste                    log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
5348254721Semaste                else
5349254721Semaste                    log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5350254721Semaste            }
5351254721Semaste
5352254721Semaste            if (should_unwind && thread_plan_sp)
5353254721Semaste            {
5354254721Semaste                if (log)
5355254721Semaste                    log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5356254721Semaste                thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5357254721Semaste                thread_plan_sp->SetPrivate (orig_plan_private);
5358254721Semaste            }
5359254721Semaste            else
5360254721Semaste            {
5361254721Semaste                if (log)
5362254721Semaste                    log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
5363254721Semaste            }
5364254721Semaste        }
5365254721Semaste        else if (return_value == eExecutionSetupError)
5366254721Semaste        {
5367254721Semaste            if (log)
5368254721Semaste                log->PutCString("Process::RunThreadPlan(): execution set up error.");
5369254721Semaste
5370254721Semaste            if (unwind_on_error && thread_plan_sp)
5371254721Semaste            {
5372254721Semaste                thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5373254721Semaste                thread_plan_sp->SetPrivate (orig_plan_private);
5374254721Semaste            }
5375254721Semaste        }
5376254721Semaste        else
5377254721Semaste        {
5378254721Semaste            if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5379254721Semaste            {
5380254721Semaste                if (log)
5381254721Semaste                    log->PutCString("Process::RunThreadPlan(): thread plan is done");
5382254721Semaste                return_value = eExecutionCompleted;
5383254721Semaste            }
5384254721Semaste            else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5385254721Semaste            {
5386254721Semaste                if (log)
5387254721Semaste                    log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5388254721Semaste                return_value = eExecutionDiscarded;
5389254721Semaste            }
5390254721Semaste            else
5391254721Semaste            {
5392254721Semaste                if (log)
5393254721Semaste                    log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
5394254721Semaste                if (unwind_on_error && thread_plan_sp)
5395254721Semaste                {
5396254721Semaste                    if (log)
5397254721Semaste                        log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
5398254721Semaste                    thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5399254721Semaste                    thread_plan_sp->SetPrivate (orig_plan_private);
5400254721Semaste                }
5401254721Semaste            }
5402254721Semaste        }
5403254721Semaste
5404254721Semaste        // Thread we ran the function in may have gone away because we ran the target
5405254721Semaste        // Check that it's still there, and if it is put it back in the context.  Also restore the
5406254721Semaste        // frame in the context if it is still present.
5407254721Semaste        thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5408254721Semaste        if (thread)
5409254721Semaste        {
5410254721Semaste            exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5411254721Semaste        }
5412254721Semaste
5413254721Semaste        // Also restore the current process'es selected frame & thread, since this function calling may
5414254721Semaste        // be done behind the user's back.
5415254721Semaste
5416254721Semaste        if (selected_tid != LLDB_INVALID_THREAD_ID)
5417254721Semaste        {
5418254721Semaste            if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5419254721Semaste            {
5420254721Semaste                // We were able to restore the selected thread, now restore the frame:
5421254721Semaste                Mutex::Locker lock(GetThreadList().GetMutex());
5422254721Semaste                StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5423254721Semaste                if (old_frame_sp)
5424254721Semaste                    GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
5425254721Semaste            }
5426254721Semaste        }
5427254721Semaste    }
5428254721Semaste
5429254721Semaste    // If the process exited during the run of the thread plan, notify everyone.
5430254721Semaste
5431254721Semaste    if (event_to_broadcast_sp)
5432254721Semaste    {
5433254721Semaste        if (log)
5434254721Semaste            log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5435254721Semaste        BroadcastEvent(event_to_broadcast_sp);
5436254721Semaste    }
5437254721Semaste
5438254721Semaste    return return_value;
5439254721Semaste}
5440254721Semaste
5441254721Semasteconst char *
5442254721SemasteProcess::ExecutionResultAsCString (ExecutionResults result)
5443254721Semaste{
5444254721Semaste    const char *result_name;
5445254721Semaste
5446254721Semaste    switch (result)
5447254721Semaste    {
5448254721Semaste        case eExecutionCompleted:
5449254721Semaste            result_name = "eExecutionCompleted";
5450254721Semaste            break;
5451254721Semaste        case eExecutionDiscarded:
5452254721Semaste            result_name = "eExecutionDiscarded";
5453254721Semaste            break;
5454254721Semaste        case eExecutionInterrupted:
5455254721Semaste            result_name = "eExecutionInterrupted";
5456254721Semaste            break;
5457254721Semaste        case eExecutionHitBreakpoint:
5458254721Semaste            result_name = "eExecutionHitBreakpoint";
5459254721Semaste            break;
5460254721Semaste        case eExecutionSetupError:
5461254721Semaste            result_name = "eExecutionSetupError";
5462254721Semaste            break;
5463254721Semaste        case eExecutionTimedOut:
5464254721Semaste            result_name = "eExecutionTimedOut";
5465254721Semaste            break;
5466254721Semaste    }
5467254721Semaste    return result_name;
5468254721Semaste}
5469254721Semaste
5470254721Semastevoid
5471254721SemasteProcess::GetStatus (Stream &strm)
5472254721Semaste{
5473254721Semaste    const StateType state = GetState();
5474254721Semaste    if (StateIsStoppedState(state, false))
5475254721Semaste    {
5476254721Semaste        if (state == eStateExited)
5477254721Semaste        {
5478254721Semaste            int exit_status = GetExitStatus();
5479254721Semaste            const char *exit_description = GetExitDescription();
5480254721Semaste            strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5481254721Semaste                          GetID(),
5482254721Semaste                          exit_status,
5483254721Semaste                          exit_status,
5484254721Semaste                          exit_description ? exit_description : "");
5485254721Semaste        }
5486254721Semaste        else
5487254721Semaste        {
5488254721Semaste            if (state == eStateConnected)
5489254721Semaste                strm.Printf ("Connected to remote target.\n");
5490254721Semaste            else
5491254721Semaste                strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
5492254721Semaste        }
5493254721Semaste    }
5494254721Semaste    else
5495254721Semaste    {
5496254721Semaste        strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
5497254721Semaste    }
5498254721Semaste}
5499254721Semaste
5500254721Semastesize_t
5501254721SemasteProcess::GetThreadStatus (Stream &strm,
5502254721Semaste                          bool only_threads_with_stop_reason,
5503254721Semaste                          uint32_t start_frame,
5504254721Semaste                          uint32_t num_frames,
5505254721Semaste                          uint32_t num_frames_with_source)
5506254721Semaste{
5507254721Semaste    size_t num_thread_infos_dumped = 0;
5508254721Semaste
5509254721Semaste    Mutex::Locker locker (GetThreadList().GetMutex());
5510254721Semaste    const size_t num_threads = GetThreadList().GetSize();
5511254721Semaste    for (uint32_t i = 0; i < num_threads; i++)
5512254721Semaste    {
5513254721Semaste        Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5514254721Semaste        if (thread)
5515254721Semaste        {
5516254721Semaste            if (only_threads_with_stop_reason)
5517254721Semaste            {
5518254721Semaste                StopInfoSP stop_info_sp = thread->GetStopInfo();
5519254721Semaste                if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
5520254721Semaste                    continue;
5521254721Semaste            }
5522254721Semaste            thread->GetStatus (strm,
5523254721Semaste                               start_frame,
5524254721Semaste                               num_frames,
5525254721Semaste                               num_frames_with_source);
5526254721Semaste            ++num_thread_infos_dumped;
5527254721Semaste        }
5528254721Semaste    }
5529254721Semaste    return num_thread_infos_dumped;
5530254721Semaste}
5531254721Semaste
5532254721Semastevoid
5533254721SemasteProcess::AddInvalidMemoryRegion (const LoadRange &region)
5534254721Semaste{
5535254721Semaste    m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5536254721Semaste}
5537254721Semaste
5538254721Semastebool
5539254721SemasteProcess::RemoveInvalidMemoryRange (const LoadRange &region)
5540254721Semaste{
5541254721Semaste    return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5542254721Semaste}
5543254721Semaste
5544254721Semastevoid
5545254721SemasteProcess::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5546254721Semaste{
5547254721Semaste    m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5548254721Semaste}
5549254721Semaste
5550254721Semastebool
5551254721SemasteProcess::RunPreResumeActions ()
5552254721Semaste{
5553254721Semaste    bool result = true;
5554254721Semaste    while (!m_pre_resume_actions.empty())
5555254721Semaste    {
5556254721Semaste        struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5557254721Semaste        m_pre_resume_actions.pop_back();
5558254721Semaste        bool this_result = action.callback (action.baton);
5559254721Semaste        if (result == true) result = this_result;
5560254721Semaste    }
5561254721Semaste    return result;
5562254721Semaste}
5563254721Semaste
5564254721Semastevoid
5565254721SemasteProcess::ClearPreResumeActions ()
5566254721Semaste{
5567254721Semaste    m_pre_resume_actions.clear();
5568254721Semaste}
5569254721Semaste
5570254721Semastevoid
5571254721SemasteProcess::Flush ()
5572254721Semaste{
5573254721Semaste    m_thread_list.Flush();
5574254721Semaste}
5575254721Semaste
5576254721Semastevoid
5577254721SemasteProcess::DidExec ()
5578254721Semaste{
5579254721Semaste    Target &target = GetTarget();
5580254721Semaste    target.CleanupProcess ();
5581254721Semaste    ModuleList unloaded_modules (target.GetImages());
5582254721Semaste    target.ModulesDidUnload (unloaded_modules);
5583254721Semaste    target.GetSectionLoadList().Clear();
5584254721Semaste    m_dynamic_checkers_ap.reset();
5585254721Semaste    m_abi_sp.reset();
5586254721Semaste    m_os_ap.reset();
5587254721Semaste    m_dyld_ap.reset();
5588254721Semaste    m_image_tokens.clear();
5589254721Semaste    m_allocated_memory_cache.Clear();
5590254721Semaste    m_language_runtimes.clear();
5591254721Semaste    m_thread_list.DiscardThreadPlans();
5592254721Semaste    m_memory_cache.Clear(true);
5593254721Semaste    DoDidExec();
5594254721Semaste    CompleteAttach ();
5595254721Semaste}
5596