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