blob: d71626790bffadd91fc744207eea1ffa13c83c14 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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/Debugger.h"
18#include "lldb/Core/Log.h"
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000021#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Host/Host.h"
23#include "lldb/Target/ABI.h"
Jim Ingham642036f2010-09-23 02:01:19 +000024#include "lldb/Target/LanguageRuntime.h"
25#include "lldb/Target/CPPLanguageRuntime.h"
26#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000028#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "lldb/Target/Target.h"
30#include "lldb/Target/TargetList.h"
31#include "lldb/Target/Thread.h"
32#include "lldb/Target/ThreadPlan.h"
33
34using namespace lldb;
35using namespace lldb_private;
36
37Process*
38Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
39{
40 ProcessCreateInstance create_callback = NULL;
41 if (plugin_name)
42 {
43 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
44 if (create_callback)
45 {
46 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
47 if (debugger_ap->CanDebug(target))
48 return debugger_ap.release();
49 }
50 }
51 else
52 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000053 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +000054 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000055 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
56 if (debugger_ap->CanDebug(target))
57 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +000058 }
59 }
60 return NULL;
61}
62
63
64//----------------------------------------------------------------------
65// Process constructor
66//----------------------------------------------------------------------
67Process::Process(Target &target, Listener &listener) :
68 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +000069 Broadcaster ("lldb.process"),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000070 ProcessInstanceSettings (*(Process::GetSettingsController().get())),
Chris Lattner24943d22010-06-08 16:52:24 +000071 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +000072 m_public_state (eStateUnloaded),
73 m_private_state (eStateUnloaded),
74 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
75 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
76 m_private_state_listener ("lldb.process.internal_state_listener"),
77 m_private_state_control_wait(),
78 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
79 m_stop_id (0),
80 m_thread_index_id (0),
81 m_exit_status (-1),
82 m_exit_string (),
83 m_thread_list (this),
84 m_notifications (),
Jim Inghamd1686902010-10-14 23:45:03 +000085 m_persistent_vars(),
Chris Lattner24943d22010-06-08 16:52:24 +000086 m_listener(listener),
Jim Inghamd1686902010-10-14 23:45:03 +000087 m_unix_signals ()
Chris Lattner24943d22010-06-08 16:52:24 +000088{
Caroline Tice1ebef442010-09-27 00:30:10 +000089 UpdateInstanceName();
90
Chris Lattner24943d22010-06-08 16:52:24 +000091 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
92 if (log)
93 log->Printf ("%p Process::Process()", this);
94
Greg Clayton49ce6822010-10-31 03:01:06 +000095 SetEventName (eBroadcastBitStateChanged, "state-changed");
96 SetEventName (eBroadcastBitInterrupt, "interrupt");
97 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
98 SetEventName (eBroadcastBitSTDERR, "stderr-available");
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100 listener.StartListeningForEvents (this,
101 eBroadcastBitStateChanged |
102 eBroadcastBitInterrupt |
103 eBroadcastBitSTDOUT |
104 eBroadcastBitSTDERR);
105
106 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
107 eBroadcastBitStateChanged);
108
109 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
110 eBroadcastInternalStateControlStop |
111 eBroadcastInternalStateControlPause |
112 eBroadcastInternalStateControlResume);
113}
114
115//----------------------------------------------------------------------
116// Destructor
117//----------------------------------------------------------------------
118Process::~Process()
119{
120 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
121 if (log)
122 log->Printf ("%p Process::~Process()", this);
123 StopPrivateStateThread();
124}
125
126void
127Process::Finalize()
128{
129 // Do any cleanup needed prior to being destructed... Subclasses
130 // that override this method should call this superclass method as well.
131}
132
133void
134Process::RegisterNotificationCallbacks (const Notifications& callbacks)
135{
136 m_notifications.push_back(callbacks);
137 if (callbacks.initialize != NULL)
138 callbacks.initialize (callbacks.baton, this);
139}
140
141bool
142Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
143{
144 std::vector<Notifications>::iterator pos, end = m_notifications.end();
145 for (pos = m_notifications.begin(); pos != end; ++pos)
146 {
147 if (pos->baton == callbacks.baton &&
148 pos->initialize == callbacks.initialize &&
149 pos->process_state_changed == callbacks.process_state_changed)
150 {
151 m_notifications.erase(pos);
152 return true;
153 }
154 }
155 return false;
156}
157
158void
159Process::SynchronouslyNotifyStateChanged (StateType state)
160{
161 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
162 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
163 {
164 if (notification_pos->process_state_changed)
165 notification_pos->process_state_changed (notification_pos->baton, this, state);
166 }
167}
168
169// FIXME: We need to do some work on events before the general Listener sees them.
170// For instance if we are continuing from a breakpoint, we need to ensure that we do
171// the little "insert real insn, step & stop" trick. But we can't do that when the
172// event is delivered by the broadcaster - since that is done on the thread that is
173// waiting for new events, so if we needed more than one event for our handling, we would
174// stall. So instead we do it when we fetch the event off of the queue.
175//
176
177StateType
178Process::GetNextEvent (EventSP &event_sp)
179{
180 StateType state = eStateInvalid;
181
182 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
183 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
184
185 return state;
186}
187
188
189StateType
190Process::WaitForProcessToStop (const TimeValue *timeout)
191{
192 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
193 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
194}
195
196
197StateType
198Process::WaitForState
199(
200 const TimeValue *timeout,
201 const StateType *match_states, const uint32_t num_match_states
202)
203{
204 EventSP event_sp;
205 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000206 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000207 while (state != eStateInvalid)
208 {
Greg Claytond8c62532010-10-07 04:19:01 +0000209 // If we are exited or detached, we won't ever get back to any
210 // other valid state...
211 if (state == eStateDetached || state == eStateExited)
212 return state;
213
Chris Lattner24943d22010-06-08 16:52:24 +0000214 state = WaitForStateChangedEvents (timeout, event_sp);
215
216 for (i=0; i<num_match_states; ++i)
217 {
218 if (match_states[i] == state)
219 return state;
220 }
221 }
222 return state;
223}
224
Jim Ingham63e24d72010-10-11 23:53:14 +0000225bool
226Process::HijackProcessEvents (Listener *listener)
227{
228 if (listener != NULL)
229 {
230 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
231 }
232 else
233 return false;
234}
235
236void
237Process::RestoreProcessEvents ()
238{
239 RestoreBroadcaster();
240}
241
Chris Lattner24943d22010-06-08 16:52:24 +0000242StateType
243Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
244{
245 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
246
247 if (log)
248 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
249
250 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000251 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
252 this,
253 eBroadcastBitStateChanged,
254 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000255 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
256
Caroline Tice926060e2010-10-29 21:48:37 +0000257 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000258 if (log)
259 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
260 __FUNCTION__,
261 timeout,
262 StateAsCString(state));
263 return state;
264}
265
266Event *
267Process::PeekAtStateChangedEvents ()
268{
269 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
270
271 if (log)
272 log->Printf ("Process::%s...", __FUNCTION__);
273
274 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000275 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
276 eBroadcastBitStateChanged);
Caroline Tice926060e2010-10-29 21:48:37 +0000277 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000278 if (log)
279 {
280 if (event_ptr)
281 {
282 log->Printf ("Process::%s (event_ptr) => %s",
283 __FUNCTION__,
284 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
285 }
286 else
287 {
288 log->Printf ("Process::%s no events found",
289 __FUNCTION__);
290 }
291 }
292 return event_ptr;
293}
294
295StateType
296Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
297{
298 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
299
300 if (log)
301 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
302
303 StateType state = eStateInvalid;
304 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
305 &m_private_state_broadcaster,
306 eBroadcastBitStateChanged,
307 event_sp))
308 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
309
310 // This is a bit of a hack, but when we wait here we could very well return
311 // to the command-line, and that could disable the log, which would render the
312 // log we got above invalid.
313 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
314 if (log)
315 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
316 return state;
317}
318
319bool
320Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
321{
322 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
323
324 if (log)
325 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
326
327 if (control_only)
328 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
329 else
330 return m_private_state_listener.WaitForEvent(timeout, event_sp);
331}
332
333bool
334Process::IsRunning () const
335{
336 return StateIsRunningState (m_public_state.GetValue());
337}
338
339int
340Process::GetExitStatus ()
341{
342 if (m_public_state.GetValue() == eStateExited)
343 return m_exit_status;
344 return -1;
345}
346
347const char *
348Process::GetExitDescription ()
349{
350 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
351 return m_exit_string.c_str();
352 return NULL;
353}
354
355void
356Process::SetExitStatus (int status, const char *cstr)
357{
358 m_exit_status = status;
359 if (cstr)
360 m_exit_string = cstr;
361 else
362 m_exit_string.clear();
363
364 SetPrivateState (eStateExited);
365}
366
367// This static callback can be used to watch for local child processes on
368// the current host. The the child process exits, the process will be
369// found in the global target list (we want to be completely sure that the
370// lldb_private::Process doesn't go away before we can deliver the signal.
371bool
372Process::SetProcessExitStatus
373(
374 void *callback_baton,
375 lldb::pid_t pid,
376 int signo, // Zero for no signal
377 int exit_status // Exit value of process if signal is zero
378)
379{
380 if (signo == 0 || exit_status)
381 {
Greg Clayton63094e02010-06-23 01:19:29 +0000382 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000383 if (target_sp)
384 {
385 ProcessSP process_sp (target_sp->GetProcessSP());
386 if (process_sp)
387 {
388 const char *signal_cstr = NULL;
389 if (signo)
390 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
391
392 process_sp->SetExitStatus (exit_status, signal_cstr);
393 }
394 }
395 return true;
396 }
397 return false;
398}
399
400
401uint32_t
402Process::GetNextThreadIndexID ()
403{
404 return ++m_thread_index_id;
405}
406
407StateType
408Process::GetState()
409{
410 // If any other threads access this we will need a mutex for it
411 return m_public_state.GetValue ();
412}
413
414void
415Process::SetPublicState (StateType new_state)
416{
417 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
418 if (log)
419 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
420 m_public_state.SetValue (new_state);
421}
422
423StateType
424Process::GetPrivateState ()
425{
426 return m_private_state.GetValue();
427}
428
429void
430Process::SetPrivateState (StateType new_state)
431{
432 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
433 bool state_changed = false;
434
435 if (log)
436 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
437
438 Mutex::Locker locker(m_private_state.GetMutex());
439
440 const StateType old_state = m_private_state.GetValueNoLock ();
441 state_changed = old_state != new_state;
442 if (state_changed)
443 {
444 m_private_state.SetValueNoLock (new_state);
445 if (StateIsStoppedState(new_state))
446 {
447 m_stop_id++;
448 if (log)
449 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
450 }
451 // Use our target to get a shared pointer to ourselves...
452 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
453 }
454 else
455 {
456 if (log)
457 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
458 }
459}
460
461
462uint32_t
463Process::GetStopID() const
464{
465 return m_stop_id;
466}
467
468addr_t
469Process::GetImageInfoAddress()
470{
471 return LLDB_INVALID_ADDRESS;
472}
473
474DynamicLoader *
475Process::GetDynamicLoader()
476{
477 return NULL;
478}
479
480const ABI *
481Process::GetABI()
482{
483 ConstString& triple = m_target_triple;
484
485 if (triple.IsEmpty())
486 return NULL;
487
488 if (m_abi_sp.get() == NULL)
489 {
490 m_abi_sp.reset(ABI::FindPlugin(triple));
491 }
492
493 return m_abi_sp.get();
494}
495
Jim Ingham642036f2010-09-23 02:01:19 +0000496LanguageRuntime *
497Process::GetLanguageRuntime(lldb::LanguageType language)
498{
499 LanguageRuntimeCollection::iterator pos;
500 pos = m_language_runtimes.find (language);
501 if (pos == m_language_runtimes.end())
502 {
503 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
504
505 m_language_runtimes[language]
506 = runtime;
507 return runtime.get();
508 }
509 else
510 return (*pos).second.get();
511}
512
513CPPLanguageRuntime *
514Process::GetCPPLanguageRuntime ()
515{
516 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
517 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
518 return static_cast<CPPLanguageRuntime *> (runtime);
519 return NULL;
520}
521
522ObjCLanguageRuntime *
523Process::GetObjCLanguageRuntime ()
524{
525 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
526 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
527 return static_cast<ObjCLanguageRuntime *> (runtime);
528 return NULL;
529}
530
Chris Lattner24943d22010-06-08 16:52:24 +0000531BreakpointSiteList &
532Process::GetBreakpointSiteList()
533{
534 return m_breakpoint_site_list;
535}
536
537const BreakpointSiteList &
538Process::GetBreakpointSiteList() const
539{
540 return m_breakpoint_site_list;
541}
542
543
544void
545Process::DisableAllBreakpointSites ()
546{
547 m_breakpoint_site_list.SetEnabledForAll (false);
548}
549
550Error
551Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
552{
553 Error error (DisableBreakpointSiteByID (break_id));
554
555 if (error.Success())
556 m_breakpoint_site_list.Remove(break_id);
557
558 return error;
559}
560
561Error
562Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
563{
564 Error error;
565 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
566 if (bp_site_sp)
567 {
568 if (bp_site_sp->IsEnabled())
569 error = DisableBreakpoint (bp_site_sp.get());
570 }
571 else
572 {
573 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
574 }
575
576 return error;
577}
578
579Error
580Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
581{
582 Error error;
583 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
584 if (bp_site_sp)
585 {
586 if (!bp_site_sp->IsEnabled())
587 error = EnableBreakpoint (bp_site_sp.get());
588 }
589 else
590 {
591 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
592 }
593 return error;
594}
595
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000596lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000597Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
598{
Greg Claytoneea26402010-09-14 23:36:40 +0000599 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000600 if (load_addr != LLDB_INVALID_ADDRESS)
601 {
602 BreakpointSiteSP bp_site_sp;
603
604 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
605 // create a new breakpoint site and add it.
606
607 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
608
609 if (bp_site_sp)
610 {
611 bp_site_sp->AddOwner (owner);
612 owner->SetBreakpointSite (bp_site_sp);
613 return bp_site_sp->GetID();
614 }
615 else
616 {
617 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
618 if (bp_site_sp)
619 {
620 if (EnableBreakpoint (bp_site_sp.get()).Success())
621 {
622 owner->SetBreakpointSite (bp_site_sp);
623 return m_breakpoint_site_list.Add (bp_site_sp);
624 }
625 }
626 }
627 }
628 // We failed to enable the breakpoint
629 return LLDB_INVALID_BREAK_ID;
630
631}
632
633void
634Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
635{
636 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
637 if (num_owners == 0)
638 {
639 DisableBreakpoint(bp_site_sp.get());
640 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
641 }
642}
643
644
645size_t
646Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
647{
648 size_t bytes_removed = 0;
649 addr_t intersect_addr;
650 size_t intersect_size;
651 size_t opcode_offset;
652 size_t idx;
653 BreakpointSiteSP bp;
654
655 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
656 {
657 if (bp->GetType() == BreakpointSite::eSoftware)
658 {
659 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
660 {
661 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
662 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
663 assert(opcode_offset + intersect_size <= bp->GetByteSize());
664 size_t buf_offset = intersect_addr - bp_addr;
665 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
666 }
667 }
668 }
669 return bytes_removed;
670}
671
672
673Error
674Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
675{
676 Error error;
677 assert (bp_site != NULL);
678 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
679 const addr_t bp_addr = bp_site->GetLoadAddress();
680 if (log)
681 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
682 if (bp_site->IsEnabled())
683 {
684 if (log)
685 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
686 return error;
687 }
688
689 if (bp_addr == LLDB_INVALID_ADDRESS)
690 {
691 error.SetErrorString("BreakpointSite contains an invalid load address.");
692 return error;
693 }
694 // Ask the lldb::Process subclass to fill in the correct software breakpoint
695 // trap for the breakpoint site
696 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
697
698 if (bp_opcode_size == 0)
699 {
700 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
701 }
702 else
703 {
704 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
705
706 if (bp_opcode_bytes == NULL)
707 {
708 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
709 return error;
710 }
711
712 // Save the original opcode by reading it
713 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
714 {
715 // Write a software breakpoint in place of the original opcode
716 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
717 {
718 uint8_t verify_bp_opcode_bytes[64];
719 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
720 {
721 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
722 {
723 bp_site->SetEnabled(true);
724 bp_site->SetType (BreakpointSite::eSoftware);
725 if (log)
726 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
727 bp_site->GetID(),
728 (uint64_t)bp_addr);
729 }
730 else
731 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
732 }
733 else
734 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
735 }
736 else
737 error.SetErrorString("Unable to write breakpoint trap to memory.");
738 }
739 else
740 error.SetErrorString("Unable to read memory at breakpoint address.");
741 }
742 if (log)
743 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
744 bp_site->GetID(),
745 (uint64_t)bp_addr,
746 error.AsCString());
747 return error;
748}
749
750Error
751Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
752{
753 Error error;
754 assert (bp_site != NULL);
755 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
756 addr_t bp_addr = bp_site->GetLoadAddress();
757 lldb::user_id_t breakID = bp_site->GetID();
758 if (log)
759 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
760
761 if (bp_site->IsHardware())
762 {
763 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
764 }
765 else if (bp_site->IsEnabled())
766 {
767 const size_t break_op_size = bp_site->GetByteSize();
768 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
769 if (break_op_size > 0)
770 {
771 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +0000772 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000773 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +0000774 bool break_op_found = false;
775
776 // Read the breakpoint opcode
777 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
778 {
779 bool verify = false;
780 // Make sure we have the a breakpoint opcode exists at this address
781 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
782 {
783 break_op_found = true;
784 // We found a valid breakpoint opcode at this address, now restore
785 // the saved opcode.
786 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
787 {
788 verify = true;
789 }
790 else
791 error.SetErrorString("Memory write failed when restoring original opcode.");
792 }
793 else
794 {
795 error.SetErrorString("Original breakpoint trap is no longer in memory.");
796 // Set verify to true and so we can check if the original opcode has already been restored
797 verify = true;
798 }
799
800 if (verify)
801 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000802 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000803 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +0000804 // Verify that our original opcode made it back to the inferior
805 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
806 {
807 // compare the memory we just read with the original opcode
808 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
809 {
810 // SUCCESS
811 bp_site->SetEnabled(false);
812 if (log)
813 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
814 return error;
815 }
816 else
817 {
818 if (break_op_found)
819 error.SetErrorString("Failed to restore original opcode.");
820 }
821 }
822 else
823 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
824 }
825 }
826 else
827 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
828 }
829 }
830 else
831 {
832 if (log)
833 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
834 return error;
835 }
836
837 if (log)
838 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
839 bp_site->GetID(),
840 (uint64_t)bp_addr,
841 error.AsCString());
842 return error;
843
844}
845
846
847size_t
848Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
849{
850 if (buf == NULL || size == 0)
851 return 0;
852
853 size_t bytes_read = 0;
854 uint8_t *bytes = (uint8_t *)buf;
855
856 while (bytes_read < size)
857 {
858 const size_t curr_size = size - bytes_read;
859 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
860 bytes + bytes_read,
861 curr_size,
862 error);
863 bytes_read += curr_bytes_read;
864 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
865 break;
866 }
867
868 // Replace any software breakpoint opcodes that fall into this range back
869 // into "buf" before we return
870 if (bytes_read > 0)
871 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
872 return bytes_read;
873}
874
875size_t
876Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
877{
878 size_t bytes_written = 0;
879 const uint8_t *bytes = (const uint8_t *)buf;
880
881 while (bytes_written < size)
882 {
883 const size_t curr_size = size - bytes_written;
884 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
885 bytes + bytes_written,
886 curr_size,
887 error);
888 bytes_written += curr_bytes_written;
889 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
890 break;
891 }
892 return bytes_written;
893}
894
895size_t
896Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
897{
898 if (buf == NULL || size == 0)
899 return 0;
900 // We need to write any data that would go where any current software traps
901 // (enabled software breakpoints) any software traps (breakpoints) that we
902 // may have placed in our tasks memory.
903
904 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
905 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
906
907 if (iter == end || iter->second->GetLoadAddress() > addr + size)
908 return DoWriteMemory(addr, buf, size, error);
909
910 BreakpointSiteList::collection::const_iterator pos;
911 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000912 addr_t intersect_addr = 0;
913 size_t intersect_size = 0;
914 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000915 const uint8_t *ubuf = (const uint8_t *)buf;
916
917 for (pos = iter; pos != end; ++pos)
918 {
919 BreakpointSiteSP bp;
920 bp = pos->second;
921
922 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
923 assert(addr <= intersect_addr && intersect_addr < addr + size);
924 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
925 assert(opcode_offset + intersect_size <= bp->GetByteSize());
926
927 // Check for bytes before this breakpoint
928 const addr_t curr_addr = addr + bytes_written;
929 if (intersect_addr > curr_addr)
930 {
931 // There are some bytes before this breakpoint that we need to
932 // just write to memory
933 size_t curr_size = intersect_addr - curr_addr;
934 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
935 ubuf + bytes_written,
936 curr_size,
937 error);
938 bytes_written += curr_bytes_written;
939 if (curr_bytes_written != curr_size)
940 {
941 // We weren't able to write all of the requested bytes, we
942 // are done looping and will return the number of bytes that
943 // we have written so far.
944 break;
945 }
946 }
947
948 // Now write any bytes that would cover up any software breakpoints
949 // directly into the breakpoint opcode buffer
950 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
951 bytes_written += intersect_size;
952 }
953
954 // Write any remaining bytes after the last breakpoint if we have any left
955 if (bytes_written < size)
956 bytes_written += WriteMemoryPrivate (addr + bytes_written,
957 ubuf + bytes_written,
958 size - bytes_written,
959 error);
960
961 return bytes_written;
962}
963
964addr_t
965Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
966{
967 // Fixme: we should track the blocks we've allocated, and clean them up...
968 // We could even do our own allocator here if that ends up being more efficient.
969 return DoAllocateMemory (size, permissions, error);
970}
971
972Error
973Process::DeallocateMemory (addr_t ptr)
974{
975 return DoDeallocateMemory (ptr);
976}
977
978
979Error
980Process::EnableWatchpoint (WatchpointLocation *watchpoint)
981{
982 Error error;
983 error.SetErrorString("watchpoints are not supported");
984 return error;
985}
986
987Error
988Process::DisableWatchpoint (WatchpointLocation *watchpoint)
989{
990 Error error;
991 error.SetErrorString("watchpoints are not supported");
992 return error;
993}
994
995StateType
996Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
997{
998 StateType state;
999 // Now wait for the process to launch and return control to us, and then
1000 // call DidLaunch:
1001 while (1)
1002 {
1003 // FIXME: Might want to put a timeout in here:
1004 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1005 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1006 break;
1007 else
1008 HandlePrivateEvent (event_sp);
1009 }
1010 return state;
1011}
1012
1013Error
1014Process::Launch
1015(
1016 char const *argv[],
1017 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001018 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001019 const char *stdin_path,
1020 const char *stdout_path,
1021 const char *stderr_path
1022)
1023{
1024 Error error;
1025 m_target_triple.Clear();
1026 m_abi_sp.reset();
1027
1028 Module *exe_module = m_target.GetExecutableModule().get();
1029 if (exe_module)
1030 {
1031 char exec_file_path[PATH_MAX];
1032 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1033 if (exe_module->GetFileSpec().Exists())
1034 {
1035 error = WillLaunch (exe_module);
1036 if (error.Success())
1037 {
Greg Claytond8c62532010-10-07 04:19:01 +00001038 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001039 // The args coming in should not contain the application name, the
1040 // lldb_private::Process class will add this in case the executable
1041 // gets resolved to a different file than was given on the command
1042 // line (like when an applicaiton bundle is specified and will
1043 // resolve to the contained exectuable file, or the file given was
1044 // a symlink or other file system link that resolves to a different
1045 // file).
1046
1047 // Get the resolved exectuable path
1048
1049 // Make a new argument vector
1050 std::vector<const char *> exec_path_plus_argv;
1051 // Append the resolved executable path
1052 exec_path_plus_argv.push_back (exec_file_path);
1053
1054 // Push all args if there are any
1055 if (argv)
1056 {
1057 for (int i = 0; argv[i]; ++i)
1058 exec_path_plus_argv.push_back(argv[i]);
1059 }
1060
1061 // Push a NULL to terminate the args.
1062 exec_path_plus_argv.push_back(NULL);
1063
1064 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001065 error = DoLaunch (exe_module,
1066 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1067 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001068 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001069 stdin_path,
1070 stdout_path,
1071 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001072
1073 if (error.Fail())
1074 {
1075 if (GetID() != LLDB_INVALID_PROCESS_ID)
1076 {
1077 SetID (LLDB_INVALID_PROCESS_ID);
1078 const char *error_string = error.AsCString();
1079 if (error_string == NULL)
1080 error_string = "launch failed";
1081 SetExitStatus (-1, error_string);
1082 }
1083 }
1084 else
1085 {
1086 EventSP event_sp;
1087 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1088
1089 if (state == eStateStopped || state == eStateCrashed)
1090 {
1091 DidLaunch ();
1092
1093 // This delays passing the stopped event to listeners till DidLaunch gets
1094 // a chance to complete...
1095 HandlePrivateEvent (event_sp);
1096 StartPrivateStateThread ();
1097 }
1098 else if (state == eStateExited)
1099 {
1100 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1101 // not likely to work, and return an invalid pid.
1102 HandlePrivateEvent (event_sp);
1103 }
1104 }
1105 }
1106 }
1107 else
1108 {
1109 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1110 }
1111 }
1112 return error;
1113}
1114
1115Error
1116Process::CompleteAttach ()
1117{
1118 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001119
1120 if (GetID() == LLDB_INVALID_PROCESS_ID)
1121 {
1122 error.SetErrorString("no process");
1123 }
1124
Chris Lattner24943d22010-06-08 16:52:24 +00001125 EventSP event_sp;
1126 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1127 if (state == eStateStopped || state == eStateCrashed)
1128 {
1129 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001130 // Figure out which one is the executable, and set that in our target:
1131 ModuleList &modules = GetTarget().GetImages();
1132
1133 size_t num_modules = modules.GetSize();
1134 for (int i = 0; i < num_modules; i++)
1135 {
1136 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1137 if (module_sp->IsExecutable())
1138 {
1139 ModuleSP exec_module = GetTarget().GetExecutableModule();
1140 if (!exec_module || exec_module != module_sp)
1141 {
1142
1143 GetTarget().SetExecutableModule (module_sp, false);
1144 }
1145 break;
1146 }
1147 }
Chris Lattner24943d22010-06-08 16:52:24 +00001148
1149 // This delays passing the stopped event to listeners till DidLaunch gets
1150 // a chance to complete...
1151 HandlePrivateEvent(event_sp);
1152 StartPrivateStateThread();
1153 }
1154 else
1155 {
1156 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1157 // not likely to work, and return an invalid pid.
1158 if (state == eStateExited)
1159 HandlePrivateEvent (event_sp);
1160 error.SetErrorStringWithFormat("invalid state after attach: %s",
1161 lldb_private::StateAsCString(state));
1162 }
1163 return error;
1164}
1165
1166Error
1167Process::Attach (lldb::pid_t attach_pid)
1168{
1169
1170 m_target_triple.Clear();
1171 m_abi_sp.reset();
1172
Jim Ingham7508e732010-08-09 23:31:02 +00001173 // Find the process and its architecture. Make sure it matches the architecture
1174 // of the current Target, and if not adjust it.
1175
1176 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1177 if (attach_spec != GetTarget().GetArchitecture())
1178 {
1179 // Set the architecture on the target.
1180 GetTarget().SetArchitecture(attach_spec);
1181 }
1182
Greg Clayton54e7afa2010-07-09 20:39:50 +00001183 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001184 if (error.Success())
1185 {
Greg Claytond8c62532010-10-07 04:19:01 +00001186 SetPublicState (eStateAttaching);
1187
Greg Clayton54e7afa2010-07-09 20:39:50 +00001188 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001189 if (error.Success())
1190 {
1191 error = CompleteAttach();
1192 }
1193 else
1194 {
1195 if (GetID() != LLDB_INVALID_PROCESS_ID)
1196 {
1197 SetID (LLDB_INVALID_PROCESS_ID);
1198 const char *error_string = error.AsCString();
1199 if (error_string == NULL)
1200 error_string = "attach failed";
1201
1202 SetExitStatus(-1, error_string);
1203 }
1204 }
1205 }
1206 return error;
1207}
1208
1209Error
1210Process::Attach (const char *process_name, bool wait_for_launch)
1211{
1212 m_target_triple.Clear();
1213 m_abi_sp.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001214
1215 // Find the process and its architecture. Make sure it matches the architecture
1216 // of the current Target, and if not adjust it.
1217
Jim Inghamea294182010-08-17 21:54:19 +00001218 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001219 {
Jim Inghamea294182010-08-17 21:54:19 +00001220 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001221 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001222 {
1223 // Set the architecture on the target.
1224 GetTarget().SetArchitecture(attach_spec);
1225 }
Jim Ingham7508e732010-08-09 23:31:02 +00001226 }
Jim Inghamea294182010-08-17 21:54:19 +00001227
Greg Clayton54e7afa2010-07-09 20:39:50 +00001228 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001229 if (error.Success())
1230 {
Greg Claytond8c62532010-10-07 04:19:01 +00001231 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001232 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001233 if (error.Fail())
1234 {
1235 if (GetID() != LLDB_INVALID_PROCESS_ID)
1236 {
1237 SetID (LLDB_INVALID_PROCESS_ID);
1238 const char *error_string = error.AsCString();
1239 if (error_string == NULL)
1240 error_string = "attach failed";
1241
1242 SetExitStatus(-1, error_string);
1243 }
1244 }
1245 else
1246 {
1247 error = CompleteAttach();
1248 }
1249 }
1250 return error;
1251}
1252
1253Error
1254Process::Resume ()
1255{
1256 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1257 if (log)
1258 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1259
1260 Error error (WillResume());
1261 // Tell the process it is about to resume before the thread list
1262 if (error.Success())
1263 {
1264 // Now let the thread list know we are about to resume to it
1265 // can let all of our threads know that they are about to be
1266 // resumed. Threads will each be called with
1267 // Thread::WillResume(StateType) where StateType contains the state
1268 // that they are supposed to have when the process is resumed
1269 // (suspended/running/stepping). Threads should also check
1270 // their resume signal in lldb::Thread::GetResumeSignal()
1271 // to see if they are suppoed to start back up with a signal.
1272 if (m_thread_list.WillResume())
1273 {
1274 error = DoResume();
1275 if (error.Success())
1276 {
1277 DidResume();
1278 m_thread_list.DidResume();
1279 }
1280 }
1281 else
1282 {
1283 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1284 }
1285 }
1286 return error;
1287}
1288
1289Error
1290Process::Halt ()
1291{
1292 Error error (WillHalt());
1293
1294 if (error.Success())
1295 {
1296 error = DoHalt();
1297 if (error.Success())
1298 DidHalt();
1299 }
1300 return error;
1301}
1302
1303Error
1304Process::Detach ()
1305{
1306 Error error (WillDetach());
1307
1308 if (error.Success())
1309 {
1310 DisableAllBreakpointSites();
1311 error = DoDetach();
1312 if (error.Success())
1313 {
1314 DidDetach();
1315 StopPrivateStateThread();
1316 }
1317 }
1318 return error;
1319}
1320
1321Error
1322Process::Destroy ()
1323{
1324 Error error (WillDestroy());
1325 if (error.Success())
1326 {
1327 DisableAllBreakpointSites();
1328 error = DoDestroy();
1329 if (error.Success())
1330 {
1331 DidDestroy();
1332 StopPrivateStateThread();
1333 }
1334 }
1335 return error;
1336}
1337
1338Error
1339Process::Signal (int signal)
1340{
1341 Error error (WillSignal());
1342 if (error.Success())
1343 {
1344 error = DoSignal(signal);
1345 if (error.Success())
1346 DidSignal();
1347 }
1348 return error;
1349}
1350
1351UnixSignals &
1352Process::GetUnixSignals ()
1353{
1354 return m_unix_signals;
1355}
1356
1357Target &
1358Process::GetTarget ()
1359{
1360 return m_target;
1361}
1362
1363const Target &
1364Process::GetTarget () const
1365{
1366 return m_target;
1367}
1368
1369uint32_t
1370Process::GetAddressByteSize()
1371{
1372 return m_target.GetArchitecture().GetAddressByteSize();
1373}
1374
1375bool
1376Process::ShouldBroadcastEvent (Event *event_ptr)
1377{
1378 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1379 bool return_value = true;
1380 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1381
1382 switch (state)
1383 {
1384 case eStateAttaching:
1385 case eStateLaunching:
1386 case eStateDetached:
1387 case eStateExited:
1388 case eStateUnloaded:
1389 // These events indicate changes in the state of the debugging session, always report them.
1390 return_value = true;
1391 break;
1392 case eStateInvalid:
1393 // We stopped for no apparent reason, don't report it.
1394 return_value = false;
1395 break;
1396 case eStateRunning:
1397 case eStateStepping:
1398 // If we've started the target running, we handle the cases where we
1399 // are already running and where there is a transition from stopped to
1400 // running differently.
1401 // running -> running: Automatically suppress extra running events
1402 // stopped -> running: Report except when there is one or more no votes
1403 // and no yes votes.
1404 SynchronouslyNotifyStateChanged (state);
1405 switch (m_public_state.GetValue())
1406 {
1407 case eStateRunning:
1408 case eStateStepping:
1409 // We always suppress multiple runnings with no PUBLIC stop in between.
1410 return_value = false;
1411 break;
1412 default:
1413 // TODO: make this work correctly. For now always report
1414 // run if we aren't running so we don't miss any runnning
1415 // events. If I run the lldb/test/thread/a.out file and
1416 // break at main.cpp:58, run and hit the breakpoints on
1417 // multiple threads, then somehow during the stepping over
1418 // of all breakpoints no run gets reported.
1419 return_value = true;
1420
1421 // This is a transition from stop to run.
1422 switch (m_thread_list.ShouldReportRun (event_ptr))
1423 {
1424 case eVoteYes:
1425 case eVoteNoOpinion:
1426 return_value = true;
1427 break;
1428 case eVoteNo:
1429 return_value = false;
1430 break;
1431 }
1432 break;
1433 }
1434 break;
1435 case eStateStopped:
1436 case eStateCrashed:
1437 case eStateSuspended:
1438 {
1439 // We've stopped. First see if we're going to restart the target.
1440 // If we are going to stop, then we always broadcast the event.
1441 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00001442 // If no thread has an opinion, we don't report it.
Chris Lattner24943d22010-06-08 16:52:24 +00001443 if (state != eStateInvalid)
1444 {
1445
1446 RefreshStateAfterStop ();
1447
1448 if (m_thread_list.ShouldStop (event_ptr) == false)
1449 {
1450 switch (m_thread_list.ShouldReportStop (event_ptr))
1451 {
1452 case eVoteYes:
1453 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001454 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001455 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001456 case eVoteNo:
1457 return_value = false;
1458 break;
1459 }
1460
1461 if (log)
1462 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state));
1463 Resume ();
1464 }
1465 else
1466 {
1467 return_value = true;
1468 SynchronouslyNotifyStateChanged (state);
1469 }
1470 }
1471 }
1472 }
1473
1474 if (log)
1475 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1476 return return_value;
1477}
1478
1479//------------------------------------------------------------------
1480// Thread Queries
1481//------------------------------------------------------------------
1482
1483ThreadList &
1484Process::GetThreadList ()
1485{
1486 return m_thread_list;
1487}
1488
1489const ThreadList &
1490Process::GetThreadList () const
1491{
1492 return m_thread_list;
1493}
1494
1495
1496bool
1497Process::StartPrivateStateThread ()
1498{
1499 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1500
1501 if (log)
1502 log->Printf ("Process::%s ( )", __FUNCTION__);
1503
1504 // Create a thread that watches our internal state and controls which
1505 // events make it to clients (into the DCProcess event queue).
1506 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1507 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1508}
1509
1510void
1511Process::PausePrivateStateThread ()
1512{
1513 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1514}
1515
1516void
1517Process::ResumePrivateStateThread ()
1518{
1519 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1520}
1521
1522void
1523Process::StopPrivateStateThread ()
1524{
1525 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1526}
1527
1528void
1529Process::ControlPrivateStateThread (uint32_t signal)
1530{
1531 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1532
1533 assert (signal == eBroadcastInternalStateControlStop ||
1534 signal == eBroadcastInternalStateControlPause ||
1535 signal == eBroadcastInternalStateControlResume);
1536
1537 if (log)
1538 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1539
1540 // Signal the private state thread
1541 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1542 {
1543 TimeValue timeout_time;
1544 bool timed_out;
1545
1546 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1547
1548 timeout_time = TimeValue::Now();
1549 timeout_time.OffsetWithSeconds(2);
1550 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1551 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1552
1553 if (signal == eBroadcastInternalStateControlStop)
1554 {
1555 if (timed_out)
1556 Host::ThreadCancel (m_private_state_thread, NULL);
1557
1558 thread_result_t result = NULL;
1559 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00001560 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001561 }
1562 }
1563}
1564
1565void
1566Process::HandlePrivateEvent (EventSP &event_sp)
1567{
1568 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1569 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1570 // See if we should broadcast this state to external clients?
1571 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1572 if (log)
1573 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1574
1575 if (should_broadcast)
1576 {
1577 if (log)
1578 {
1579 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1580 }
1581 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1582 BroadcastEvent (event_sp);
1583 }
1584 else
1585 {
1586 if (log)
1587 {
1588 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1589 }
1590 }
1591}
1592
1593void *
1594Process::PrivateStateThread (void *arg)
1595{
1596 Process *proc = static_cast<Process*> (arg);
1597 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001598 return result;
1599}
1600
1601void *
1602Process::RunPrivateStateThread ()
1603{
1604 bool control_only = false;
1605 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1606
1607 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1608 if (log)
1609 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1610
1611 bool exit_now = false;
1612 while (!exit_now)
1613 {
1614 EventSP event_sp;
1615 WaitForEventsPrivate (NULL, event_sp, control_only);
1616 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1617 {
1618 switch (event_sp->GetType())
1619 {
1620 case eBroadcastInternalStateControlStop:
1621 exit_now = true;
1622 continue; // Go to next loop iteration so we exit without
1623 break; // doing any internal state managment below
1624
1625 case eBroadcastInternalStateControlPause:
1626 control_only = true;
1627 break;
1628
1629 case eBroadcastInternalStateControlResume:
1630 control_only = false;
1631 break;
1632 }
1633 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1634 }
1635
1636
1637 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1638
1639 if (internal_state != eStateInvalid)
1640 {
1641 HandlePrivateEvent (event_sp);
1642 }
1643
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001644 if (internal_state == eStateInvalid ||
1645 internal_state == eStateExited ||
1646 internal_state == eStateDetached )
Chris Lattner24943d22010-06-08 16:52:24 +00001647 break;
1648 }
1649
Caroline Tice926060e2010-10-29 21:48:37 +00001650 // Verify log is still enabled before attempting to write to it...
1651 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001652 if (log)
1653 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1654
Greg Clayton8b4c16e2010-08-19 21:50:06 +00001655 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001656 return NULL;
1657}
1658
Chris Lattner24943d22010-06-08 16:52:24 +00001659//------------------------------------------------------------------
1660// Process Event Data
1661//------------------------------------------------------------------
1662
1663Process::ProcessEventData::ProcessEventData () :
1664 EventData (),
1665 m_process_sp (),
1666 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001667 m_restarted (false),
1668 m_update_state (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001669{
1670}
1671
1672Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1673 EventData (),
1674 m_process_sp (process_sp),
1675 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001676 m_restarted (false),
1677 m_update_state (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001678{
1679}
1680
1681Process::ProcessEventData::~ProcessEventData()
1682{
1683}
1684
1685const ConstString &
1686Process::ProcessEventData::GetFlavorString ()
1687{
1688 static ConstString g_flavor ("Process::ProcessEventData");
1689 return g_flavor;
1690}
1691
1692const ConstString &
1693Process::ProcessEventData::GetFlavor () const
1694{
1695 return ProcessEventData::GetFlavorString ();
1696}
1697
1698const ProcessSP &
1699Process::ProcessEventData::GetProcessSP () const
1700{
1701 return m_process_sp;
1702}
1703
1704StateType
1705Process::ProcessEventData::GetState () const
1706{
1707 return m_state;
1708}
1709
1710bool
1711Process::ProcessEventData::GetRestarted () const
1712{
1713 return m_restarted;
1714}
1715
1716void
1717Process::ProcessEventData::SetRestarted (bool new_value)
1718{
1719 m_restarted = new_value;
1720}
1721
1722void
1723Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1724{
1725 // This function gets called twice for each event, once when the event gets pulled
1726 // off of the private process event queue, and once when it gets pulled off of
1727 // the public event queue. m_update_state is used to distinguish these
1728 // two cases; it is false when we're just pulling it off for private handling,
1729 // and we don't want to do the breakpoint command handling then.
1730
1731 if (!m_update_state)
1732 return;
1733
1734 m_process_sp->SetPublicState (m_state);
1735
1736 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1737 if (m_state == eStateStopped && ! m_restarted)
1738 {
1739 int num_threads = m_process_sp->GetThreadList().GetSize();
1740 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00001741
Chris Lattner24943d22010-06-08 16:52:24 +00001742 for (idx = 0; idx < num_threads; ++idx)
1743 {
1744 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1745
Jim Ingham6297a3a2010-10-20 00:39:53 +00001746 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
1747 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001748 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00001749 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00001750 }
1751 }
Greg Clayton643ee732010-08-04 01:40:35 +00001752
Jim Ingham6fb8baa2010-08-10 00:59:59 +00001753 // The stop action might restart the target. If it does, then we want to mark that in the
1754 // event so that whoever is receiving it will know to wait for the running event and reflect
1755 // that state appropriately.
1756
Chris Lattner24943d22010-06-08 16:52:24 +00001757 if (m_process_sp->GetPrivateState() == eStateRunning)
1758 SetRestarted(true);
1759 }
1760}
1761
1762void
1763Process::ProcessEventData::Dump (Stream *s) const
1764{
1765 if (m_process_sp)
1766 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1767
1768 s->Printf("state = %s", StateAsCString(GetState()));;
1769}
1770
1771const Process::ProcessEventData *
1772Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1773{
1774 if (event_ptr)
1775 {
1776 const EventData *event_data = event_ptr->GetData();
1777 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1778 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1779 }
1780 return NULL;
1781}
1782
1783ProcessSP
1784Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
1785{
1786 ProcessSP process_sp;
1787 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1788 if (data)
1789 process_sp = data->GetProcessSP();
1790 return process_sp;
1791}
1792
1793StateType
1794Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
1795{
1796 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1797 if (data == NULL)
1798 return eStateInvalid;
1799 else
1800 return data->GetState();
1801}
1802
1803bool
1804Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
1805{
1806 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1807 if (data == NULL)
1808 return false;
1809 else
1810 return data->GetRestarted();
1811}
1812
1813void
1814Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
1815{
1816 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1817 if (data != NULL)
1818 data->SetRestarted(new_value);
1819}
1820
1821bool
1822Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
1823{
1824 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1825 if (data)
1826 {
1827 data->SetUpdateStateOnRemoval();
1828 return true;
1829 }
1830 return false;
1831}
1832
1833void
1834Process::ProcessEventData::SetUpdateStateOnRemoval()
1835{
1836 m_update_state = true;
1837}
1838
1839Target *
1840Process::CalculateTarget ()
1841{
1842 return &m_target;
1843}
1844
1845Process *
1846Process::CalculateProcess ()
1847{
1848 return this;
1849}
1850
1851Thread *
1852Process::CalculateThread ()
1853{
1854 return NULL;
1855}
1856
1857StackFrame *
1858Process::CalculateStackFrame ()
1859{
1860 return NULL;
1861}
1862
1863void
Greg Claytona830adb2010-10-04 01:05:56 +00001864Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00001865{
1866 exe_ctx.target = &m_target;
1867 exe_ctx.process = this;
1868 exe_ctx.thread = NULL;
1869 exe_ctx.frame = NULL;
1870}
1871
1872lldb::ProcessSP
1873Process::GetSP ()
1874{
1875 return GetTarget().GetProcessSP();
1876}
1877
Sean Callanana48fe162010-08-11 03:57:18 +00001878ClangPersistentVariables &
1879Process::GetPersistentVariables()
1880{
1881 return m_persistent_vars;
1882}
1883
Jim Ingham7508e732010-08-09 23:31:02 +00001884uint32_t
1885Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
1886{
1887 return 0;
1888}
1889
1890ArchSpec
1891Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
1892{
1893 return Host::GetArchSpecForExistingProcess (pid);
1894}
1895
1896ArchSpec
1897Process::GetArchSpecForExistingProcess (const char *process_name)
1898{
1899 return Host::GetArchSpecForExistingProcess (process_name);
1900}
1901
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001902lldb::UserSettingsControllerSP
1903Process::GetSettingsController (bool finish)
1904{
Greg Claytond0a5a232010-09-19 02:33:57 +00001905 static UserSettingsControllerSP g_settings_controller (new SettingsController);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001906 static bool initialized = false;
1907
1908 if (!initialized)
1909 {
Jim Ingham7ac83bd2010-09-07 20:27:09 +00001910 initialized = UserSettingsController::InitializeSettingsController (g_settings_controller,
Greg Claytond0a5a232010-09-19 02:33:57 +00001911 Process::SettingsController::global_settings_table,
1912 Process::SettingsController::instance_settings_table);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001913 }
1914
1915 if (finish)
1916 {
Jim Ingham7ac83bd2010-09-07 20:27:09 +00001917 UserSettingsController::FinalizeSettingsController (g_settings_controller);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001918 g_settings_controller.reset();
Jim Ingham7ac83bd2010-09-07 20:27:09 +00001919 initialized = false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001920 }
1921
1922 return g_settings_controller;
1923}
1924
Caroline Tice1ebef442010-09-27 00:30:10 +00001925void
1926Process::UpdateInstanceName ()
1927{
1928 ModuleSP module_sp = GetTarget().GetExecutableModule();
1929 if (module_sp)
1930 {
1931 StreamString sstr;
1932 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
1933
1934 Process::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
1935 sstr.GetData());
1936 }
1937}
1938
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001939//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00001940// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001941//--------------------------------------------------------------
1942
Greg Claytond0a5a232010-09-19 02:33:57 +00001943Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00001944 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001945{
Caroline Tice004afcb2010-09-08 17:48:55 +00001946 m_default_settings.reset (new ProcessInstanceSettings (*this, false,
1947 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001948}
1949
Greg Claytond0a5a232010-09-19 02:33:57 +00001950Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001951{
1952}
1953
1954lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00001955Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001956{
Caroline Tice004afcb2010-09-08 17:48:55 +00001957 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*(Process::GetSettingsController().get()),
1958 false, instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001959 lldb::InstanceSettingsSP new_settings_sp (new_settings);
1960 return new_settings_sp;
1961}
1962
1963//--------------------------------------------------------------
1964// class ProcessInstanceSettings
1965//--------------------------------------------------------------
1966
Caroline Tice004afcb2010-09-08 17:48:55 +00001967ProcessInstanceSettings::ProcessInstanceSettings (UserSettingsController &owner, bool live_instance,
1968 const char *name) :
Caroline Tice75b11a32010-09-16 19:05:55 +00001969 InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001970 m_run_args (),
1971 m_env_vars (),
1972 m_input_path (),
1973 m_output_path (),
1974 m_error_path (),
1975 m_plugin (),
1976 m_disable_aslr (true)
1977{
Caroline Tice396704b2010-09-09 18:26:37 +00001978 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1979 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
1980 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00001981 // This is true for CreateInstanceName() too.
1982
1983 if (GetInstanceName () == InstanceSettings::InvalidName())
1984 {
1985 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1986 m_owner.RegisterInstanceSettings (this);
1987 }
Caroline Tice396704b2010-09-09 18:26:37 +00001988
1989 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001990 {
1991 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1992 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00001993 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00001994 }
1995}
1996
1997ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
1998 InstanceSettings (*(Process::GetSettingsController().get()), CreateInstanceName().AsCString()),
1999 m_run_args (rhs.m_run_args),
2000 m_env_vars (rhs.m_env_vars),
2001 m_input_path (rhs.m_input_path),
2002 m_output_path (rhs.m_output_path),
2003 m_error_path (rhs.m_error_path),
2004 m_plugin (rhs.m_plugin),
2005 m_disable_aslr (rhs.m_disable_aslr)
2006{
2007 if (m_instance_name != InstanceSettings::GetDefaultName())
2008 {
2009 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2010 CopyInstanceSettings (pending_settings,false);
2011 m_owner.RemovePendingSettings (m_instance_name);
2012 }
2013}
2014
2015ProcessInstanceSettings::~ProcessInstanceSettings ()
2016{
2017}
2018
2019ProcessInstanceSettings&
2020ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2021{
2022 if (this != &rhs)
2023 {
2024 m_run_args = rhs.m_run_args;
2025 m_env_vars = rhs.m_env_vars;
2026 m_input_path = rhs.m_input_path;
2027 m_output_path = rhs.m_output_path;
2028 m_error_path = rhs.m_error_path;
2029 m_plugin = rhs.m_plugin;
2030 m_disable_aslr = rhs.m_disable_aslr;
2031 }
2032
2033 return *this;
2034}
2035
2036
2037void
2038ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2039 const char *index_value,
2040 const char *value,
2041 const ConstString &instance_name,
2042 const SettingEntry &entry,
2043 lldb::VarSetOperationType op,
2044 Error &err,
2045 bool pending)
2046{
2047 if (var_name == RunArgsVarName())
2048 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2049 else if (var_name == EnvVarsVarName())
2050 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2051 else if (var_name == InputPathVarName())
2052 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2053 else if (var_name == OutputPathVarName())
2054 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2055 else if (var_name == ErrorPathVarName())
2056 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2057 else if (var_name == PluginVarName())
2058 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
2059 else if (var_name == DisableASLRVarName())
2060 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
2061}
2062
2063void
2064ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2065 bool pending)
2066{
2067 if (new_settings.get() == NULL)
2068 return;
2069
2070 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2071
2072 m_run_args = new_process_settings->m_run_args;
2073 m_env_vars = new_process_settings->m_env_vars;
2074 m_input_path = new_process_settings->m_input_path;
2075 m_output_path = new_process_settings->m_output_path;
2076 m_error_path = new_process_settings->m_error_path;
2077 m_plugin = new_process_settings->m_plugin;
2078 m_disable_aslr = new_process_settings->m_disable_aslr;
2079}
2080
Caroline Ticebcb5b452010-09-20 21:37:42 +00002081bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002082ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2083 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00002084 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00002085 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002086{
2087 if (var_name == RunArgsVarName())
2088 {
2089 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00002090 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002091 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2092 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00002093 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002094 }
2095 else if (var_name == EnvVarsVarName())
2096 {
2097 if (m_env_vars.size() > 0)
2098 {
2099 std::map<std::string, std::string>::iterator pos;
2100 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2101 {
2102 StreamString value_str;
2103 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2104 value.AppendString (value_str.GetData());
2105 }
2106 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002107 }
2108 else if (var_name == InputPathVarName())
2109 {
2110 value.AppendString (m_input_path.c_str());
2111 }
2112 else if (var_name == OutputPathVarName())
2113 {
2114 value.AppendString (m_output_path.c_str());
2115 }
2116 else if (var_name == ErrorPathVarName())
2117 {
2118 value.AppendString (m_error_path.c_str());
2119 }
2120 else if (var_name == PluginVarName())
2121 {
2122 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2123 }
2124 else if (var_name == DisableASLRVarName())
2125 {
2126 if (m_disable_aslr)
2127 value.AppendString ("true");
2128 else
2129 value.AppendString ("false");
2130 }
2131 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00002132 {
2133 if (err)
2134 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2135 return false;
2136 }
2137 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002138}
2139
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002140const ConstString
2141ProcessInstanceSettings::CreateInstanceName ()
2142{
2143 static int instance_count = 1;
2144 StreamString sstr;
2145
2146 sstr.Printf ("process_%d", instance_count);
2147 ++instance_count;
2148
2149 const ConstString ret_val (sstr.GetData());
2150 return ret_val;
2151}
2152
2153const ConstString &
2154ProcessInstanceSettings::RunArgsVarName ()
2155{
2156 static ConstString run_args_var_name ("run-args");
2157
2158 return run_args_var_name;
2159}
2160
2161const ConstString &
2162ProcessInstanceSettings::EnvVarsVarName ()
2163{
2164 static ConstString env_vars_var_name ("env-vars");
2165
2166 return env_vars_var_name;
2167}
2168
2169const ConstString &
2170ProcessInstanceSettings::InputPathVarName ()
2171{
2172 static ConstString input_path_var_name ("input-path");
2173
2174 return input_path_var_name;
2175}
2176
2177const ConstString &
2178ProcessInstanceSettings::OutputPathVarName ()
2179{
Caroline Tice87097232010-09-07 18:35:40 +00002180 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002181
2182 return output_path_var_name;
2183}
2184
2185const ConstString &
2186ProcessInstanceSettings::ErrorPathVarName ()
2187{
Caroline Tice87097232010-09-07 18:35:40 +00002188 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002189
2190 return error_path_var_name;
2191}
2192
2193const ConstString &
2194ProcessInstanceSettings::PluginVarName ()
2195{
2196 static ConstString plugin_var_name ("plugin");
2197
2198 return plugin_var_name;
2199}
2200
2201
2202const ConstString &
2203ProcessInstanceSettings::DisableASLRVarName ()
2204{
2205 static ConstString disable_aslr_var_name ("disable-aslr");
2206
2207 return disable_aslr_var_name;
2208}
2209
2210
2211//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002212// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002213//--------------------------------------------------
2214
2215SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002216Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002217{
2218 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2219 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2220};
2221
2222
2223lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00002224Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002225{
Caroline Ticef2c330d2010-09-09 18:01:59 +00002226 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2227 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2228 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002229};
2230
2231SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002232Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002233{
2234 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2235 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2236 { "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." },
2237 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2238 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2239 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2240 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
2241 { "disable-aslr", eSetVarTypeBool, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
2242 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2243};
2244
2245
Jim Ingham7508e732010-08-09 23:31:02 +00002246