Process.cpp revision 1f3dd643e10552de04644986a603f7ff02ed4beb
1//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
17#include "lldb/Core/ConnectionFileDescriptor.h"
18#include "lldb/Core/Debugger.h"
19#include "lldb/Core/InputReader.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
23#include "lldb/Interpreter/CommandInterpreter.h"
24#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
26#include "lldb/Target/DynamicLoader.h"
27#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
30#include "lldb/Target/RegisterContext.h"
31#include "lldb/Target/StopInfo.h"
32#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
40Process*
41Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
42{
43    ProcessCreateInstance create_callback = NULL;
44    if (plugin_name)
45    {
46        create_callback  = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
47        if (create_callback)
48        {
49            std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
50            if (debugger_ap->CanDebug(target))
51                return debugger_ap.release();
52        }
53    }
54    else
55    {
56        for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
57        {
58            std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
59            if (debugger_ap->CanDebug(target))
60                return debugger_ap.release();
61        }
62    }
63    return NULL;
64}
65
66
67//----------------------------------------------------------------------
68// Process constructor
69//----------------------------------------------------------------------
70Process::Process(Target &target, Listener &listener) :
71    UserID (LLDB_INVALID_PROCESS_ID),
72    Broadcaster ("lldb.process"),
73    ProcessInstanceSettings (*GetSettingsController()),
74    m_target (target),
75    m_public_state (eStateUnloaded),
76    m_private_state (eStateUnloaded),
77    m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
78    m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
79    m_private_state_listener ("lldb.process.internal_state_listener"),
80    m_private_state_control_wait(),
81    m_private_state_thread (LLDB_INVALID_HOST_THREAD),
82    m_stop_id (0),
83    m_thread_index_id (0),
84    m_exit_status (-1),
85    m_exit_string (),
86    m_thread_list (this),
87    m_notifications (),
88    m_image_tokens (),
89    m_listener (listener),
90    m_breakpoint_site_list (),
91    m_dynamic_checkers_ap (),
92    m_unix_signals (),
93    m_target_triple (),
94    m_byte_order (eByteOrderHost),
95    m_addr_byte_size (0),
96    m_abi_sp (),
97    m_process_input_reader (),
98    m_stdio_communication ("lldb.process.stdio"),
99    m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
100    m_stdout_data ()
101{
102    UpdateInstanceName();
103
104    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
105    if (log)
106        log->Printf ("%p Process::Process()", this);
107
108    SetEventName (eBroadcastBitStateChanged, "state-changed");
109    SetEventName (eBroadcastBitInterrupt, "interrupt");
110    SetEventName (eBroadcastBitSTDOUT, "stdout-available");
111    SetEventName (eBroadcastBitSTDERR, "stderr-available");
112
113    listener.StartListeningForEvents (this,
114                                      eBroadcastBitStateChanged |
115                                      eBroadcastBitInterrupt |
116                                      eBroadcastBitSTDOUT |
117                                      eBroadcastBitSTDERR);
118
119    m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
120                                                     eBroadcastBitStateChanged);
121
122    m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
123                                                     eBroadcastInternalStateControlStop |
124                                                     eBroadcastInternalStateControlPause |
125                                                     eBroadcastInternalStateControlResume);
126}
127
128//----------------------------------------------------------------------
129// Destructor
130//----------------------------------------------------------------------
131Process::~Process()
132{
133    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
134    if (log)
135        log->Printf ("%p Process::~Process()", this);
136    StopPrivateStateThread();
137}
138
139void
140Process::Finalize()
141{
142    // Do any cleanup needed prior to being destructed... Subclasses
143    // that override this method should call this superclass method as well.
144}
145
146void
147Process::RegisterNotificationCallbacks (const Notifications& callbacks)
148{
149    m_notifications.push_back(callbacks);
150    if (callbacks.initialize != NULL)
151        callbacks.initialize (callbacks.baton, this);
152}
153
154bool
155Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
156{
157    std::vector<Notifications>::iterator pos, end = m_notifications.end();
158    for (pos = m_notifications.begin(); pos != end; ++pos)
159    {
160        if (pos->baton == callbacks.baton &&
161            pos->initialize == callbacks.initialize &&
162            pos->process_state_changed == callbacks.process_state_changed)
163        {
164            m_notifications.erase(pos);
165            return true;
166        }
167    }
168    return false;
169}
170
171void
172Process::SynchronouslyNotifyStateChanged (StateType state)
173{
174    std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
175    for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
176    {
177        if (notification_pos->process_state_changed)
178            notification_pos->process_state_changed (notification_pos->baton, this, state);
179    }
180}
181
182// FIXME: We need to do some work on events before the general Listener sees them.
183// For instance if we are continuing from a breakpoint, we need to ensure that we do
184// the little "insert real insn, step & stop" trick.  But we can't do that when the
185// event is delivered by the broadcaster - since that is done on the thread that is
186// waiting for new events, so if we needed more than one event for our handling, we would
187// stall.  So instead we do it when we fetch the event off of the queue.
188//
189
190StateType
191Process::GetNextEvent (EventSP &event_sp)
192{
193    StateType state = eStateInvalid;
194
195    if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
196        state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
197
198    return state;
199}
200
201
202StateType
203Process::WaitForProcessToStop (const TimeValue *timeout)
204{
205    StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
206    return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
207}
208
209
210StateType
211Process::WaitForState
212(
213    const TimeValue *timeout,
214    const StateType *match_states, const uint32_t num_match_states
215)
216{
217    EventSP event_sp;
218    uint32_t i;
219    StateType state = GetState();
220    while (state != eStateInvalid)
221    {
222        // If we are exited or detached, we won't ever get back to any
223        // other valid state...
224        if (state == eStateDetached || state == eStateExited)
225            return state;
226
227        state = WaitForStateChangedEvents (timeout, event_sp);
228
229        for (i=0; i<num_match_states; ++i)
230        {
231            if (match_states[i] == state)
232                return state;
233        }
234    }
235    return state;
236}
237
238bool
239Process::HijackProcessEvents (Listener *listener)
240{
241    if (listener != NULL)
242    {
243        return HijackBroadcaster(listener, eBroadcastBitStateChanged);
244    }
245    else
246        return false;
247}
248
249void
250Process::RestoreProcessEvents ()
251{
252    RestoreBroadcaster();
253}
254
255StateType
256Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
257{
258    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
259
260    if (log)
261        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
262
263    StateType state = eStateInvalid;
264    if (m_listener.WaitForEventForBroadcasterWithType (timeout,
265                                                       this,
266                                                       eBroadcastBitStateChanged,
267                                                       event_sp))
268        state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
269
270    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
271    if (log)
272        log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
273                     __FUNCTION__,
274                     timeout,
275                     StateAsCString(state));
276    return state;
277}
278
279Event *
280Process::PeekAtStateChangedEvents ()
281{
282    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
283
284    if (log)
285        log->Printf ("Process::%s...", __FUNCTION__);
286
287    Event *event_ptr;
288    event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
289                                                                  eBroadcastBitStateChanged);
290    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
291    if (log)
292    {
293        if (event_ptr)
294        {
295            log->Printf ("Process::%s (event_ptr) => %s",
296                         __FUNCTION__,
297                         StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
298        }
299        else
300        {
301            log->Printf ("Process::%s no events found",
302                         __FUNCTION__);
303        }
304    }
305    return event_ptr;
306}
307
308StateType
309Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
310{
311    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
312
313    if (log)
314        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
315
316    StateType state = eStateInvalid;
317    if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
318                                                                    &m_private_state_broadcaster,
319                                                                    eBroadcastBitStateChanged,
320                                                                    event_sp))
321        state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
322
323    // This is a bit of a hack, but when we wait here we could very well return
324    // to the command-line, and that could disable the log, which would render the
325    // log we got above invalid.
326    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
327    if (log)
328        log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
329    return state;
330}
331
332bool
333Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
334{
335    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
336
337    if (log)
338        log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
339
340    if (control_only)
341        return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
342    else
343        return m_private_state_listener.WaitForEvent(timeout, event_sp);
344}
345
346bool
347Process::IsRunning () const
348{
349    return StateIsRunningState (m_public_state.GetValue());
350}
351
352int
353Process::GetExitStatus ()
354{
355    if (m_public_state.GetValue() == eStateExited)
356        return m_exit_status;
357    return -1;
358}
359
360
361void
362Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
363{
364    if (m_inherit_host_env && !m_got_host_env)
365    {
366        m_got_host_env = true;
367        StringList host_env;
368        const size_t host_env_count = Host::GetEnvironment (host_env);
369        for (size_t idx=0; idx<host_env_count; idx++)
370        {
371            const char *env_entry = host_env.GetStringAtIndex (idx);
372            if (env_entry)
373            {
374                const char *equal_pos = ::strchr(env_entry, '=');
375                if (equal_pos)
376                {
377                    std::string key (env_entry, equal_pos - env_entry);
378                    std::string value (equal_pos + 1);
379                    if (m_env_vars.find (key) == m_env_vars.end())
380                        m_env_vars[key] = value;
381                }
382            }
383        }
384    }
385}
386
387
388size_t
389Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
390{
391    GetHostEnvironmentIfNeeded ();
392
393    dictionary::const_iterator pos, end = m_env_vars.end();
394    for (pos = m_env_vars.begin(); pos != end; ++pos)
395    {
396        std::string env_var_equal_value (pos->first);
397        env_var_equal_value.append(1, '=');
398        env_var_equal_value.append (pos->second);
399        env.AppendArgument (env_var_equal_value.c_str());
400    }
401    return env.GetArgumentCount();
402}
403
404
405const char *
406Process::GetExitDescription ()
407{
408    if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
409        return m_exit_string.c_str();
410    return NULL;
411}
412
413void
414Process::SetExitStatus (int status, const char *cstr)
415{
416    if (m_private_state.GetValue() != eStateExited)
417    {
418        m_exit_status = status;
419        if (cstr)
420            m_exit_string = cstr;
421        else
422            m_exit_string.clear();
423
424        DidExit ();
425
426        SetPrivateState (eStateExited);
427    }
428}
429
430// This static callback can be used to watch for local child processes on
431// the current host. The the child process exits, the process will be
432// found in the global target list (we want to be completely sure that the
433// lldb_private::Process doesn't go away before we can deliver the signal.
434bool
435Process::SetProcessExitStatus
436(
437    void *callback_baton,
438    lldb::pid_t pid,
439    int signo,      // Zero for no signal
440    int exit_status      // Exit value of process if signal is zero
441)
442{
443    if (signo == 0 || exit_status)
444    {
445        TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
446        if (target_sp)
447        {
448            ProcessSP process_sp (target_sp->GetProcessSP());
449            if (process_sp)
450            {
451                const char *signal_cstr = NULL;
452                if (signo)
453                    signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
454
455                process_sp->SetExitStatus (exit_status, signal_cstr);
456            }
457        }
458        return true;
459    }
460    return false;
461}
462
463
464uint32_t
465Process::GetNextThreadIndexID ()
466{
467    return ++m_thread_index_id;
468}
469
470StateType
471Process::GetState()
472{
473    // If any other threads access this we will need a mutex for it
474    return m_public_state.GetValue ();
475}
476
477void
478Process::SetPublicState (StateType new_state)
479{
480    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
481    if (log)
482        log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
483    m_public_state.SetValue (new_state);
484}
485
486StateType
487Process::GetPrivateState ()
488{
489    return m_private_state.GetValue();
490}
491
492void
493Process::SetPrivateState (StateType new_state)
494{
495    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
496    bool state_changed = false;
497
498    if (log)
499        log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
500
501    Mutex::Locker locker(m_private_state.GetMutex());
502
503    const StateType old_state = m_private_state.GetValueNoLock ();
504    state_changed = old_state != new_state;
505    if (state_changed)
506    {
507        m_private_state.SetValueNoLock (new_state);
508        if (StateIsStoppedState(new_state))
509        {
510            m_stop_id++;
511            if (log)
512                log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
513        }
514        // Use our target to get a shared pointer to ourselves...
515        m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
516    }
517    else
518    {
519        if (log)
520            log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
521    }
522}
523
524
525uint32_t
526Process::GetStopID() const
527{
528    return m_stop_id;
529}
530
531addr_t
532Process::GetImageInfoAddress()
533{
534    return LLDB_INVALID_ADDRESS;
535}
536
537//----------------------------------------------------------------------
538// LoadImage
539//
540// This function provides a default implementation that works for most
541// unix variants. Any Process subclasses that need to do shared library
542// loading differently should override LoadImage and UnloadImage and
543// do what is needed.
544//----------------------------------------------------------------------
545uint32_t
546Process::LoadImage (const FileSpec &image_spec, Error &error)
547{
548    DynamicLoader *loader = GetDynamicLoader();
549    if (loader)
550    {
551        error = loader->CanLoadImage();
552        if (error.Fail())
553            return LLDB_INVALID_IMAGE_TOKEN;
554    }
555
556    if (error.Success())
557    {
558        ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
559        if (thread_sp == NULL)
560            thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
561
562        if (thread_sp)
563        {
564            StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
565
566            if (frame_sp)
567            {
568                ExecutionContext exe_ctx;
569                frame_sp->CalculateExecutionContext (exe_ctx);
570                bool unwind_on_error = true;
571                StreamString expr;
572                char path[PATH_MAX];
573                image_spec.GetPath(path, sizeof(path));
574                expr.Printf("dlopen (\"%s\", 2)", path);
575                const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
576                lldb::ValueObjectSP result_valobj_sp;
577                ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
578                if (result_valobj_sp->GetError().Success())
579                {
580                    Scalar scalar;
581                    if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
582                    {
583                        addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
584                        if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
585                        {
586                            uint32_t image_token = m_image_tokens.size();
587                            m_image_tokens.push_back (image_ptr);
588                            return image_token;
589                        }
590                    }
591                }
592            }
593        }
594    }
595    return LLDB_INVALID_IMAGE_TOKEN;
596}
597
598//----------------------------------------------------------------------
599// UnloadImage
600//
601// This function provides a default implementation that works for most
602// unix variants. Any Process subclasses that need to do shared library
603// loading differently should override LoadImage and UnloadImage and
604// do what is needed.
605//----------------------------------------------------------------------
606Error
607Process::UnloadImage (uint32_t image_token)
608{
609    Error error;
610    if (image_token < m_image_tokens.size())
611    {
612        const addr_t image_addr = m_image_tokens[image_token];
613        if (image_addr == LLDB_INVALID_ADDRESS)
614        {
615            error.SetErrorString("image already unloaded");
616        }
617        else
618        {
619            DynamicLoader *loader = GetDynamicLoader();
620            if (loader)
621                error = loader->CanLoadImage();
622
623            if (error.Success())
624            {
625                ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
626                if (thread_sp == NULL)
627                    thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
628
629                if (thread_sp)
630                {
631                    StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
632
633                    if (frame_sp)
634                    {
635                        ExecutionContext exe_ctx;
636                        frame_sp->CalculateExecutionContext (exe_ctx);
637                        bool unwind_on_error = true;
638                        StreamString expr;
639                        expr.Printf("dlclose ((void *)0x%llx)", image_addr);
640                        const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
641                        lldb::ValueObjectSP result_valobj_sp;
642                        ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
643                        if (result_valobj_sp->GetError().Success())
644                        {
645                            Scalar scalar;
646                            if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
647                            {
648                                if (scalar.UInt(1))
649                                {
650                                    error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
651                                }
652                                else
653                                {
654                                    m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
655                                }
656                            }
657                        }
658                        else
659                        {
660                            error = result_valobj_sp->GetError();
661                        }
662                    }
663                }
664            }
665        }
666    }
667    else
668    {
669        error.SetErrorString("invalid image token");
670    }
671    return error;
672}
673
674DynamicLoader *
675Process::GetDynamicLoader()
676{
677    return NULL;
678}
679
680const ABI *
681Process::GetABI()
682{
683    ConstString& triple = m_target_triple;
684
685    if (triple.IsEmpty())
686        return NULL;
687
688    if (m_abi_sp.get() == NULL)
689    {
690        m_abi_sp.reset(ABI::FindPlugin(triple));
691    }
692
693    return m_abi_sp.get();
694}
695
696LanguageRuntime *
697Process::GetLanguageRuntime(lldb::LanguageType language)
698{
699    LanguageRuntimeCollection::iterator pos;
700    pos = m_language_runtimes.find (language);
701    if (pos == m_language_runtimes.end())
702    {
703        lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
704
705        m_language_runtimes[language]
706            = runtime;
707        return runtime.get();
708    }
709    else
710        return (*pos).second.get();
711}
712
713CPPLanguageRuntime *
714Process::GetCPPLanguageRuntime ()
715{
716    LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
717    if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
718        return static_cast<CPPLanguageRuntime *> (runtime);
719    return NULL;
720}
721
722ObjCLanguageRuntime *
723Process::GetObjCLanguageRuntime ()
724{
725    LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
726    if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
727        return static_cast<ObjCLanguageRuntime *> (runtime);
728    return NULL;
729}
730
731BreakpointSiteList &
732Process::GetBreakpointSiteList()
733{
734    return m_breakpoint_site_list;
735}
736
737const BreakpointSiteList &
738Process::GetBreakpointSiteList() const
739{
740    return m_breakpoint_site_list;
741}
742
743
744void
745Process::DisableAllBreakpointSites ()
746{
747    m_breakpoint_site_list.SetEnabledForAll (false);
748}
749
750Error
751Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
752{
753    Error error (DisableBreakpointSiteByID (break_id));
754
755    if (error.Success())
756        m_breakpoint_site_list.Remove(break_id);
757
758    return error;
759}
760
761Error
762Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
763{
764    Error error;
765    BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
766    if (bp_site_sp)
767    {
768        if (bp_site_sp->IsEnabled())
769            error = DisableBreakpoint (bp_site_sp.get());
770    }
771    else
772    {
773        error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
774    }
775
776    return error;
777}
778
779Error
780Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
781{
782    Error error;
783    BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
784    if (bp_site_sp)
785    {
786        if (!bp_site_sp->IsEnabled())
787            error = EnableBreakpoint (bp_site_sp.get());
788    }
789    else
790    {
791        error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
792    }
793    return error;
794}
795
796lldb::break_id_t
797Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
798{
799    const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
800    if (load_addr != LLDB_INVALID_ADDRESS)
801    {
802        BreakpointSiteSP bp_site_sp;
803
804        // Look up this breakpoint site.  If it exists, then add this new owner, otherwise
805        // create a new breakpoint site and add it.
806
807        bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
808
809        if (bp_site_sp)
810        {
811            bp_site_sp->AddOwner (owner);
812            owner->SetBreakpointSite (bp_site_sp);
813            return bp_site_sp->GetID();
814        }
815        else
816        {
817            bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
818            if (bp_site_sp)
819            {
820                if (EnableBreakpoint (bp_site_sp.get()).Success())
821                {
822                    owner->SetBreakpointSite (bp_site_sp);
823                    return m_breakpoint_site_list.Add (bp_site_sp);
824                }
825            }
826        }
827    }
828    // We failed to enable the breakpoint
829    return LLDB_INVALID_BREAK_ID;
830
831}
832
833void
834Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
835{
836    uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
837    if (num_owners == 0)
838    {
839        DisableBreakpoint(bp_site_sp.get());
840        m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
841    }
842}
843
844
845size_t
846Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
847{
848    size_t bytes_removed = 0;
849    addr_t intersect_addr;
850    size_t intersect_size;
851    size_t opcode_offset;
852    size_t idx;
853    BreakpointSiteSP bp;
854
855    for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
856    {
857        if (bp->GetType() == BreakpointSite::eSoftware)
858        {
859            if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
860            {
861                assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
862                assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
863                assert(opcode_offset + intersect_size <= bp->GetByteSize());
864                size_t buf_offset = intersect_addr - bp_addr;
865                ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
866            }
867        }
868    }
869    return bytes_removed;
870}
871
872
873Error
874Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
875{
876    Error error;
877    assert (bp_site != NULL);
878    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
879    const addr_t bp_addr = bp_site->GetLoadAddress();
880    if (log)
881        log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
882    if (bp_site->IsEnabled())
883    {
884        if (log)
885            log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
886        return error;
887    }
888
889    if (bp_addr == LLDB_INVALID_ADDRESS)
890    {
891        error.SetErrorString("BreakpointSite contains an invalid load address.");
892        return error;
893    }
894    // Ask the lldb::Process subclass to fill in the correct software breakpoint
895    // trap for the breakpoint site
896    const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
897
898    if (bp_opcode_size == 0)
899    {
900        error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
901    }
902    else
903    {
904        const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
905
906        if (bp_opcode_bytes == NULL)
907        {
908            error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
909            return error;
910        }
911
912        // Save the original opcode by reading it
913        if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
914        {
915            // Write a software breakpoint in place of the original opcode
916            if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
917            {
918                uint8_t verify_bp_opcode_bytes[64];
919                if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
920                {
921                    if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
922                    {
923                        bp_site->SetEnabled(true);
924                        bp_site->SetType (BreakpointSite::eSoftware);
925                        if (log)
926                            log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
927                                         bp_site->GetID(),
928                                         (uint64_t)bp_addr);
929                    }
930                    else
931                        error.SetErrorString("Failed to verify the breakpoint trap in memory.");
932                }
933                else
934                    error.SetErrorString("Unable to read memory to verify breakpoint trap.");
935            }
936            else
937                error.SetErrorString("Unable to write breakpoint trap to memory.");
938        }
939        else
940            error.SetErrorString("Unable to read memory at breakpoint address.");
941    }
942    if (log)
943        log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
944                     bp_site->GetID(),
945                     (uint64_t)bp_addr,
946                     error.AsCString());
947    return error;
948}
949
950Error
951Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
952{
953    Error error;
954    assert (bp_site != NULL);
955    LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
956    addr_t bp_addr = bp_site->GetLoadAddress();
957    lldb::user_id_t breakID = bp_site->GetID();
958    if (log)
959        log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
960
961    if (bp_site->IsHardware())
962    {
963        error.SetErrorString("Breakpoint site is a hardware breakpoint.");
964    }
965    else if (bp_site->IsEnabled())
966    {
967        const size_t break_op_size = bp_site->GetByteSize();
968        const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
969        if (break_op_size > 0)
970        {
971            // Clear a software breakoint instruction
972            uint8_t curr_break_op[8];
973            assert (break_op_size <= sizeof(curr_break_op));
974            bool break_op_found = false;
975
976            // Read the breakpoint opcode
977            if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
978            {
979                bool verify = false;
980                // Make sure we have the a breakpoint opcode exists at this address
981                if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
982                {
983                    break_op_found = true;
984                    // We found a valid breakpoint opcode at this address, now restore
985                    // the saved opcode.
986                    if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
987                    {
988                        verify = true;
989                    }
990                    else
991                        error.SetErrorString("Memory write failed when restoring original opcode.");
992                }
993                else
994                {
995                    error.SetErrorString("Original breakpoint trap is no longer in memory.");
996                    // Set verify to true and so we can check if the original opcode has already been restored
997                    verify = true;
998                }
999
1000                if (verify)
1001                {
1002                    uint8_t verify_opcode[8];
1003                    assert (break_op_size < sizeof(verify_opcode));
1004                    // Verify that our original opcode made it back to the inferior
1005                    if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1006                    {
1007                        // compare the memory we just read with the original opcode
1008                        if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1009                        {
1010                            // SUCCESS
1011                            bp_site->SetEnabled(false);
1012                            if (log)
1013                                log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1014                            return error;
1015                        }
1016                        else
1017                        {
1018                            if (break_op_found)
1019                                error.SetErrorString("Failed to restore original opcode.");
1020                        }
1021                    }
1022                    else
1023                        error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1024                }
1025            }
1026            else
1027                error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1028        }
1029    }
1030    else
1031    {
1032        if (log)
1033            log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1034        return error;
1035    }
1036
1037    if (log)
1038        log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1039                     bp_site->GetID(),
1040                     (uint64_t)bp_addr,
1041                     error.AsCString());
1042    return error;
1043
1044}
1045
1046
1047size_t
1048Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1049{
1050    if (buf == NULL || size == 0)
1051        return 0;
1052
1053    size_t bytes_read = 0;
1054    uint8_t *bytes = (uint8_t *)buf;
1055
1056    while (bytes_read < size)
1057    {
1058        const size_t curr_size = size - bytes_read;
1059        const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1060                                                     bytes + bytes_read,
1061                                                     curr_size,
1062                                                     error);
1063        bytes_read += curr_bytes_read;
1064        if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1065            break;
1066    }
1067
1068    // Replace any software breakpoint opcodes that fall into this range back
1069    // into "buf" before we return
1070    if (bytes_read > 0)
1071        RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1072    return bytes_read;
1073}
1074
1075size_t
1076Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1077{
1078    size_t bytes_written = 0;
1079    const uint8_t *bytes = (const uint8_t *)buf;
1080
1081    while (bytes_written < size)
1082    {
1083        const size_t curr_size = size - bytes_written;
1084        const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1085                                                         bytes + bytes_written,
1086                                                         curr_size,
1087                                                         error);
1088        bytes_written += curr_bytes_written;
1089        if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1090            break;
1091    }
1092    return bytes_written;
1093}
1094
1095size_t
1096Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1097{
1098    if (buf == NULL || size == 0)
1099        return 0;
1100    // We need to write any data that would go where any current software traps
1101    // (enabled software breakpoints) any software traps (breakpoints) that we
1102    // may have placed in our tasks memory.
1103
1104    BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1105    BreakpointSiteList::collection::const_iterator end =  m_breakpoint_site_list.GetMap()->end();
1106
1107    if (iter == end || iter->second->GetLoadAddress() > addr + size)
1108        return DoWriteMemory(addr, buf, size, error);
1109
1110    BreakpointSiteList::collection::const_iterator pos;
1111    size_t bytes_written = 0;
1112    addr_t intersect_addr = 0;
1113    size_t intersect_size = 0;
1114    size_t opcode_offset = 0;
1115    const uint8_t *ubuf = (const uint8_t *)buf;
1116
1117    for (pos = iter; pos != end; ++pos)
1118    {
1119        BreakpointSiteSP bp;
1120        bp = pos->second;
1121
1122        assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1123        assert(addr <= intersect_addr && intersect_addr < addr + size);
1124        assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1125        assert(opcode_offset + intersect_size <= bp->GetByteSize());
1126
1127        // Check for bytes before this breakpoint
1128        const addr_t curr_addr = addr + bytes_written;
1129        if (intersect_addr > curr_addr)
1130        {
1131            // There are some bytes before this breakpoint that we need to
1132            // just write to memory
1133            size_t curr_size = intersect_addr - curr_addr;
1134            size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1135                                                            ubuf + bytes_written,
1136                                                            curr_size,
1137                                                            error);
1138            bytes_written += curr_bytes_written;
1139            if (curr_bytes_written != curr_size)
1140            {
1141                // We weren't able to write all of the requested bytes, we
1142                // are done looping and will return the number of bytes that
1143                // we have written so far.
1144                break;
1145            }
1146        }
1147
1148        // Now write any bytes that would cover up any software breakpoints
1149        // directly into the breakpoint opcode buffer
1150        ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1151        bytes_written += intersect_size;
1152    }
1153
1154    // Write any remaining bytes after the last breakpoint if we have any left
1155    if (bytes_written < size)
1156        bytes_written += WriteMemoryPrivate (addr + bytes_written,
1157                                             ubuf + bytes_written,
1158                                             size - bytes_written,
1159                                             error);
1160
1161    return bytes_written;
1162}
1163
1164addr_t
1165Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1166{
1167    // Fixme: we should track the blocks we've allocated, and clean them up...
1168    // We could even do our own allocator here if that ends up being more efficient.
1169    return DoAllocateMemory (size, permissions, error);
1170}
1171
1172Error
1173Process::DeallocateMemory (addr_t ptr)
1174{
1175    return DoDeallocateMemory (ptr);
1176}
1177
1178
1179Error
1180Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1181{
1182    Error error;
1183    error.SetErrorString("watchpoints are not supported");
1184    return error;
1185}
1186
1187Error
1188Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1189{
1190    Error error;
1191    error.SetErrorString("watchpoints are not supported");
1192    return error;
1193}
1194
1195StateType
1196Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1197{
1198    StateType state;
1199    // Now wait for the process to launch and return control to us, and then
1200    // call DidLaunch:
1201    while (1)
1202    {
1203        // FIXME: Might want to put a timeout in here:
1204        state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1205        if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1206            break;
1207        else
1208            HandlePrivateEvent (event_sp);
1209    }
1210    return state;
1211}
1212
1213Error
1214Process::Launch
1215(
1216    char const *argv[],
1217    char const *envp[],
1218    uint32_t launch_flags,
1219    const char *stdin_path,
1220    const char *stdout_path,
1221    const char *stderr_path
1222)
1223{
1224    Error error;
1225    m_target_triple.Clear();
1226    m_abi_sp.reset();
1227    m_process_input_reader.reset();
1228
1229    Module *exe_module = m_target.GetExecutableModule().get();
1230    if (exe_module)
1231    {
1232        char exec_file_path[PATH_MAX];
1233        exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1234        if (exe_module->GetFileSpec().Exists())
1235        {
1236            error = WillLaunch (exe_module);
1237            if (error.Success())
1238            {
1239                SetPublicState (eStateLaunching);
1240                // The args coming in should not contain the application name, the
1241                // lldb_private::Process class will add this in case the executable
1242                // gets resolved to a different file than was given on the command
1243                // line (like when an applicaiton bundle is specified and will
1244                // resolve to the contained exectuable file, or the file given was
1245                // a symlink or other file system link that resolves to a different
1246                // file).
1247
1248                // Get the resolved exectuable path
1249
1250                // Make a new argument vector
1251                std::vector<const char *> exec_path_plus_argv;
1252                // Append the resolved executable path
1253                exec_path_plus_argv.push_back (exec_file_path);
1254
1255                // Push all args if there are any
1256                if (argv)
1257                {
1258                    for (int i = 0; argv[i]; ++i)
1259                        exec_path_plus_argv.push_back(argv[i]);
1260                }
1261
1262                // Push a NULL to terminate the args.
1263                exec_path_plus_argv.push_back(NULL);
1264
1265                // Now launch using these arguments.
1266                error = DoLaunch (exe_module,
1267                                  exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1268                                  envp,
1269                                  launch_flags,
1270                                  stdin_path,
1271                                  stdout_path,
1272                                  stderr_path);
1273
1274                if (error.Fail())
1275                {
1276                    if (GetID() != LLDB_INVALID_PROCESS_ID)
1277                    {
1278                        SetID (LLDB_INVALID_PROCESS_ID);
1279                        const char *error_string = error.AsCString();
1280                        if (error_string == NULL)
1281                            error_string = "launch failed";
1282                        SetExitStatus (-1, error_string);
1283                    }
1284                }
1285                else
1286                {
1287                    EventSP event_sp;
1288                    StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1289
1290                    if (state == eStateStopped || state == eStateCrashed)
1291                    {
1292                        DidLaunch ();
1293
1294                        // This delays passing the stopped event to listeners till DidLaunch gets
1295                        // a chance to complete...
1296                        HandlePrivateEvent (event_sp);
1297                        StartPrivateStateThread ();
1298                    }
1299                    else if (state == eStateExited)
1300                    {
1301                        // We exited while trying to launch somehow.  Don't call DidLaunch as that's
1302                        // not likely to work, and return an invalid pid.
1303                        HandlePrivateEvent (event_sp);
1304                    }
1305                }
1306            }
1307        }
1308        else
1309        {
1310            error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1311        }
1312    }
1313    return error;
1314}
1315
1316Error
1317Process::CompleteAttach ()
1318{
1319    Error error;
1320
1321    if (GetID() == LLDB_INVALID_PROCESS_ID)
1322    {
1323        error.SetErrorString("no process");
1324    }
1325
1326    EventSP event_sp;
1327    StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1328    if (state == eStateStopped || state == eStateCrashed)
1329    {
1330        DidAttach ();
1331        // Figure out which one is the executable, and set that in our target:
1332        ModuleList &modules = GetTarget().GetImages();
1333
1334        size_t num_modules = modules.GetSize();
1335        for (int i = 0; i < num_modules; i++)
1336        {
1337            ModuleSP module_sp = modules.GetModuleAtIndex(i);
1338            if (module_sp->IsExecutable())
1339            {
1340                ModuleSP exec_module = GetTarget().GetExecutableModule();
1341                if (!exec_module || exec_module != module_sp)
1342                {
1343
1344                    GetTarget().SetExecutableModule (module_sp, false);
1345                }
1346                break;
1347            }
1348        }
1349
1350        // This delays passing the stopped event to listeners till DidLaunch gets
1351        // a chance to complete...
1352        HandlePrivateEvent(event_sp);
1353        StartPrivateStateThread();
1354    }
1355    else
1356    {
1357        // We exited while trying to launch somehow.  Don't call DidLaunch as that's
1358        // not likely to work, and return an invalid pid.
1359        if (state == eStateExited)
1360            HandlePrivateEvent (event_sp);
1361        error.SetErrorStringWithFormat("invalid state after attach: %s",
1362                                        lldb_private::StateAsCString(state));
1363    }
1364    return error;
1365}
1366
1367Error
1368Process::Attach (lldb::pid_t attach_pid)
1369{
1370
1371    m_target_triple.Clear();
1372    m_abi_sp.reset();
1373    m_process_input_reader.reset();
1374
1375    // Find the process and its architecture.  Make sure it matches the architecture
1376    // of the current Target, and if not adjust it.
1377
1378    ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1379    if (attach_spec != GetTarget().GetArchitecture())
1380    {
1381        // Set the architecture on the target.
1382        GetTarget().SetArchitecture(attach_spec);
1383    }
1384
1385    Error error (WillAttachToProcessWithID(attach_pid));
1386    if (error.Success())
1387    {
1388        SetPublicState (eStateAttaching);
1389
1390        error = DoAttachToProcessWithID (attach_pid);
1391        if (error.Success())
1392        {
1393            error = CompleteAttach();
1394        }
1395        else
1396        {
1397            if (GetID() != LLDB_INVALID_PROCESS_ID)
1398            {
1399                SetID (LLDB_INVALID_PROCESS_ID);
1400                const char *error_string = error.AsCString();
1401                if (error_string == NULL)
1402                    error_string = "attach failed";
1403
1404                SetExitStatus(-1, error_string);
1405            }
1406        }
1407    }
1408    return error;
1409}
1410
1411Error
1412Process::Attach (const char *process_name, bool wait_for_launch)
1413{
1414    m_target_triple.Clear();
1415    m_abi_sp.reset();
1416    m_process_input_reader.reset();
1417
1418    // Find the process and its architecture.  Make sure it matches the architecture
1419    // of the current Target, and if not adjust it.
1420
1421    if (!wait_for_launch)
1422    {
1423        ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
1424        if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
1425        {
1426            // Set the architecture on the target.
1427            GetTarget().SetArchitecture(attach_spec);
1428        }
1429    }
1430
1431    Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
1432    if (error.Success())
1433    {
1434        SetPublicState (eStateAttaching);
1435        error = DoAttachToProcessWithName (process_name, wait_for_launch);
1436        if (error.Fail())
1437        {
1438            if (GetID() != LLDB_INVALID_PROCESS_ID)
1439            {
1440                SetID (LLDB_INVALID_PROCESS_ID);
1441                const char *error_string = error.AsCString();
1442                if (error_string == NULL)
1443                    error_string = "attach failed";
1444
1445                SetExitStatus(-1, error_string);
1446            }
1447        }
1448        else
1449        {
1450            error = CompleteAttach();
1451        }
1452    }
1453    return error;
1454}
1455
1456Error
1457Process::Resume ()
1458{
1459    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1460    if (log)
1461        log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1462
1463    Error error (WillResume());
1464    // Tell the process it is about to resume before the thread list
1465    if (error.Success())
1466    {
1467        // Now let the thread list know we are about to resume so it
1468        // can let all of our threads know that they are about to be
1469        // resumed. Threads will each be called with
1470        // Thread::WillResume(StateType) where StateType contains the state
1471        // that they are supposed to have when the process is resumed
1472        // (suspended/running/stepping). Threads should also check
1473        // their resume signal in lldb::Thread::GetResumeSignal()
1474        // to see if they are suppoed to start back up with a signal.
1475        if (m_thread_list.WillResume())
1476        {
1477            error = DoResume();
1478            if (error.Success())
1479            {
1480                DidResume();
1481                m_thread_list.DidResume();
1482            }
1483        }
1484        else
1485        {
1486            error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1487        }
1488    }
1489    return error;
1490}
1491
1492Error
1493Process::Halt ()
1494{
1495    Error error (WillHalt());
1496
1497    if (error.Success())
1498    {
1499
1500        bool caused_stop = false;
1501        EventSP event_sp;
1502
1503        // Pause our private state thread so we can ensure no one else eats
1504        // the stop event out from under us.
1505        PausePrivateStateThread();
1506
1507        // Ask the process subclass to actually halt our process
1508        error = DoHalt(caused_stop);
1509        if (error.Success())
1510        {
1511            // If "caused_stop" is true, then DoHalt stopped the process. If
1512            // "caused_stop" is false, the process was already stopped.
1513            // If the DoHalt caused the process to stop, then we want to catch
1514            // this event and set the interrupted bool to true before we pass
1515            // this along so clients know that the process was interrupted by
1516            // a halt command.
1517            if (caused_stop)
1518            {
1519                // Wait for 2 seconds for the process to stop.
1520                TimeValue timeout_time;
1521                timeout_time = TimeValue::Now();
1522                timeout_time.OffsetWithSeconds(2);
1523                StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1524
1525                if (state == eStateInvalid)
1526                {
1527                    // We timeout out and didn't get a stop event...
1528                    error.SetErrorString ("Halt timed out.");
1529                }
1530                else
1531                {
1532                    if (StateIsStoppedState (state))
1533                    {
1534                        // We caused the process to interrupt itself, so mark this
1535                        // as such in the stop event so clients can tell an interrupted
1536                        // process from a natural stop
1537                        ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1538                    }
1539                    else
1540                    {
1541                        LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1542                        if (log)
1543                            log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1544                        error.SetErrorString ("Did not get stopped event after halt.");
1545                    }
1546                }
1547            }
1548            DidHalt();
1549
1550        }
1551        // Resume our private state thread before we post the event (if any)
1552        ResumePrivateStateThread();
1553
1554        // Post any event we might have consumed. If all goes well, we will have
1555        // stopped the process, intercepted the event and set the interrupted
1556        // bool in the event.  Post it to the private event queue and that will end up
1557        // correctly setting the state.
1558        if (event_sp)
1559            m_private_state_broadcaster.BroadcastEvent(event_sp);
1560
1561    }
1562    return error;
1563}
1564
1565Error
1566Process::Detach ()
1567{
1568    Error error (WillDetach());
1569
1570    if (error.Success())
1571    {
1572        DisableAllBreakpointSites();
1573        error = DoDetach();
1574        if (error.Success())
1575        {
1576            DidDetach();
1577            StopPrivateStateThread();
1578        }
1579    }
1580    return error;
1581}
1582
1583Error
1584Process::Destroy ()
1585{
1586    Error error (WillDestroy());
1587    if (error.Success())
1588    {
1589        DisableAllBreakpointSites();
1590        error = DoDestroy();
1591        if (error.Success())
1592        {
1593            DidDestroy();
1594            StopPrivateStateThread();
1595        }
1596        m_stdio_communication.StopReadThread();
1597        m_stdio_communication.Disconnect();
1598        if (m_process_input_reader && m_process_input_reader->IsActive())
1599            m_target.GetDebugger().PopInputReader (m_process_input_reader);
1600        if (m_process_input_reader)
1601            m_process_input_reader.reset();
1602    }
1603    return error;
1604}
1605
1606Error
1607Process::Signal (int signal)
1608{
1609    Error error (WillSignal());
1610    if (error.Success())
1611    {
1612        error = DoSignal(signal);
1613        if (error.Success())
1614            DidSignal();
1615    }
1616    return error;
1617}
1618
1619UnixSignals &
1620Process::GetUnixSignals ()
1621{
1622    return m_unix_signals;
1623}
1624
1625Target &
1626Process::GetTarget ()
1627{
1628    return m_target;
1629}
1630
1631const Target &
1632Process::GetTarget () const
1633{
1634    return m_target;
1635}
1636
1637uint32_t
1638Process::GetAddressByteSize()
1639{
1640    if (m_addr_byte_size == 0)
1641        return m_target.GetArchitecture().GetAddressByteSize();
1642    return m_addr_byte_size;
1643}
1644
1645bool
1646Process::ShouldBroadcastEvent (Event *event_ptr)
1647{
1648    const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1649    bool return_value = true;
1650    LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
1651
1652    switch (state)
1653    {
1654        case eStateAttaching:
1655        case eStateLaunching:
1656        case eStateDetached:
1657        case eStateExited:
1658        case eStateUnloaded:
1659            // These events indicate changes in the state of the debugging session, always report them.
1660            return_value = true;
1661            break;
1662        case eStateInvalid:
1663            // We stopped for no apparent reason, don't report it.
1664            return_value = false;
1665            break;
1666        case eStateRunning:
1667        case eStateStepping:
1668            // If we've started the target running, we handle the cases where we
1669            // are already running and where there is a transition from stopped to
1670            // running differently.
1671            // running -> running: Automatically suppress extra running events
1672            // stopped -> running: Report except when there is one or more no votes
1673            //     and no yes votes.
1674            SynchronouslyNotifyStateChanged (state);
1675            switch (m_public_state.GetValue())
1676            {
1677                case eStateRunning:
1678                case eStateStepping:
1679                    // We always suppress multiple runnings with no PUBLIC stop in between.
1680                    return_value = false;
1681                    break;
1682                default:
1683                    // TODO: make this work correctly. For now always report
1684                    // run if we aren't running so we don't miss any runnning
1685                    // events. If I run the lldb/test/thread/a.out file and
1686                    // break at main.cpp:58, run and hit the breakpoints on
1687                    // multiple threads, then somehow during the stepping over
1688                    // of all breakpoints no run gets reported.
1689                    return_value = true;
1690
1691                    // This is a transition from stop to run.
1692                    switch (m_thread_list.ShouldReportRun (event_ptr))
1693                    {
1694                        case eVoteYes:
1695                        case eVoteNoOpinion:
1696                            return_value = true;
1697                            break;
1698                        case eVoteNo:
1699                            return_value = false;
1700                            break;
1701                    }
1702                    break;
1703            }
1704            break;
1705        case eStateStopped:
1706        case eStateCrashed:
1707        case eStateSuspended:
1708        {
1709            // We've stopped.  First see if we're going to restart the target.
1710            // If we are going to stop, then we always broadcast the event.
1711            // If we aren't going to stop, let the thread plans decide if we're going to report this event.
1712            // If no thread has an opinion, we don't report it.
1713            if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
1714            {
1715                if (log)
1716                    log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
1717                return true;
1718            }
1719            else
1720            {
1721                RefreshStateAfterStop ();
1722
1723                if (m_thread_list.ShouldStop (event_ptr) == false)
1724                {
1725                    switch (m_thread_list.ShouldReportStop (event_ptr))
1726                    {
1727                        case eVoteYes:
1728                            Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
1729                            // Intentional fall-through here.
1730                        case eVoteNoOpinion:
1731                        case eVoteNo:
1732                            return_value = false;
1733                            break;
1734                    }
1735
1736                    if (log)
1737                        log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
1738                    Resume ();
1739                }
1740                else
1741                {
1742                    return_value = true;
1743                    SynchronouslyNotifyStateChanged (state);
1744                }
1745            }
1746        }
1747    }
1748
1749    if (log)
1750        log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1751    return return_value;
1752}
1753
1754//------------------------------------------------------------------
1755// Thread Queries
1756//------------------------------------------------------------------
1757
1758ThreadList &
1759Process::GetThreadList ()
1760{
1761    return m_thread_list;
1762}
1763
1764const ThreadList &
1765Process::GetThreadList () const
1766{
1767    return m_thread_list;
1768}
1769
1770
1771bool
1772Process::StartPrivateStateThread ()
1773{
1774    LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
1775
1776    if (log)
1777        log->Printf ("Process::%s ( )", __FUNCTION__);
1778
1779    // Create a thread that watches our internal state and controls which
1780    // events make it to clients (into the DCProcess event queue).
1781    m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1782    return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1783}
1784
1785void
1786Process::PausePrivateStateThread ()
1787{
1788    ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1789}
1790
1791void
1792Process::ResumePrivateStateThread ()
1793{
1794    ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1795}
1796
1797void
1798Process::StopPrivateStateThread ()
1799{
1800    ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1801}
1802
1803void
1804Process::ControlPrivateStateThread (uint32_t signal)
1805{
1806    LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
1807
1808    assert (signal == eBroadcastInternalStateControlStop ||
1809            signal == eBroadcastInternalStateControlPause ||
1810            signal == eBroadcastInternalStateControlResume);
1811
1812    if (log)
1813        log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1814
1815    // Signal the private state thread
1816    if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1817    {
1818        TimeValue timeout_time;
1819        bool timed_out;
1820
1821        m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1822
1823        timeout_time = TimeValue::Now();
1824        timeout_time.OffsetWithSeconds(2);
1825        m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1826        m_private_state_control_wait.SetValue (false, eBroadcastNever);
1827
1828        if (signal == eBroadcastInternalStateControlStop)
1829        {
1830            if (timed_out)
1831                Host::ThreadCancel (m_private_state_thread, NULL);
1832
1833            thread_result_t result = NULL;
1834            Host::ThreadJoin (m_private_state_thread, &result, NULL);
1835            m_private_state_thread = LLDB_INVALID_HOST_THREAD;
1836        }
1837    }
1838}
1839
1840void
1841Process::HandlePrivateEvent (EventSP &event_sp)
1842{
1843    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1844    const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1845    // See if we should broadcast this state to external clients?
1846    const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1847    if (log)
1848        log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1849
1850    if (should_broadcast)
1851    {
1852        if (log)
1853        {
1854            log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1855        }
1856        if (StateIsRunningState (internal_state))
1857            PushProcessInputReader ();
1858        else
1859            PopProcessInputReader ();
1860        Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1861        BroadcastEvent (event_sp);
1862    }
1863    else
1864    {
1865        if (log)
1866        {
1867            log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1868        }
1869    }
1870}
1871
1872void *
1873Process::PrivateStateThread (void *arg)
1874{
1875    Process *proc = static_cast<Process*> (arg);
1876    void *result = proc->RunPrivateStateThread ();
1877    return result;
1878}
1879
1880void *
1881Process::RunPrivateStateThread ()
1882{
1883    bool control_only = false;
1884    m_private_state_control_wait.SetValue (false, eBroadcastNever);
1885
1886    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1887    if (log)
1888        log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1889
1890    bool exit_now = false;
1891    while (!exit_now)
1892    {
1893        EventSP event_sp;
1894        WaitForEventsPrivate (NULL, event_sp, control_only);
1895        if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1896        {
1897            switch (event_sp->GetType())
1898            {
1899            case eBroadcastInternalStateControlStop:
1900                exit_now = true;
1901                continue;   // Go to next loop iteration so we exit without
1902                break;      // doing any internal state managment below
1903
1904            case eBroadcastInternalStateControlPause:
1905                control_only = true;
1906                break;
1907
1908            case eBroadcastInternalStateControlResume:
1909                control_only = false;
1910                break;
1911            }
1912
1913            log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1914            if (log)
1915                log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
1916
1917            m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1918            continue;
1919        }
1920
1921
1922        const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1923
1924        if (internal_state != eStateInvalid)
1925        {
1926            HandlePrivateEvent (event_sp);
1927        }
1928
1929        if (internal_state == eStateInvalid ||
1930            internal_state == eStateExited  ||
1931            internal_state == eStateDetached )
1932        {
1933            log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1934            if (log)
1935                log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
1936
1937            break;
1938        }
1939    }
1940
1941    // Verify log is still enabled before attempting to write to it...
1942    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1943    if (log)
1944        log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1945
1946    m_private_state_thread = LLDB_INVALID_HOST_THREAD;
1947    return NULL;
1948}
1949
1950//------------------------------------------------------------------
1951// Process Event Data
1952//------------------------------------------------------------------
1953
1954Process::ProcessEventData::ProcessEventData () :
1955    EventData (),
1956    m_process_sp (),
1957    m_state (eStateInvalid),
1958    m_restarted (false),
1959    m_update_state (false),
1960    m_interrupted (false)
1961{
1962}
1963
1964Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1965    EventData (),
1966    m_process_sp (process_sp),
1967    m_state (state),
1968    m_restarted (false),
1969    m_update_state (false),
1970    m_interrupted (false)
1971{
1972}
1973
1974Process::ProcessEventData::~ProcessEventData()
1975{
1976}
1977
1978const ConstString &
1979Process::ProcessEventData::GetFlavorString ()
1980{
1981    static ConstString g_flavor ("Process::ProcessEventData");
1982    return g_flavor;
1983}
1984
1985const ConstString &
1986Process::ProcessEventData::GetFlavor () const
1987{
1988    return ProcessEventData::GetFlavorString ();
1989}
1990
1991void
1992Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1993{
1994    // This function gets called twice for each event, once when the event gets pulled
1995    // off of the private process event queue, and once when it gets pulled off of
1996    // the public event queue.  m_update_state is used to distinguish these
1997    // two cases; it is false when we're just pulling it off for private handling,
1998    // and we don't want to do the breakpoint command handling then.
1999
2000    if (!m_update_state)
2001        return;
2002
2003    m_process_sp->SetPublicState (m_state);
2004
2005    // If we're stopped and haven't restarted, then do the breakpoint commands here:
2006    if (m_state == eStateStopped && ! m_restarted)
2007    {
2008        int num_threads = m_process_sp->GetThreadList().GetSize();
2009        int idx;
2010
2011        for (idx = 0; idx < num_threads; ++idx)
2012        {
2013            lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2014
2015            StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2016            if (stop_info_sp)
2017            {
2018                stop_info_sp->PerformAction(event_ptr);
2019            }
2020        }
2021
2022        // The stop action might restart the target.  If it does, then we want to mark that in the
2023        // event so that whoever is receiving it will know to wait for the running event and reflect
2024        // that state appropriately.
2025
2026        if (m_process_sp->GetPrivateState() == eStateRunning)
2027            SetRestarted(true);
2028    }
2029}
2030
2031void
2032Process::ProcessEventData::Dump (Stream *s) const
2033{
2034    if (m_process_sp)
2035        s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2036
2037    s->Printf("state = %s", StateAsCString(GetState()));;
2038}
2039
2040const Process::ProcessEventData *
2041Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2042{
2043    if (event_ptr)
2044    {
2045        const EventData *event_data = event_ptr->GetData();
2046        if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2047            return static_cast <const ProcessEventData *> (event_ptr->GetData());
2048    }
2049    return NULL;
2050}
2051
2052ProcessSP
2053Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2054{
2055    ProcessSP process_sp;
2056    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2057    if (data)
2058        process_sp = data->GetProcessSP();
2059    return process_sp;
2060}
2061
2062StateType
2063Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2064{
2065    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2066    if (data == NULL)
2067        return eStateInvalid;
2068    else
2069        return data->GetState();
2070}
2071
2072bool
2073Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2074{
2075    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2076    if (data == NULL)
2077        return false;
2078    else
2079        return data->GetRestarted();
2080}
2081
2082void
2083Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2084{
2085    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2086    if (data != NULL)
2087        data->SetRestarted(new_value);
2088}
2089
2090bool
2091Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2092{
2093    const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2094    if (data == NULL)
2095        return false;
2096    else
2097        return data->GetInterrupted ();
2098}
2099
2100void
2101Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2102{
2103    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2104    if (data != NULL)
2105        data->SetInterrupted(new_value);
2106}
2107
2108bool
2109Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2110{
2111    ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2112    if (data)
2113    {
2114        data->SetUpdateStateOnRemoval();
2115        return true;
2116    }
2117    return false;
2118}
2119
2120Target *
2121Process::CalculateTarget ()
2122{
2123    return &m_target;
2124}
2125
2126Process *
2127Process::CalculateProcess ()
2128{
2129    return this;
2130}
2131
2132Thread *
2133Process::CalculateThread ()
2134{
2135    return NULL;
2136}
2137
2138StackFrame *
2139Process::CalculateStackFrame ()
2140{
2141    return NULL;
2142}
2143
2144void
2145Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
2146{
2147    exe_ctx.target = &m_target;
2148    exe_ctx.process = this;
2149    exe_ctx.thread = NULL;
2150    exe_ctx.frame = NULL;
2151}
2152
2153lldb::ProcessSP
2154Process::GetSP ()
2155{
2156    return GetTarget().GetProcessSP();
2157}
2158
2159uint32_t
2160Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2161{
2162    return 0;
2163}
2164
2165ArchSpec
2166Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2167{
2168    return Host::GetArchSpecForExistingProcess (pid);
2169}
2170
2171ArchSpec
2172Process::GetArchSpecForExistingProcess (const char *process_name)
2173{
2174    return Host::GetArchSpecForExistingProcess (process_name);
2175}
2176
2177void
2178Process::AppendSTDOUT (const char * s, size_t len)
2179{
2180    Mutex::Locker locker (m_stdio_communication_mutex);
2181    m_stdout_data.append (s, len);
2182
2183    BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
2184}
2185
2186void
2187Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2188{
2189    Process *process = (Process *) baton;
2190    process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2191}
2192
2193size_t
2194Process::ProcessInputReaderCallback (void *baton,
2195                                     InputReader &reader,
2196                                     lldb::InputReaderAction notification,
2197                                     const char *bytes,
2198                                     size_t bytes_len)
2199{
2200    Process *process = (Process *) baton;
2201
2202    switch (notification)
2203    {
2204    case eInputReaderActivate:
2205        break;
2206
2207    case eInputReaderDeactivate:
2208        break;
2209
2210    case eInputReaderReactivate:
2211        break;
2212
2213    case eInputReaderGotToken:
2214        {
2215            Error error;
2216            process->PutSTDIN (bytes, bytes_len, error);
2217        }
2218        break;
2219
2220    case eInputReaderInterrupt:
2221        process->Halt ();
2222        break;
2223
2224    case eInputReaderEndOfFile:
2225        process->AppendSTDOUT ("^D", 2);
2226        break;
2227
2228    case eInputReaderDone:
2229        break;
2230
2231    }
2232
2233    return bytes_len;
2234}
2235
2236void
2237Process::ResetProcessInputReader ()
2238{
2239    m_process_input_reader.reset();
2240}
2241
2242void
2243Process::SetUpProcessInputReader (int file_descriptor)
2244{
2245    // First set up the Read Thread for reading/handling process I/O
2246
2247    std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2248
2249    if (conn_ap.get())
2250    {
2251        m_stdio_communication.SetConnection (conn_ap.release());
2252        if (m_stdio_communication.IsConnected())
2253        {
2254            m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2255            m_stdio_communication.StartReadThread();
2256
2257            // Now read thread is set up, set up input reader.
2258
2259            if (!m_process_input_reader.get())
2260            {
2261                m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2262                Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2263                                                               this,
2264                                                               eInputReaderGranularityByte,
2265                                                               NULL,
2266                                                               NULL,
2267                                                               false));
2268
2269                if  (err.Fail())
2270                    m_process_input_reader.reset();
2271            }
2272        }
2273    }
2274}
2275
2276void
2277Process::PushProcessInputReader ()
2278{
2279    if (m_process_input_reader && !m_process_input_reader->IsActive())
2280        m_target.GetDebugger().PushInputReader (m_process_input_reader);
2281}
2282
2283void
2284Process::PopProcessInputReader ()
2285{
2286    if (m_process_input_reader && m_process_input_reader->IsActive())
2287        m_target.GetDebugger().PopInputReader (m_process_input_reader);
2288}
2289
2290
2291void
2292Process::Initialize ()
2293{
2294    UserSettingsControllerSP &usc = GetSettingsController();
2295    usc.reset (new SettingsController);
2296    UserSettingsController::InitializeSettingsController (usc,
2297                                                          SettingsController::global_settings_table,
2298                                                          SettingsController::instance_settings_table);
2299}
2300
2301void
2302Process::Terminate ()
2303{
2304    UserSettingsControllerSP &usc = GetSettingsController();
2305    UserSettingsController::FinalizeSettingsController (usc);
2306    usc.reset();
2307}
2308
2309UserSettingsControllerSP &
2310Process::GetSettingsController ()
2311{
2312    static UserSettingsControllerSP g_settings_controller;
2313    return g_settings_controller;
2314}
2315
2316void
2317Process::UpdateInstanceName ()
2318{
2319    ModuleSP module_sp = GetTarget().GetExecutableModule();
2320    if (module_sp)
2321    {
2322        StreamString sstr;
2323        sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2324
2325        GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
2326                                                                  sstr.GetData());
2327    }
2328}
2329
2330ExecutionResults
2331Process::RunThreadPlan (ExecutionContext &exe_ctx,
2332                        lldb::ThreadPlanSP &thread_plan_sp,
2333                        bool stop_others,
2334                        bool try_all_threads,
2335                        bool discard_on_error,
2336                        uint32_t single_thread_timeout_usec,
2337                        Stream &errors)
2338{
2339    ExecutionResults return_value = eExecutionSetupError;
2340
2341    // Save this value for restoration of the execution context after we run
2342    uint32_t tid = exe_ctx.thread->GetIndexID();
2343
2344    // N.B. Running the target may unset the currently selected thread and frame.  We don't want to do that either,
2345    // so we should arrange to reset them as well.
2346
2347    lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2348    lldb::StackFrameSP selected_frame_sp;
2349
2350    uint32_t selected_tid;
2351    if (selected_thread_sp != NULL)
2352    {
2353        selected_tid = selected_thread_sp->GetIndexID();
2354        selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2355    }
2356    else
2357    {
2358        selected_tid = LLDB_INVALID_THREAD_ID;
2359    }
2360
2361    exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2362
2363    Listener listener("ClangFunction temporary listener");
2364    exe_ctx.process->HijackProcessEvents(&listener);
2365
2366    Error resume_error = exe_ctx.process->Resume ();
2367    if (!resume_error.Success())
2368    {
2369        errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2370        exe_ctx.process->RestoreProcessEvents();
2371        return lldb::eExecutionSetupError;
2372    }
2373
2374    // We need to call the function synchronously, so spin waiting for it to return.
2375    // If we get interrupted while executing, we're going to lose our context, and
2376    // won't be able to gather the result at this point.
2377    // We set the timeout AFTER the resume, since the resume takes some time and we
2378    // don't want to charge that to the timeout.
2379
2380    TimeValue* timeout_ptr = NULL;
2381    TimeValue real_timeout;
2382
2383    if (single_thread_timeout_usec != 0)
2384    {
2385        real_timeout = TimeValue::Now();
2386        real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2387        timeout_ptr = &real_timeout;
2388    }
2389
2390    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2391    while (1)
2392    {
2393        lldb::EventSP event_sp;
2394        lldb::StateType stop_state = lldb::eStateInvalid;
2395        // Now wait for the process to stop again:
2396        bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2397
2398        if (!got_event)
2399        {
2400            // Right now this is the only way to tell we've timed out...
2401            // We should interrupt the process here...
2402            // Not really sure what to do if Halt fails here...
2403            if (log)
2404                if (try_all_threads)
2405                    log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2406                                 single_thread_timeout_usec);
2407                else
2408                    log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2409                                 single_thread_timeout_usec);
2410
2411            if (exe_ctx.process->Halt().Success())
2412            {
2413                timeout_ptr = NULL;
2414                if (log)
2415                    log->Printf ("Halt succeeded.");
2416
2417                // Between the time that we got the timeout and the time we halted, but target
2418                // might have actually completed the plan.  If so, we're done.  Note, I call WFE here with a short
2419                // timeout to
2420                got_event = listener.WaitForEvent(NULL, event_sp);
2421
2422                if (got_event)
2423                {
2424                    stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2425                    if (log)
2426                    {
2427                        log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2428                        if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2429                            log->Printf ("    Event was the Halt interruption event.");
2430                    }
2431
2432                    if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2433                    {
2434                        if (log)
2435                            log->Printf ("Even though we timed out, the call plan was done.  Exiting wait loop.");
2436                        return_value = lldb::eExecutionCompleted;
2437                        break;
2438                    }
2439
2440                    if (try_all_threads
2441                        && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2442                    {
2443
2444                        thread_plan_sp->SetStopOthers (false);
2445                        if (log)
2446                            log->Printf ("About to resume.");
2447
2448                        exe_ctx.process->Resume();
2449                        continue;
2450                    }
2451                    else
2452                    {
2453                        exe_ctx.process->RestoreProcessEvents ();
2454                        return lldb::eExecutionInterrupted;
2455                    }
2456                }
2457            }
2458        }
2459
2460        stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2461        if (log)
2462            log->Printf("Got event: %s.", StateAsCString(stop_state));
2463
2464        if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2465            continue;
2466
2467        if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2468        {
2469            return_value = lldb::eExecutionCompleted;
2470            break;
2471        }
2472        else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2473        {
2474            return_value = lldb::eExecutionDiscarded;
2475            break;
2476        }
2477        else
2478        {
2479            if (log)
2480            {
2481                StreamString s;
2482                event_sp->Dump (&s);
2483                StreamString ts;
2484
2485                const char *event_explanation;
2486
2487                do
2488                {
2489                    const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2490
2491                    if (!event_data)
2492                    {
2493                        event_explanation = "<no event data>";
2494                        break;
2495                    }
2496
2497                    Process *process = event_data->GetProcessSP().get();
2498
2499                    if (!process)
2500                    {
2501                        event_explanation = "<no process>";
2502                        break;
2503                    }
2504
2505                    ThreadList &thread_list = process->GetThreadList();
2506
2507                    uint32_t num_threads = thread_list.GetSize();
2508                    uint32_t thread_index;
2509
2510                    ts.Printf("<%u threads> ", num_threads);
2511
2512                    for (thread_index = 0;
2513                         thread_index < num_threads;
2514                         ++thread_index)
2515                    {
2516                        Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2517
2518                        if (!thread)
2519                        {
2520                            ts.Printf("<?> ");
2521                            continue;
2522                        }
2523
2524                        ts.Printf("<");
2525                        RegisterContext *register_context = thread->GetRegisterContext();
2526
2527                        if (register_context)
2528                            ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2529                        else
2530                            ts.Printf("[ip unknown] ");
2531
2532                        lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2533                        if (stop_info_sp)
2534                        {
2535                            const char *stop_desc = stop_info_sp->GetDescription();
2536                            if (stop_desc)
2537                                ts.PutCString (stop_desc);
2538                        }
2539                        ts.Printf(">");
2540                    }
2541
2542                    event_explanation = ts.GetData();
2543                } while (0);
2544
2545                if (log)
2546                    log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2547            }
2548
2549            if (discard_on_error && thread_plan_sp)
2550            {
2551                exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2552            }
2553            return_value = lldb::eExecutionInterrupted;
2554            break;
2555        }
2556    }
2557
2558    if (exe_ctx.process)
2559        exe_ctx.process->RestoreProcessEvents ();
2560
2561    // Thread we ran the function in may have gone away because we ran the target
2562    // Check that it's still there.
2563    exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2564    if (exe_ctx.thread)
2565        exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2566
2567    // Also restore the current process'es selected frame & thread, since this function calling may
2568    // be done behind the user's back.
2569
2570    if (selected_tid != LLDB_INVALID_THREAD_ID)
2571    {
2572        if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2573        {
2574            // We were able to restore the selected thread, now restore the frame:
2575            exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2576        }
2577    }
2578
2579    return return_value;
2580}
2581
2582const char *
2583Process::ExecutionResultAsCString (ExecutionResults result)
2584{
2585    const char *result_name;
2586
2587    switch (result)
2588    {
2589        case lldb::eExecutionCompleted:
2590            result_name = "eExecutionCompleted";
2591            break;
2592        case lldb::eExecutionDiscarded:
2593            result_name = "eExecutionDiscarded";
2594            break;
2595        case lldb::eExecutionInterrupted:
2596            result_name = "eExecutionInterrupted";
2597            break;
2598        case lldb::eExecutionSetupError:
2599            result_name = "eExecutionSetupError";
2600            break;
2601        case lldb::eExecutionTimedOut:
2602            result_name = "eExecutionTimedOut";
2603            break;
2604    }
2605    return result_name;
2606}
2607
2608//--------------------------------------------------------------
2609// class Process::SettingsController
2610//--------------------------------------------------------------
2611
2612Process::SettingsController::SettingsController () :
2613    UserSettingsController ("process", Target::GetSettingsController())
2614{
2615    m_default_settings.reset (new ProcessInstanceSettings (*this,
2616                                                           false,
2617                                                           InstanceSettings::GetDefaultName().AsCString()));
2618}
2619
2620Process::SettingsController::~SettingsController ()
2621{
2622}
2623
2624lldb::InstanceSettingsSP
2625Process::SettingsController::CreateInstanceSettings (const char *instance_name)
2626{
2627    ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2628                                                                         false,
2629                                                                         instance_name);
2630    lldb::InstanceSettingsSP new_settings_sp (new_settings);
2631    return new_settings_sp;
2632}
2633
2634//--------------------------------------------------------------
2635// class ProcessInstanceSettings
2636//--------------------------------------------------------------
2637
2638ProcessInstanceSettings::ProcessInstanceSettings
2639(
2640    UserSettingsController &owner,
2641    bool live_instance,
2642    const char *name
2643) :
2644    InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
2645    m_run_args (),
2646    m_env_vars (),
2647    m_input_path (),
2648    m_output_path (),
2649    m_error_path (),
2650    m_plugin (),
2651    m_disable_aslr (true),
2652    m_disable_stdio (false),
2653    m_inherit_host_env (true),
2654    m_got_host_env (false)
2655{
2656    // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2657    // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2658    // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
2659    // This is true for CreateInstanceName() too.
2660
2661    if (GetInstanceName () == InstanceSettings::InvalidName())
2662    {
2663        ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2664        m_owner.RegisterInstanceSettings (this);
2665    }
2666
2667    if (live_instance)
2668    {
2669        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2670        CopyInstanceSettings (pending_settings,false);
2671        //m_owner.RemovePendingSettings (m_instance_name);
2672    }
2673}
2674
2675ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
2676    InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
2677    m_run_args (rhs.m_run_args),
2678    m_env_vars (rhs.m_env_vars),
2679    m_input_path (rhs.m_input_path),
2680    m_output_path (rhs.m_output_path),
2681    m_error_path (rhs.m_error_path),
2682    m_plugin (rhs.m_plugin),
2683    m_disable_aslr (rhs.m_disable_aslr),
2684    m_disable_stdio (rhs.m_disable_stdio)
2685{
2686    if (m_instance_name != InstanceSettings::GetDefaultName())
2687    {
2688        const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2689        CopyInstanceSettings (pending_settings,false);
2690        m_owner.RemovePendingSettings (m_instance_name);
2691    }
2692}
2693
2694ProcessInstanceSettings::~ProcessInstanceSettings ()
2695{
2696}
2697
2698ProcessInstanceSettings&
2699ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2700{
2701    if (this != &rhs)
2702    {
2703        m_run_args = rhs.m_run_args;
2704        m_env_vars = rhs.m_env_vars;
2705        m_input_path = rhs.m_input_path;
2706        m_output_path = rhs.m_output_path;
2707        m_error_path = rhs.m_error_path;
2708        m_plugin = rhs.m_plugin;
2709        m_disable_aslr = rhs.m_disable_aslr;
2710        m_disable_stdio = rhs.m_disable_stdio;
2711        m_inherit_host_env = rhs.m_inherit_host_env;
2712    }
2713
2714    return *this;
2715}
2716
2717
2718void
2719ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2720                                                         const char *index_value,
2721                                                         const char *value,
2722                                                         const ConstString &instance_name,
2723                                                         const SettingEntry &entry,
2724                                                         lldb::VarSetOperationType op,
2725                                                         Error &err,
2726                                                         bool pending)
2727{
2728    if (var_name == RunArgsVarName())
2729        UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2730    else if (var_name == EnvVarsVarName())
2731    {
2732        GetHostEnvironmentIfNeeded ();
2733        UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2734    }
2735    else if (var_name == InputPathVarName())
2736        UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2737    else if (var_name == OutputPathVarName())
2738        UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2739    else if (var_name == ErrorPathVarName())
2740        UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2741    else if (var_name == PluginVarName())
2742        UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
2743    else if (var_name == InheritHostEnvVarName())
2744        UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
2745    else if (var_name == DisableASLRVarName())
2746        UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
2747    else if (var_name == DisableSTDIOVarName ())
2748        UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
2749}
2750
2751void
2752ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2753                                               bool pending)
2754{
2755    if (new_settings.get() == NULL)
2756        return;
2757
2758    ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2759
2760    m_run_args = new_process_settings->m_run_args;
2761    m_env_vars = new_process_settings->m_env_vars;
2762    m_input_path = new_process_settings->m_input_path;
2763    m_output_path = new_process_settings->m_output_path;
2764    m_error_path = new_process_settings->m_error_path;
2765    m_plugin = new_process_settings->m_plugin;
2766    m_disable_aslr = new_process_settings->m_disable_aslr;
2767    m_disable_stdio = new_process_settings->m_disable_stdio;
2768}
2769
2770bool
2771ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2772                                                   const ConstString &var_name,
2773                                                   StringList &value,
2774                                                   Error *err)
2775{
2776    if (var_name == RunArgsVarName())
2777    {
2778        if (m_run_args.GetArgumentCount() > 0)
2779        {
2780            for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2781                value.AppendString (m_run_args.GetArgumentAtIndex (i));
2782        }
2783    }
2784    else if (var_name == EnvVarsVarName())
2785    {
2786        GetHostEnvironmentIfNeeded ();
2787
2788        if (m_env_vars.size() > 0)
2789        {
2790            std::map<std::string, std::string>::iterator pos;
2791            for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2792            {
2793                StreamString value_str;
2794                value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2795                value.AppendString (value_str.GetData());
2796            }
2797        }
2798    }
2799    else if (var_name == InputPathVarName())
2800    {
2801        value.AppendString (m_input_path.c_str());
2802    }
2803    else if (var_name == OutputPathVarName())
2804    {
2805        value.AppendString (m_output_path.c_str());
2806    }
2807    else if (var_name == ErrorPathVarName())
2808    {
2809        value.AppendString (m_error_path.c_str());
2810    }
2811    else if (var_name == PluginVarName())
2812    {
2813        value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2814    }
2815    else if (var_name == InheritHostEnvVarName())
2816    {
2817        if (m_inherit_host_env)
2818            value.AppendString ("true");
2819        else
2820            value.AppendString ("false");
2821    }
2822    else if (var_name == DisableASLRVarName())
2823    {
2824        if (m_disable_aslr)
2825            value.AppendString ("true");
2826        else
2827            value.AppendString ("false");
2828    }
2829    else if (var_name == DisableSTDIOVarName())
2830    {
2831        if (m_disable_stdio)
2832            value.AppendString ("true");
2833        else
2834            value.AppendString ("false");
2835    }
2836    else
2837    {
2838        if (err)
2839            err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2840        return false;
2841    }
2842    return true;
2843}
2844
2845const ConstString
2846ProcessInstanceSettings::CreateInstanceName ()
2847{
2848    static int instance_count = 1;
2849    StreamString sstr;
2850
2851    sstr.Printf ("process_%d", instance_count);
2852    ++instance_count;
2853
2854    const ConstString ret_val (sstr.GetData());
2855    return ret_val;
2856}
2857
2858const ConstString &
2859ProcessInstanceSettings::RunArgsVarName ()
2860{
2861    static ConstString run_args_var_name ("run-args");
2862
2863    return run_args_var_name;
2864}
2865
2866const ConstString &
2867ProcessInstanceSettings::EnvVarsVarName ()
2868{
2869    static ConstString env_vars_var_name ("env-vars");
2870
2871    return env_vars_var_name;
2872}
2873
2874const ConstString &
2875ProcessInstanceSettings::InheritHostEnvVarName ()
2876{
2877    static ConstString g_name ("inherit-env");
2878
2879    return g_name;
2880}
2881
2882const ConstString &
2883ProcessInstanceSettings::InputPathVarName ()
2884{
2885  static ConstString input_path_var_name ("input-path");
2886
2887    return input_path_var_name;
2888}
2889
2890const ConstString &
2891ProcessInstanceSettings::OutputPathVarName ()
2892{
2893    static ConstString output_path_var_name ("output-path");
2894
2895    return output_path_var_name;
2896}
2897
2898const ConstString &
2899ProcessInstanceSettings::ErrorPathVarName ()
2900{
2901    static ConstString error_path_var_name ("error-path");
2902
2903    return error_path_var_name;
2904}
2905
2906const ConstString &
2907ProcessInstanceSettings::PluginVarName ()
2908{
2909    static ConstString plugin_var_name ("plugin");
2910
2911    return plugin_var_name;
2912}
2913
2914
2915const ConstString &
2916ProcessInstanceSettings::DisableASLRVarName ()
2917{
2918    static ConstString disable_aslr_var_name ("disable-aslr");
2919
2920    return disable_aslr_var_name;
2921}
2922
2923const ConstString &
2924ProcessInstanceSettings::DisableSTDIOVarName ()
2925{
2926    static ConstString disable_stdio_var_name ("disable-stdio");
2927
2928    return disable_stdio_var_name;
2929}
2930
2931//--------------------------------------------------
2932// SettingsController Variable Tables
2933//--------------------------------------------------
2934
2935SettingEntry
2936Process::SettingsController::global_settings_table[] =
2937{
2938  //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
2939    {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2940};
2941
2942
2943lldb::OptionEnumValueElement
2944Process::SettingsController::g_plugins[] =
2945{
2946    { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2947    { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2948    { 0, NULL, NULL }
2949};
2950
2951SettingEntry
2952Process::SettingsController::instance_settings_table[] =
2953{
2954  //{ "var-name",       var-type,              "default",       enum-table, init'd, hidden, "help-text"},
2955    { "run-args",       eSetVarTypeArray,       NULL,           NULL,       false,  false,  "A list containing all the arguments to be passed to the executable when it is run." },
2956    { "env-vars",       eSetVarTypeDictionary,  NULL,           NULL,       false,  false,  "A list of all the environment variables to be passed to the executable's environment, and their values." },
2957    { "inherit-env",    eSetVarTypeBoolean,     "true",         NULL,       false,  false,  "Inherit the environment from the process that is running LLDB." },
2958    { "input-path",     eSetVarTypeString,      "/dev/stdin",   NULL,       false,  false,  "The file/path to be used by the executable program for reading its input." },
2959    { "output-path",    eSetVarTypeString,      "/dev/stdout",  NULL,       false,  false,  "The file/path to be used by the executable program for writing its output." },
2960    { "error-path",     eSetVarTypeString,      "/dev/stderr",  NULL,       false,  false,  "The file/path to be used by the executable program for writings its error messages." },
2961    { "plugin",         eSetVarTypeEnum,        NULL         ,  g_plugins,  false,  false,  "The plugin to be used to run the process." },
2962    { "disable-aslr",   eSetVarTypeBoolean,     "true",         NULL,       false,  false,  "Disable Address Space Layout Randomization (ASLR)" },
2963    { "disable-stdio",  eSetVarTypeBoolean,     "false",        NULL,       false,  false,  "Disable stdin/stdout for process (e.g. for a GUI application)" },
2964    {  NULL,            eSetVarTypeNone,        NULL,           NULL,       false,  false,  NULL }
2965};
2966
2967
2968
2969