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