blob: b6537276ffacba9620c80e556a741149cb874096 [file] [log] [blame]
Chris Lattner30fdc8d2010-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 Tice3df9a8d2010-09-04 00:03:46 +000021#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Host/Host.h"
23#include "lldb/Target/ABI.h"
Jim Ingham22777012010-09-23 02:01:19 +000024#include "lldb/Target/LanguageRuntime.h"
25#include "lldb/Target/CPPLanguageRuntime.h"
26#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000028#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Claytonc982c762010-07-09 20:39:50 +000053 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054 {
Greg Claytonc982c762010-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 Lattner30fdc8d2010-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 Tice3df9a8d2010-09-04 00:03:46 +000070 ProcessInstanceSettings (*(Process::GetSettingsController().get())),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071 m_target (target),
Chris Lattner30fdc8d2010-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 Ingham36f3b362010-10-14 23:45:03 +000085 m_persistent_vars(),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086 m_listener(listener),
Jim Ingham36f3b362010-10-14 23:45:03 +000087 m_unix_signals ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +000088{
Caroline Tice1559a462010-09-27 00:30:10 +000089 UpdateInstanceName();
90
Chris Lattner30fdc8d2010-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 Clayton05faeb72010-10-07 04:19:01 +0000201 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202 while (state != eStateInvalid)
203 {
Greg Clayton05faeb72010-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 Lattner30fdc8d2010-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 Ingham30f9b212010-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 Lattner30fdc8d2010-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;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000246 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
247 this,
248 eBroadcastBitStateChanged,
249 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000250 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
251
Caroline Tice20ad3c42010-10-29 21:48:37 +0000252 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253 if (log)
254 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
255 __FUNCTION__,
256 timeout,
257 StateAsCString(state));
258 return state;
259}
260
261Event *
262Process::PeekAtStateChangedEvents ()
263{
264 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
265
266 if (log)
267 log->Printf ("Process::%s...", __FUNCTION__);
268
269 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000270 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
271 eBroadcastBitStateChanged);
Caroline Tice20ad3c42010-10-29 21:48:37 +0000272 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273 if (log)
274 {
275 if (event_ptr)
276 {
277 log->Printf ("Process::%s (event_ptr) => %s",
278 __FUNCTION__,
279 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
280 }
281 else
282 {
283 log->Printf ("Process::%s no events found",
284 __FUNCTION__);
285 }
286 }
287 return event_ptr;
288}
289
290StateType
291Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
292{
293 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
294
295 if (log)
296 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
297
298 StateType state = eStateInvalid;
299 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
300 &m_private_state_broadcaster,
301 eBroadcastBitStateChanged,
302 event_sp))
303 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
304
305 // This is a bit of a hack, but when we wait here we could very well return
306 // to the command-line, and that could disable the log, which would render the
307 // log we got above invalid.
308 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
309 if (log)
310 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
311 return state;
312}
313
314bool
315Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
316{
317 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
318
319 if (log)
320 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
321
322 if (control_only)
323 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
324 else
325 return m_private_state_listener.WaitForEvent(timeout, event_sp);
326}
327
328bool
329Process::IsRunning () const
330{
331 return StateIsRunningState (m_public_state.GetValue());
332}
333
334int
335Process::GetExitStatus ()
336{
337 if (m_public_state.GetValue() == eStateExited)
338 return m_exit_status;
339 return -1;
340}
341
342const char *
343Process::GetExitDescription ()
344{
345 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
346 return m_exit_string.c_str();
347 return NULL;
348}
349
350void
351Process::SetExitStatus (int status, const char *cstr)
352{
353 m_exit_status = status;
354 if (cstr)
355 m_exit_string = cstr;
356 else
357 m_exit_string.clear();
358
359 SetPrivateState (eStateExited);
360}
361
362// This static callback can be used to watch for local child processes on
363// the current host. The the child process exits, the process will be
364// found in the global target list (we want to be completely sure that the
365// lldb_private::Process doesn't go away before we can deliver the signal.
366bool
367Process::SetProcessExitStatus
368(
369 void *callback_baton,
370 lldb::pid_t pid,
371 int signo, // Zero for no signal
372 int exit_status // Exit value of process if signal is zero
373)
374{
375 if (signo == 0 || exit_status)
376 {
Greg Clayton66111032010-06-23 01:19:29 +0000377 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378 if (target_sp)
379 {
380 ProcessSP process_sp (target_sp->GetProcessSP());
381 if (process_sp)
382 {
383 const char *signal_cstr = NULL;
384 if (signo)
385 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
386
387 process_sp->SetExitStatus (exit_status, signal_cstr);
388 }
389 }
390 return true;
391 }
392 return false;
393}
394
395
396uint32_t
397Process::GetNextThreadIndexID ()
398{
399 return ++m_thread_index_id;
400}
401
402StateType
403Process::GetState()
404{
405 // If any other threads access this we will need a mutex for it
406 return m_public_state.GetValue ();
407}
408
409void
410Process::SetPublicState (StateType new_state)
411{
412 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
413 if (log)
414 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
415 m_public_state.SetValue (new_state);
416}
417
418StateType
419Process::GetPrivateState ()
420{
421 return m_private_state.GetValue();
422}
423
424void
425Process::SetPrivateState (StateType new_state)
426{
427 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
428 bool state_changed = false;
429
430 if (log)
431 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
432
433 Mutex::Locker locker(m_private_state.GetMutex());
434
435 const StateType old_state = m_private_state.GetValueNoLock ();
436 state_changed = old_state != new_state;
437 if (state_changed)
438 {
439 m_private_state.SetValueNoLock (new_state);
440 if (StateIsStoppedState(new_state))
441 {
442 m_stop_id++;
443 if (log)
444 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
445 }
446 // Use our target to get a shared pointer to ourselves...
447 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
448 }
449 else
450 {
451 if (log)
452 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
453 }
454}
455
456
457uint32_t
458Process::GetStopID() const
459{
460 return m_stop_id;
461}
462
463addr_t
464Process::GetImageInfoAddress()
465{
466 return LLDB_INVALID_ADDRESS;
467}
468
469DynamicLoader *
470Process::GetDynamicLoader()
471{
472 return NULL;
473}
474
475const ABI *
476Process::GetABI()
477{
478 ConstString& triple = m_target_triple;
479
480 if (triple.IsEmpty())
481 return NULL;
482
483 if (m_abi_sp.get() == NULL)
484 {
485 m_abi_sp.reset(ABI::FindPlugin(triple));
486 }
487
488 return m_abi_sp.get();
489}
490
Jim Ingham22777012010-09-23 02:01:19 +0000491LanguageRuntime *
492Process::GetLanguageRuntime(lldb::LanguageType language)
493{
494 LanguageRuntimeCollection::iterator pos;
495 pos = m_language_runtimes.find (language);
496 if (pos == m_language_runtimes.end())
497 {
498 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
499
500 m_language_runtimes[language]
501 = runtime;
502 return runtime.get();
503 }
504 else
505 return (*pos).second.get();
506}
507
508CPPLanguageRuntime *
509Process::GetCPPLanguageRuntime ()
510{
511 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
512 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
513 return static_cast<CPPLanguageRuntime *> (runtime);
514 return NULL;
515}
516
517ObjCLanguageRuntime *
518Process::GetObjCLanguageRuntime ()
519{
520 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
521 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
522 return static_cast<ObjCLanguageRuntime *> (runtime);
523 return NULL;
524}
525
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526BreakpointSiteList &
527Process::GetBreakpointSiteList()
528{
529 return m_breakpoint_site_list;
530}
531
532const BreakpointSiteList &
533Process::GetBreakpointSiteList() const
534{
535 return m_breakpoint_site_list;
536}
537
538
539void
540Process::DisableAllBreakpointSites ()
541{
542 m_breakpoint_site_list.SetEnabledForAll (false);
543}
544
545Error
546Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
547{
548 Error error (DisableBreakpointSiteByID (break_id));
549
550 if (error.Success())
551 m_breakpoint_site_list.Remove(break_id);
552
553 return error;
554}
555
556Error
557Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
558{
559 Error error;
560 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
561 if (bp_site_sp)
562 {
563 if (bp_site_sp->IsEnabled())
564 error = DisableBreakpoint (bp_site_sp.get());
565 }
566 else
567 {
568 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
569 }
570
571 return error;
572}
573
574Error
575Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
576{
577 Error error;
578 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
579 if (bp_site_sp)
580 {
581 if (!bp_site_sp->IsEnabled())
582 error = EnableBreakpoint (bp_site_sp.get());
583 }
584 else
585 {
586 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
587 }
588 return error;
589}
590
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000591lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
593{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000594 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 if (load_addr != LLDB_INVALID_ADDRESS)
596 {
597 BreakpointSiteSP bp_site_sp;
598
599 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
600 // create a new breakpoint site and add it.
601
602 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
603
604 if (bp_site_sp)
605 {
606 bp_site_sp->AddOwner (owner);
607 owner->SetBreakpointSite (bp_site_sp);
608 return bp_site_sp->GetID();
609 }
610 else
611 {
612 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
613 if (bp_site_sp)
614 {
615 if (EnableBreakpoint (bp_site_sp.get()).Success())
616 {
617 owner->SetBreakpointSite (bp_site_sp);
618 return m_breakpoint_site_list.Add (bp_site_sp);
619 }
620 }
621 }
622 }
623 // We failed to enable the breakpoint
624 return LLDB_INVALID_BREAK_ID;
625
626}
627
628void
629Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
630{
631 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
632 if (num_owners == 0)
633 {
634 DisableBreakpoint(bp_site_sp.get());
635 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
636 }
637}
638
639
640size_t
641Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
642{
643 size_t bytes_removed = 0;
644 addr_t intersect_addr;
645 size_t intersect_size;
646 size_t opcode_offset;
647 size_t idx;
648 BreakpointSiteSP bp;
649
650 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
651 {
652 if (bp->GetType() == BreakpointSite::eSoftware)
653 {
654 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
655 {
656 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
657 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
658 assert(opcode_offset + intersect_size <= bp->GetByteSize());
659 size_t buf_offset = intersect_addr - bp_addr;
660 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
661 }
662 }
663 }
664 return bytes_removed;
665}
666
667
668Error
669Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
670{
671 Error error;
672 assert (bp_site != NULL);
673 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
674 const addr_t bp_addr = bp_site->GetLoadAddress();
675 if (log)
676 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
677 if (bp_site->IsEnabled())
678 {
679 if (log)
680 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
681 return error;
682 }
683
684 if (bp_addr == LLDB_INVALID_ADDRESS)
685 {
686 error.SetErrorString("BreakpointSite contains an invalid load address.");
687 return error;
688 }
689 // Ask the lldb::Process subclass to fill in the correct software breakpoint
690 // trap for the breakpoint site
691 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
692
693 if (bp_opcode_size == 0)
694 {
695 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
696 }
697 else
698 {
699 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
700
701 if (bp_opcode_bytes == NULL)
702 {
703 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
704 return error;
705 }
706
707 // Save the original opcode by reading it
708 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
709 {
710 // Write a software breakpoint in place of the original opcode
711 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
712 {
713 uint8_t verify_bp_opcode_bytes[64];
714 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
715 {
716 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
717 {
718 bp_site->SetEnabled(true);
719 bp_site->SetType (BreakpointSite::eSoftware);
720 if (log)
721 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
722 bp_site->GetID(),
723 (uint64_t)bp_addr);
724 }
725 else
726 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
727 }
728 else
729 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
730 }
731 else
732 error.SetErrorString("Unable to write breakpoint trap to memory.");
733 }
734 else
735 error.SetErrorString("Unable to read memory at breakpoint address.");
736 }
737 if (log)
738 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
739 bp_site->GetID(),
740 (uint64_t)bp_addr,
741 error.AsCString());
742 return error;
743}
744
745Error
746Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
747{
748 Error error;
749 assert (bp_site != NULL);
750 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
751 addr_t bp_addr = bp_site->GetLoadAddress();
752 lldb::user_id_t breakID = bp_site->GetID();
753 if (log)
754 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
755
756 if (bp_site->IsHardware())
757 {
758 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
759 }
760 else if (bp_site->IsEnabled())
761 {
762 const size_t break_op_size = bp_site->GetByteSize();
763 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
764 if (break_op_size > 0)
765 {
766 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +0000767 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000768 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 bool break_op_found = false;
770
771 // Read the breakpoint opcode
772 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
773 {
774 bool verify = false;
775 // Make sure we have the a breakpoint opcode exists at this address
776 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
777 {
778 break_op_found = true;
779 // We found a valid breakpoint opcode at this address, now restore
780 // the saved opcode.
781 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
782 {
783 verify = true;
784 }
785 else
786 error.SetErrorString("Memory write failed when restoring original opcode.");
787 }
788 else
789 {
790 error.SetErrorString("Original breakpoint trap is no longer in memory.");
791 // Set verify to true and so we can check if the original opcode has already been restored
792 verify = true;
793 }
794
795 if (verify)
796 {
Greg Claytonc982c762010-07-09 20:39:50 +0000797 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000798 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 // Verify that our original opcode made it back to the inferior
800 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
801 {
802 // compare the memory we just read with the original opcode
803 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
804 {
805 // SUCCESS
806 bp_site->SetEnabled(false);
807 if (log)
808 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
809 return error;
810 }
811 else
812 {
813 if (break_op_found)
814 error.SetErrorString("Failed to restore original opcode.");
815 }
816 }
817 else
818 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
819 }
820 }
821 else
822 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
823 }
824 }
825 else
826 {
827 if (log)
828 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
829 return error;
830 }
831
832 if (log)
833 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
834 bp_site->GetID(),
835 (uint64_t)bp_addr,
836 error.AsCString());
837 return error;
838
839}
840
841
842size_t
843Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
844{
845 if (buf == NULL || size == 0)
846 return 0;
847
848 size_t bytes_read = 0;
849 uint8_t *bytes = (uint8_t *)buf;
850
851 while (bytes_read < size)
852 {
853 const size_t curr_size = size - bytes_read;
854 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
855 bytes + bytes_read,
856 curr_size,
857 error);
858 bytes_read += curr_bytes_read;
859 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
860 break;
861 }
862
863 // Replace any software breakpoint opcodes that fall into this range back
864 // into "buf" before we return
865 if (bytes_read > 0)
866 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
867 return bytes_read;
868}
869
870size_t
871Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
872{
873 size_t bytes_written = 0;
874 const uint8_t *bytes = (const uint8_t *)buf;
875
876 while (bytes_written < size)
877 {
878 const size_t curr_size = size - bytes_written;
879 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
880 bytes + bytes_written,
881 curr_size,
882 error);
883 bytes_written += curr_bytes_written;
884 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
885 break;
886 }
887 return bytes_written;
888}
889
890size_t
891Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
892{
893 if (buf == NULL || size == 0)
894 return 0;
895 // We need to write any data that would go where any current software traps
896 // (enabled software breakpoints) any software traps (breakpoints) that we
897 // may have placed in our tasks memory.
898
899 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
900 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
901
902 if (iter == end || iter->second->GetLoadAddress() > addr + size)
903 return DoWriteMemory(addr, buf, size, error);
904
905 BreakpointSiteList::collection::const_iterator pos;
906 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +0000907 addr_t intersect_addr = 0;
908 size_t intersect_size = 0;
909 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 const uint8_t *ubuf = (const uint8_t *)buf;
911
912 for (pos = iter; pos != end; ++pos)
913 {
914 BreakpointSiteSP bp;
915 bp = pos->second;
916
917 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
918 assert(addr <= intersect_addr && intersect_addr < addr + size);
919 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
920 assert(opcode_offset + intersect_size <= bp->GetByteSize());
921
922 // Check for bytes before this breakpoint
923 const addr_t curr_addr = addr + bytes_written;
924 if (intersect_addr > curr_addr)
925 {
926 // There are some bytes before this breakpoint that we need to
927 // just write to memory
928 size_t curr_size = intersect_addr - curr_addr;
929 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
930 ubuf + bytes_written,
931 curr_size,
932 error);
933 bytes_written += curr_bytes_written;
934 if (curr_bytes_written != curr_size)
935 {
936 // We weren't able to write all of the requested bytes, we
937 // are done looping and will return the number of bytes that
938 // we have written so far.
939 break;
940 }
941 }
942
943 // Now write any bytes that would cover up any software breakpoints
944 // directly into the breakpoint opcode buffer
945 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
946 bytes_written += intersect_size;
947 }
948
949 // Write any remaining bytes after the last breakpoint if we have any left
950 if (bytes_written < size)
951 bytes_written += WriteMemoryPrivate (addr + bytes_written,
952 ubuf + bytes_written,
953 size - bytes_written,
954 error);
955
956 return bytes_written;
957}
958
959addr_t
960Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
961{
962 // Fixme: we should track the blocks we've allocated, and clean them up...
963 // We could even do our own allocator here if that ends up being more efficient.
964 return DoAllocateMemory (size, permissions, error);
965}
966
967Error
968Process::DeallocateMemory (addr_t ptr)
969{
970 return DoDeallocateMemory (ptr);
971}
972
973
974Error
975Process::EnableWatchpoint (WatchpointLocation *watchpoint)
976{
977 Error error;
978 error.SetErrorString("watchpoints are not supported");
979 return error;
980}
981
982Error
983Process::DisableWatchpoint (WatchpointLocation *watchpoint)
984{
985 Error error;
986 error.SetErrorString("watchpoints are not supported");
987 return error;
988}
989
990StateType
991Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
992{
993 StateType state;
994 // Now wait for the process to launch and return control to us, and then
995 // call DidLaunch:
996 while (1)
997 {
998 // FIXME: Might want to put a timeout in here:
999 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1000 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1001 break;
1002 else
1003 HandlePrivateEvent (event_sp);
1004 }
1005 return state;
1006}
1007
1008Error
1009Process::Launch
1010(
1011 char const *argv[],
1012 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001013 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 const char *stdin_path,
1015 const char *stdout_path,
1016 const char *stderr_path
1017)
1018{
1019 Error error;
1020 m_target_triple.Clear();
1021 m_abi_sp.reset();
1022
1023 Module *exe_module = m_target.GetExecutableModule().get();
1024 if (exe_module)
1025 {
1026 char exec_file_path[PATH_MAX];
1027 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1028 if (exe_module->GetFileSpec().Exists())
1029 {
1030 error = WillLaunch (exe_module);
1031 if (error.Success())
1032 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001033 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 // The args coming in should not contain the application name, the
1035 // lldb_private::Process class will add this in case the executable
1036 // gets resolved to a different file than was given on the command
1037 // line (like when an applicaiton bundle is specified and will
1038 // resolve to the contained exectuable file, or the file given was
1039 // a symlink or other file system link that resolves to a different
1040 // file).
1041
1042 // Get the resolved exectuable path
1043
1044 // Make a new argument vector
1045 std::vector<const char *> exec_path_plus_argv;
1046 // Append the resolved executable path
1047 exec_path_plus_argv.push_back (exec_file_path);
1048
1049 // Push all args if there are any
1050 if (argv)
1051 {
1052 for (int i = 0; argv[i]; ++i)
1053 exec_path_plus_argv.push_back(argv[i]);
1054 }
1055
1056 // Push a NULL to terminate the args.
1057 exec_path_plus_argv.push_back(NULL);
1058
1059 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001060 error = DoLaunch (exe_module,
1061 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1062 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001063 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001064 stdin_path,
1065 stdout_path,
1066 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067
1068 if (error.Fail())
1069 {
1070 if (GetID() != LLDB_INVALID_PROCESS_ID)
1071 {
1072 SetID (LLDB_INVALID_PROCESS_ID);
1073 const char *error_string = error.AsCString();
1074 if (error_string == NULL)
1075 error_string = "launch failed";
1076 SetExitStatus (-1, error_string);
1077 }
1078 }
1079 else
1080 {
1081 EventSP event_sp;
1082 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1083
1084 if (state == eStateStopped || state == eStateCrashed)
1085 {
1086 DidLaunch ();
1087
1088 // This delays passing the stopped event to listeners till DidLaunch gets
1089 // a chance to complete...
1090 HandlePrivateEvent (event_sp);
1091 StartPrivateStateThread ();
1092 }
1093 else if (state == eStateExited)
1094 {
1095 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1096 // not likely to work, and return an invalid pid.
1097 HandlePrivateEvent (event_sp);
1098 }
1099 }
1100 }
1101 }
1102 else
1103 {
1104 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1105 }
1106 }
1107 return error;
1108}
1109
1110Error
1111Process::CompleteAttach ()
1112{
1113 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001114
1115 if (GetID() == LLDB_INVALID_PROCESS_ID)
1116 {
1117 error.SetErrorString("no process");
1118 }
1119
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120 EventSP event_sp;
1121 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1122 if (state == eStateStopped || state == eStateCrashed)
1123 {
1124 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001125 // Figure out which one is the executable, and set that in our target:
1126 ModuleList &modules = GetTarget().GetImages();
1127
1128 size_t num_modules = modules.GetSize();
1129 for (int i = 0; i < num_modules; i++)
1130 {
1131 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1132 if (module_sp->IsExecutable())
1133 {
1134 ModuleSP exec_module = GetTarget().GetExecutableModule();
1135 if (!exec_module || exec_module != module_sp)
1136 {
1137
1138 GetTarget().SetExecutableModule (module_sp, false);
1139 }
1140 break;
1141 }
1142 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143
1144 // This delays passing the stopped event to listeners till DidLaunch gets
1145 // a chance to complete...
1146 HandlePrivateEvent(event_sp);
1147 StartPrivateStateThread();
1148 }
1149 else
1150 {
1151 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1152 // not likely to work, and return an invalid pid.
1153 if (state == eStateExited)
1154 HandlePrivateEvent (event_sp);
1155 error.SetErrorStringWithFormat("invalid state after attach: %s",
1156 lldb_private::StateAsCString(state));
1157 }
1158 return error;
1159}
1160
1161Error
1162Process::Attach (lldb::pid_t attach_pid)
1163{
1164
1165 m_target_triple.Clear();
1166 m_abi_sp.reset();
1167
Jim Ingham5aee1622010-08-09 23:31:02 +00001168 // Find the process and its architecture. Make sure it matches the architecture
1169 // of the current Target, and if not adjust it.
1170
1171 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1172 if (attach_spec != GetTarget().GetArchitecture())
1173 {
1174 // Set the architecture on the target.
1175 GetTarget().SetArchitecture(attach_spec);
1176 }
1177
Greg Claytonc982c762010-07-09 20:39:50 +00001178 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179 if (error.Success())
1180 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001181 SetPublicState (eStateAttaching);
1182
Greg Claytonc982c762010-07-09 20:39:50 +00001183 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184 if (error.Success())
1185 {
1186 error = CompleteAttach();
1187 }
1188 else
1189 {
1190 if (GetID() != LLDB_INVALID_PROCESS_ID)
1191 {
1192 SetID (LLDB_INVALID_PROCESS_ID);
1193 const char *error_string = error.AsCString();
1194 if (error_string == NULL)
1195 error_string = "attach failed";
1196
1197 SetExitStatus(-1, error_string);
1198 }
1199 }
1200 }
1201 return error;
1202}
1203
1204Error
1205Process::Attach (const char *process_name, bool wait_for_launch)
1206{
1207 m_target_triple.Clear();
1208 m_abi_sp.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001209
1210 // Find the process and its architecture. Make sure it matches the architecture
1211 // of the current Target, and if not adjust it.
1212
Jim Ingham2ecb7422010-08-17 21:54:19 +00001213 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001214 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001215 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001216 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001217 {
1218 // Set the architecture on the target.
1219 GetTarget().SetArchitecture(attach_spec);
1220 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001221 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001222
Greg Claytonc982c762010-07-09 20:39:50 +00001223 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001224 if (error.Success())
1225 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001226 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001227 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001228 if (error.Fail())
1229 {
1230 if (GetID() != LLDB_INVALID_PROCESS_ID)
1231 {
1232 SetID (LLDB_INVALID_PROCESS_ID);
1233 const char *error_string = error.AsCString();
1234 if (error_string == NULL)
1235 error_string = "attach failed";
1236
1237 SetExitStatus(-1, error_string);
1238 }
1239 }
1240 else
1241 {
1242 error = CompleteAttach();
1243 }
1244 }
1245 return error;
1246}
1247
1248Error
1249Process::Resume ()
1250{
1251 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1252 if (log)
1253 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1254
1255 Error error (WillResume());
1256 // Tell the process it is about to resume before the thread list
1257 if (error.Success())
1258 {
1259 // Now let the thread list know we are about to resume to it
1260 // can let all of our threads know that they are about to be
1261 // resumed. Threads will each be called with
1262 // Thread::WillResume(StateType) where StateType contains the state
1263 // that they are supposed to have when the process is resumed
1264 // (suspended/running/stepping). Threads should also check
1265 // their resume signal in lldb::Thread::GetResumeSignal()
1266 // to see if they are suppoed to start back up with a signal.
1267 if (m_thread_list.WillResume())
1268 {
1269 error = DoResume();
1270 if (error.Success())
1271 {
1272 DidResume();
1273 m_thread_list.DidResume();
1274 }
1275 }
1276 else
1277 {
1278 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1279 }
1280 }
1281 return error;
1282}
1283
1284Error
1285Process::Halt ()
1286{
1287 Error error (WillHalt());
1288
1289 if (error.Success())
1290 {
1291 error = DoHalt();
1292 if (error.Success())
1293 DidHalt();
1294 }
1295 return error;
1296}
1297
1298Error
1299Process::Detach ()
1300{
1301 Error error (WillDetach());
1302
1303 if (error.Success())
1304 {
1305 DisableAllBreakpointSites();
1306 error = DoDetach();
1307 if (error.Success())
1308 {
1309 DidDetach();
1310 StopPrivateStateThread();
1311 }
1312 }
1313 return error;
1314}
1315
1316Error
1317Process::Destroy ()
1318{
1319 Error error (WillDestroy());
1320 if (error.Success())
1321 {
1322 DisableAllBreakpointSites();
1323 error = DoDestroy();
1324 if (error.Success())
1325 {
1326 DidDestroy();
1327 StopPrivateStateThread();
1328 }
1329 }
1330 return error;
1331}
1332
1333Error
1334Process::Signal (int signal)
1335{
1336 Error error (WillSignal());
1337 if (error.Success())
1338 {
1339 error = DoSignal(signal);
1340 if (error.Success())
1341 DidSignal();
1342 }
1343 return error;
1344}
1345
1346UnixSignals &
1347Process::GetUnixSignals ()
1348{
1349 return m_unix_signals;
1350}
1351
1352Target &
1353Process::GetTarget ()
1354{
1355 return m_target;
1356}
1357
1358const Target &
1359Process::GetTarget () const
1360{
1361 return m_target;
1362}
1363
1364uint32_t
1365Process::GetAddressByteSize()
1366{
1367 return m_target.GetArchitecture().GetAddressByteSize();
1368}
1369
1370bool
1371Process::ShouldBroadcastEvent (Event *event_ptr)
1372{
1373 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1374 bool return_value = true;
1375 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1376
1377 switch (state)
1378 {
1379 case eStateAttaching:
1380 case eStateLaunching:
1381 case eStateDetached:
1382 case eStateExited:
1383 case eStateUnloaded:
1384 // These events indicate changes in the state of the debugging session, always report them.
1385 return_value = true;
1386 break;
1387 case eStateInvalid:
1388 // We stopped for no apparent reason, don't report it.
1389 return_value = false;
1390 break;
1391 case eStateRunning:
1392 case eStateStepping:
1393 // If we've started the target running, we handle the cases where we
1394 // are already running and where there is a transition from stopped to
1395 // running differently.
1396 // running -> running: Automatically suppress extra running events
1397 // stopped -> running: Report except when there is one or more no votes
1398 // and no yes votes.
1399 SynchronouslyNotifyStateChanged (state);
1400 switch (m_public_state.GetValue())
1401 {
1402 case eStateRunning:
1403 case eStateStepping:
1404 // We always suppress multiple runnings with no PUBLIC stop in between.
1405 return_value = false;
1406 break;
1407 default:
1408 // TODO: make this work correctly. For now always report
1409 // run if we aren't running so we don't miss any runnning
1410 // events. If I run the lldb/test/thread/a.out file and
1411 // break at main.cpp:58, run and hit the breakpoints on
1412 // multiple threads, then somehow during the stepping over
1413 // of all breakpoints no run gets reported.
1414 return_value = true;
1415
1416 // This is a transition from stop to run.
1417 switch (m_thread_list.ShouldReportRun (event_ptr))
1418 {
1419 case eVoteYes:
1420 case eVoteNoOpinion:
1421 return_value = true;
1422 break;
1423 case eVoteNo:
1424 return_value = false;
1425 break;
1426 }
1427 break;
1428 }
1429 break;
1430 case eStateStopped:
1431 case eStateCrashed:
1432 case eStateSuspended:
1433 {
1434 // We've stopped. First see if we're going to restart the target.
1435 // If we are going to stop, then we always broadcast the event.
1436 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00001437 // If no thread has an opinion, we don't report it.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001438 if (state != eStateInvalid)
1439 {
1440
1441 RefreshStateAfterStop ();
1442
1443 if (m_thread_list.ShouldStop (event_ptr) == false)
1444 {
1445 switch (m_thread_list.ShouldReportStop (event_ptr))
1446 {
1447 case eVoteYes:
1448 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00001449 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001450 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451 case eVoteNo:
1452 return_value = false;
1453 break;
1454 }
1455
1456 if (log)
1457 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state));
1458 Resume ();
1459 }
1460 else
1461 {
1462 return_value = true;
1463 SynchronouslyNotifyStateChanged (state);
1464 }
1465 }
1466 }
1467 }
1468
1469 if (log)
1470 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1471 return return_value;
1472}
1473
1474//------------------------------------------------------------------
1475// Thread Queries
1476//------------------------------------------------------------------
1477
1478ThreadList &
1479Process::GetThreadList ()
1480{
1481 return m_thread_list;
1482}
1483
1484const ThreadList &
1485Process::GetThreadList () const
1486{
1487 return m_thread_list;
1488}
1489
1490
1491bool
1492Process::StartPrivateStateThread ()
1493{
1494 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1495
1496 if (log)
1497 log->Printf ("Process::%s ( )", __FUNCTION__);
1498
1499 // Create a thread that watches our internal state and controls which
1500 // events make it to clients (into the DCProcess event queue).
1501 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1502 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1503}
1504
1505void
1506Process::PausePrivateStateThread ()
1507{
1508 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1509}
1510
1511void
1512Process::ResumePrivateStateThread ()
1513{
1514 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1515}
1516
1517void
1518Process::StopPrivateStateThread ()
1519{
1520 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1521}
1522
1523void
1524Process::ControlPrivateStateThread (uint32_t signal)
1525{
1526 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1527
1528 assert (signal == eBroadcastInternalStateControlStop ||
1529 signal == eBroadcastInternalStateControlPause ||
1530 signal == eBroadcastInternalStateControlResume);
1531
1532 if (log)
1533 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1534
1535 // Signal the private state thread
1536 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1537 {
1538 TimeValue timeout_time;
1539 bool timed_out;
1540
1541 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1542
1543 timeout_time = TimeValue::Now();
1544 timeout_time.OffsetWithSeconds(2);
1545 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1546 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1547
1548 if (signal == eBroadcastInternalStateControlStop)
1549 {
1550 if (timed_out)
1551 Host::ThreadCancel (m_private_state_thread, NULL);
1552
1553 thread_result_t result = NULL;
1554 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00001555 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001556 }
1557 }
1558}
1559
1560void
1561Process::HandlePrivateEvent (EventSP &event_sp)
1562{
1563 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1564 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1565 // See if we should broadcast this state to external clients?
1566 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1567 if (log)
1568 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1569
1570 if (should_broadcast)
1571 {
1572 if (log)
1573 {
1574 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1575 }
1576 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1577 BroadcastEvent (event_sp);
1578 }
1579 else
1580 {
1581 if (log)
1582 {
1583 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1584 }
1585 }
1586}
1587
1588void *
1589Process::PrivateStateThread (void *arg)
1590{
1591 Process *proc = static_cast<Process*> (arg);
1592 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001593 return result;
1594}
1595
1596void *
1597Process::RunPrivateStateThread ()
1598{
1599 bool control_only = false;
1600 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1601
1602 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1603 if (log)
1604 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1605
1606 bool exit_now = false;
1607 while (!exit_now)
1608 {
1609 EventSP event_sp;
1610 WaitForEventsPrivate (NULL, event_sp, control_only);
1611 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1612 {
1613 switch (event_sp->GetType())
1614 {
1615 case eBroadcastInternalStateControlStop:
1616 exit_now = true;
1617 continue; // Go to next loop iteration so we exit without
1618 break; // doing any internal state managment below
1619
1620 case eBroadcastInternalStateControlPause:
1621 control_only = true;
1622 break;
1623
1624 case eBroadcastInternalStateControlResume:
1625 control_only = false;
1626 break;
1627 }
1628 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1629 }
1630
1631
1632 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1633
1634 if (internal_state != eStateInvalid)
1635 {
1636 HandlePrivateEvent (event_sp);
1637 }
1638
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001639 if (internal_state == eStateInvalid ||
1640 internal_state == eStateExited ||
1641 internal_state == eStateDetached )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642 break;
1643 }
1644
Caroline Tice20ad3c42010-10-29 21:48:37 +00001645 // Verify log is still enabled before attempting to write to it...
1646 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001647 if (log)
1648 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1649
Greg Claytonbe77e3b2010-08-19 21:50:06 +00001650 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651 return NULL;
1652}
1653
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001654//------------------------------------------------------------------
1655// Process Event Data
1656//------------------------------------------------------------------
1657
1658Process::ProcessEventData::ProcessEventData () :
1659 EventData (),
1660 m_process_sp (),
1661 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00001662 m_restarted (false),
1663 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664{
1665}
1666
1667Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1668 EventData (),
1669 m_process_sp (process_sp),
1670 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00001671 m_restarted (false),
1672 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673{
1674}
1675
1676Process::ProcessEventData::~ProcessEventData()
1677{
1678}
1679
1680const ConstString &
1681Process::ProcessEventData::GetFlavorString ()
1682{
1683 static ConstString g_flavor ("Process::ProcessEventData");
1684 return g_flavor;
1685}
1686
1687const ConstString &
1688Process::ProcessEventData::GetFlavor () const
1689{
1690 return ProcessEventData::GetFlavorString ();
1691}
1692
1693const ProcessSP &
1694Process::ProcessEventData::GetProcessSP () const
1695{
1696 return m_process_sp;
1697}
1698
1699StateType
1700Process::ProcessEventData::GetState () const
1701{
1702 return m_state;
1703}
1704
1705bool
1706Process::ProcessEventData::GetRestarted () const
1707{
1708 return m_restarted;
1709}
1710
1711void
1712Process::ProcessEventData::SetRestarted (bool new_value)
1713{
1714 m_restarted = new_value;
1715}
1716
1717void
1718Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1719{
1720 // This function gets called twice for each event, once when the event gets pulled
1721 // off of the private process event queue, and once when it gets pulled off of
1722 // the public event queue. m_update_state is used to distinguish these
1723 // two cases; it is false when we're just pulling it off for private handling,
1724 // and we don't want to do the breakpoint command handling then.
1725
1726 if (!m_update_state)
1727 return;
1728
1729 m_process_sp->SetPublicState (m_state);
1730
1731 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1732 if (m_state == eStateStopped && ! m_restarted)
1733 {
1734 int num_threads = m_process_sp->GetThreadList().GetSize();
1735 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00001736
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 for (idx = 0; idx < num_threads; ++idx)
1738 {
1739 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1740
Jim Inghamb15bfc72010-10-20 00:39:53 +00001741 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
1742 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00001744 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 }
1746 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00001747
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00001748 // The stop action might restart the target. If it does, then we want to mark that in the
1749 // event so that whoever is receiving it will know to wait for the running event and reflect
1750 // that state appropriately.
1751
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001752 if (m_process_sp->GetPrivateState() == eStateRunning)
1753 SetRestarted(true);
1754 }
1755}
1756
1757void
1758Process::ProcessEventData::Dump (Stream *s) const
1759{
1760 if (m_process_sp)
1761 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1762
1763 s->Printf("state = %s", StateAsCString(GetState()));;
1764}
1765
1766const Process::ProcessEventData *
1767Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1768{
1769 if (event_ptr)
1770 {
1771 const EventData *event_data = event_ptr->GetData();
1772 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1773 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1774 }
1775 return NULL;
1776}
1777
1778ProcessSP
1779Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
1780{
1781 ProcessSP process_sp;
1782 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1783 if (data)
1784 process_sp = data->GetProcessSP();
1785 return process_sp;
1786}
1787
1788StateType
1789Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
1790{
1791 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1792 if (data == NULL)
1793 return eStateInvalid;
1794 else
1795 return data->GetState();
1796}
1797
1798bool
1799Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
1800{
1801 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1802 if (data == NULL)
1803 return false;
1804 else
1805 return data->GetRestarted();
1806}
1807
1808void
1809Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
1810{
1811 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1812 if (data != NULL)
1813 data->SetRestarted(new_value);
1814}
1815
1816bool
1817Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
1818{
1819 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1820 if (data)
1821 {
1822 data->SetUpdateStateOnRemoval();
1823 return true;
1824 }
1825 return false;
1826}
1827
1828void
1829Process::ProcessEventData::SetUpdateStateOnRemoval()
1830{
1831 m_update_state = true;
1832}
1833
1834Target *
1835Process::CalculateTarget ()
1836{
1837 return &m_target;
1838}
1839
1840Process *
1841Process::CalculateProcess ()
1842{
1843 return this;
1844}
1845
1846Thread *
1847Process::CalculateThread ()
1848{
1849 return NULL;
1850}
1851
1852StackFrame *
1853Process::CalculateStackFrame ()
1854{
1855 return NULL;
1856}
1857
1858void
Greg Clayton0603aa92010-10-04 01:05:56 +00001859Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860{
1861 exe_ctx.target = &m_target;
1862 exe_ctx.process = this;
1863 exe_ctx.thread = NULL;
1864 exe_ctx.frame = NULL;
1865}
1866
1867lldb::ProcessSP
1868Process::GetSP ()
1869{
1870 return GetTarget().GetProcessSP();
1871}
1872
Sean Callanan2235f322010-08-11 03:57:18 +00001873ClangPersistentVariables &
1874Process::GetPersistentVariables()
1875{
1876 return m_persistent_vars;
1877}
1878
Jim Ingham5aee1622010-08-09 23:31:02 +00001879uint32_t
1880Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
1881{
1882 return 0;
1883}
1884
1885ArchSpec
1886Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
1887{
1888 return Host::GetArchSpecForExistingProcess (pid);
1889}
1890
1891ArchSpec
1892Process::GetArchSpecForExistingProcess (const char *process_name)
1893{
1894 return Host::GetArchSpecForExistingProcess (process_name);
1895}
1896
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001897lldb::UserSettingsControllerSP
1898Process::GetSettingsController (bool finish)
1899{
Greg Clayton1b654882010-09-19 02:33:57 +00001900 static UserSettingsControllerSP g_settings_controller (new SettingsController);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001901 static bool initialized = false;
1902
1903 if (!initialized)
1904 {
Jim Ingham95852752010-09-07 20:27:09 +00001905 initialized = UserSettingsController::InitializeSettingsController (g_settings_controller,
Greg Clayton1b654882010-09-19 02:33:57 +00001906 Process::SettingsController::global_settings_table,
1907 Process::SettingsController::instance_settings_table);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001908 }
1909
1910 if (finish)
1911 {
Jim Ingham95852752010-09-07 20:27:09 +00001912 UserSettingsController::FinalizeSettingsController (g_settings_controller);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001913 g_settings_controller.reset();
Jim Ingham95852752010-09-07 20:27:09 +00001914 initialized = false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001915 }
1916
1917 return g_settings_controller;
1918}
1919
Caroline Tice1559a462010-09-27 00:30:10 +00001920void
1921Process::UpdateInstanceName ()
1922{
1923 ModuleSP module_sp = GetTarget().GetExecutableModule();
1924 if (module_sp)
1925 {
1926 StreamString sstr;
1927 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
1928
1929 Process::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
1930 sstr.GetData());
1931 }
1932}
1933
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001934//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00001935// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001936//--------------------------------------------------------------
1937
Greg Clayton1b654882010-09-19 02:33:57 +00001938Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00001939 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001940{
Caroline Tice91123da2010-09-08 17:48:55 +00001941 m_default_settings.reset (new ProcessInstanceSettings (*this, false,
1942 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001943}
1944
Greg Clayton1b654882010-09-19 02:33:57 +00001945Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001946{
1947}
1948
1949lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00001950Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001951{
Caroline Tice91123da2010-09-08 17:48:55 +00001952 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*(Process::GetSettingsController().get()),
1953 false, instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001954 lldb::InstanceSettingsSP new_settings_sp (new_settings);
1955 return new_settings_sp;
1956}
1957
1958//--------------------------------------------------------------
1959// class ProcessInstanceSettings
1960//--------------------------------------------------------------
1961
Caroline Tice91123da2010-09-08 17:48:55 +00001962ProcessInstanceSettings::ProcessInstanceSettings (UserSettingsController &owner, bool live_instance,
1963 const char *name) :
Caroline Tice9e41c152010-09-16 19:05:55 +00001964 InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001965 m_run_args (),
1966 m_env_vars (),
1967 m_input_path (),
1968 m_output_path (),
1969 m_error_path (),
1970 m_plugin (),
1971 m_disable_aslr (true)
1972{
Caroline Ticef20e8232010-09-09 18:26:37 +00001973 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1974 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
1975 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00001976 // This is true for CreateInstanceName() too.
1977
1978 if (GetInstanceName () == InstanceSettings::InvalidName())
1979 {
1980 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1981 m_owner.RegisterInstanceSettings (this);
1982 }
Caroline Ticef20e8232010-09-09 18:26:37 +00001983
1984 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001985 {
1986 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1987 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00001988 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001989 }
1990}
1991
1992ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
1993 InstanceSettings (*(Process::GetSettingsController().get()), CreateInstanceName().AsCString()),
1994 m_run_args (rhs.m_run_args),
1995 m_env_vars (rhs.m_env_vars),
1996 m_input_path (rhs.m_input_path),
1997 m_output_path (rhs.m_output_path),
1998 m_error_path (rhs.m_error_path),
1999 m_plugin (rhs.m_plugin),
2000 m_disable_aslr (rhs.m_disable_aslr)
2001{
2002 if (m_instance_name != InstanceSettings::GetDefaultName())
2003 {
2004 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2005 CopyInstanceSettings (pending_settings,false);
2006 m_owner.RemovePendingSettings (m_instance_name);
2007 }
2008}
2009
2010ProcessInstanceSettings::~ProcessInstanceSettings ()
2011{
2012}
2013
2014ProcessInstanceSettings&
2015ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2016{
2017 if (this != &rhs)
2018 {
2019 m_run_args = rhs.m_run_args;
2020 m_env_vars = rhs.m_env_vars;
2021 m_input_path = rhs.m_input_path;
2022 m_output_path = rhs.m_output_path;
2023 m_error_path = rhs.m_error_path;
2024 m_plugin = rhs.m_plugin;
2025 m_disable_aslr = rhs.m_disable_aslr;
2026 }
2027
2028 return *this;
2029}
2030
2031
2032void
2033ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2034 const char *index_value,
2035 const char *value,
2036 const ConstString &instance_name,
2037 const SettingEntry &entry,
2038 lldb::VarSetOperationType op,
2039 Error &err,
2040 bool pending)
2041{
2042 if (var_name == RunArgsVarName())
2043 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2044 else if (var_name == EnvVarsVarName())
2045 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2046 else if (var_name == InputPathVarName())
2047 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2048 else if (var_name == OutputPathVarName())
2049 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2050 else if (var_name == ErrorPathVarName())
2051 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2052 else if (var_name == PluginVarName())
2053 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
2054 else if (var_name == DisableASLRVarName())
2055 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
2056}
2057
2058void
2059ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2060 bool pending)
2061{
2062 if (new_settings.get() == NULL)
2063 return;
2064
2065 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2066
2067 m_run_args = new_process_settings->m_run_args;
2068 m_env_vars = new_process_settings->m_env_vars;
2069 m_input_path = new_process_settings->m_input_path;
2070 m_output_path = new_process_settings->m_output_path;
2071 m_error_path = new_process_settings->m_error_path;
2072 m_plugin = new_process_settings->m_plugin;
2073 m_disable_aslr = new_process_settings->m_disable_aslr;
2074}
2075
Caroline Tice12cecd72010-09-20 21:37:42 +00002076bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002077ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2078 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00002079 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00002080 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002081{
2082 if (var_name == RunArgsVarName())
2083 {
2084 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00002085 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002086 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2087 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00002088 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002089 }
2090 else if (var_name == EnvVarsVarName())
2091 {
2092 if (m_env_vars.size() > 0)
2093 {
2094 std::map<std::string, std::string>::iterator pos;
2095 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2096 {
2097 StreamString value_str;
2098 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2099 value.AppendString (value_str.GetData());
2100 }
2101 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002102 }
2103 else if (var_name == InputPathVarName())
2104 {
2105 value.AppendString (m_input_path.c_str());
2106 }
2107 else if (var_name == OutputPathVarName())
2108 {
2109 value.AppendString (m_output_path.c_str());
2110 }
2111 else if (var_name == ErrorPathVarName())
2112 {
2113 value.AppendString (m_error_path.c_str());
2114 }
2115 else if (var_name == PluginVarName())
2116 {
2117 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2118 }
2119 else if (var_name == DisableASLRVarName())
2120 {
2121 if (m_disable_aslr)
2122 value.AppendString ("true");
2123 else
2124 value.AppendString ("false");
2125 }
2126 else
Caroline Tice12cecd72010-09-20 21:37:42 +00002127 {
2128 if (err)
2129 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2130 return false;
2131 }
2132 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002133}
2134
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002135const ConstString
2136ProcessInstanceSettings::CreateInstanceName ()
2137{
2138 static int instance_count = 1;
2139 StreamString sstr;
2140
2141 sstr.Printf ("process_%d", instance_count);
2142 ++instance_count;
2143
2144 const ConstString ret_val (sstr.GetData());
2145 return ret_val;
2146}
2147
2148const ConstString &
2149ProcessInstanceSettings::RunArgsVarName ()
2150{
2151 static ConstString run_args_var_name ("run-args");
2152
2153 return run_args_var_name;
2154}
2155
2156const ConstString &
2157ProcessInstanceSettings::EnvVarsVarName ()
2158{
2159 static ConstString env_vars_var_name ("env-vars");
2160
2161 return env_vars_var_name;
2162}
2163
2164const ConstString &
2165ProcessInstanceSettings::InputPathVarName ()
2166{
2167 static ConstString input_path_var_name ("input-path");
2168
2169 return input_path_var_name;
2170}
2171
2172const ConstString &
2173ProcessInstanceSettings::OutputPathVarName ()
2174{
Caroline Tice49e27372010-09-07 18:35:40 +00002175 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002176
2177 return output_path_var_name;
2178}
2179
2180const ConstString &
2181ProcessInstanceSettings::ErrorPathVarName ()
2182{
Caroline Tice49e27372010-09-07 18:35:40 +00002183 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002184
2185 return error_path_var_name;
2186}
2187
2188const ConstString &
2189ProcessInstanceSettings::PluginVarName ()
2190{
2191 static ConstString plugin_var_name ("plugin");
2192
2193 return plugin_var_name;
2194}
2195
2196
2197const ConstString &
2198ProcessInstanceSettings::DisableASLRVarName ()
2199{
2200 static ConstString disable_aslr_var_name ("disable-aslr");
2201
2202 return disable_aslr_var_name;
2203}
2204
2205
2206//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002207// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002208//--------------------------------------------------
2209
2210SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00002211Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002212{
2213 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2214 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2215};
2216
2217
2218lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00002219Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002220{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00002221 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2222 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2223 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002224};
2225
2226SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00002227Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002228{
2229 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2230 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2231 { "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." },
2232 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2233 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2234 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2235 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
2236 { "disable-aslr", eSetVarTypeBool, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
2237 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2238};
2239
2240
Jim Ingham5aee1622010-08-09 23:31:02 +00002241