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