blob: c9b5579be5d3a44f71572d0c9e8d1c74ab52a115 [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"
Greg Clayton0baa3942010-11-04 01:54:29 +000024#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000025#include "lldb/Target/LanguageRuntime.h"
26#include "lldb/Target/CPPLanguageRuntime.h"
27#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000029#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Target/Target.h"
31#include "lldb/Target/TargetList.h"
32#include "lldb/Target/Thread.h"
33#include "lldb/Target/ThreadPlan.h"
34
35using namespace lldb;
36using namespace lldb_private;
37
38Process*
39Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
40{
41 ProcessCreateInstance create_callback = NULL;
42 if (plugin_name)
43 {
44 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
45 if (create_callback)
46 {
47 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
48 if (debugger_ap->CanDebug(target))
49 return debugger_ap.release();
50 }
51 }
52 else
53 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000054 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +000055 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000056 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
57 if (debugger_ap->CanDebug(target))
58 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +000059 }
60 }
61 return NULL;
62}
63
64
65//----------------------------------------------------------------------
66// Process constructor
67//----------------------------------------------------------------------
68Process::Process(Target &target, Listener &listener) :
69 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +000070 Broadcaster ("lldb.process"),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000071 ProcessInstanceSettings (*(Process::GetSettingsController().get())),
Chris Lattner24943d22010-06-08 16:52:24 +000072 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +000073 m_public_state (eStateUnloaded),
74 m_private_state (eStateUnloaded),
75 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
76 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
77 m_private_state_listener ("lldb.process.internal_state_listener"),
78 m_private_state_control_wait(),
79 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
80 m_stop_id (0),
81 m_thread_index_id (0),
82 m_exit_status (-1),
83 m_exit_string (),
84 m_thread_list (this),
85 m_notifications (),
Jim Inghamd1686902010-10-14 23:45:03 +000086 m_persistent_vars(),
Chris Lattner24943d22010-06-08 16:52:24 +000087 m_listener(listener),
Jim Inghamd1686902010-10-14 23:45:03 +000088 m_unix_signals ()
Chris Lattner24943d22010-06-08 16:52:24 +000089{
Caroline Tice1ebef442010-09-27 00:30:10 +000090 UpdateInstanceName();
91
Greg Claytone005f2c2010-11-06 01:53:30 +000092 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +000093 if (log)
94 log->Printf ("%p Process::Process()", this);
95
Greg Clayton49ce6822010-10-31 03:01:06 +000096 SetEventName (eBroadcastBitStateChanged, "state-changed");
97 SetEventName (eBroadcastBitInterrupt, "interrupt");
98 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
99 SetEventName (eBroadcastBitSTDERR, "stderr-available");
100
Chris Lattner24943d22010-06-08 16:52:24 +0000101 listener.StartListeningForEvents (this,
102 eBroadcastBitStateChanged |
103 eBroadcastBitInterrupt |
104 eBroadcastBitSTDOUT |
105 eBroadcastBitSTDERR);
106
107 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
108 eBroadcastBitStateChanged);
109
110 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
111 eBroadcastInternalStateControlStop |
112 eBroadcastInternalStateControlPause |
113 eBroadcastInternalStateControlResume);
114}
115
116//----------------------------------------------------------------------
117// Destructor
118//----------------------------------------------------------------------
119Process::~Process()
120{
Greg Claytone005f2c2010-11-06 01:53:30 +0000121 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000122 if (log)
123 log->Printf ("%p Process::~Process()", this);
124 StopPrivateStateThread();
125}
126
127void
128Process::Finalize()
129{
130 // Do any cleanup needed prior to being destructed... Subclasses
131 // that override this method should call this superclass method as well.
132}
133
134void
135Process::RegisterNotificationCallbacks (const Notifications& callbacks)
136{
137 m_notifications.push_back(callbacks);
138 if (callbacks.initialize != NULL)
139 callbacks.initialize (callbacks.baton, this);
140}
141
142bool
143Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
144{
145 std::vector<Notifications>::iterator pos, end = m_notifications.end();
146 for (pos = m_notifications.begin(); pos != end; ++pos)
147 {
148 if (pos->baton == callbacks.baton &&
149 pos->initialize == callbacks.initialize &&
150 pos->process_state_changed == callbacks.process_state_changed)
151 {
152 m_notifications.erase(pos);
153 return true;
154 }
155 }
156 return false;
157}
158
159void
160Process::SynchronouslyNotifyStateChanged (StateType state)
161{
162 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
163 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
164 {
165 if (notification_pos->process_state_changed)
166 notification_pos->process_state_changed (notification_pos->baton, this, state);
167 }
168}
169
170// FIXME: We need to do some work on events before the general Listener sees them.
171// For instance if we are continuing from a breakpoint, we need to ensure that we do
172// the little "insert real insn, step & stop" trick. But we can't do that when the
173// event is delivered by the broadcaster - since that is done on the thread that is
174// waiting for new events, so if we needed more than one event for our handling, we would
175// stall. So instead we do it when we fetch the event off of the queue.
176//
177
178StateType
179Process::GetNextEvent (EventSP &event_sp)
180{
181 StateType state = eStateInvalid;
182
183 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
184 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
185
186 return state;
187}
188
189
190StateType
191Process::WaitForProcessToStop (const TimeValue *timeout)
192{
193 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
194 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
195}
196
197
198StateType
199Process::WaitForState
200(
201 const TimeValue *timeout,
202 const StateType *match_states, const uint32_t num_match_states
203)
204{
205 EventSP event_sp;
206 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000207 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000208 while (state != eStateInvalid)
209 {
Greg Claytond8c62532010-10-07 04:19:01 +0000210 // If we are exited or detached, we won't ever get back to any
211 // other valid state...
212 if (state == eStateDetached || state == eStateExited)
213 return state;
214
Chris Lattner24943d22010-06-08 16:52:24 +0000215 state = WaitForStateChangedEvents (timeout, event_sp);
216
217 for (i=0; i<num_match_states; ++i)
218 {
219 if (match_states[i] == state)
220 return state;
221 }
222 }
223 return state;
224}
225
Jim Ingham63e24d72010-10-11 23:53:14 +0000226bool
227Process::HijackProcessEvents (Listener *listener)
228{
229 if (listener != NULL)
230 {
231 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
232 }
233 else
234 return false;
235}
236
237void
238Process::RestoreProcessEvents ()
239{
240 RestoreBroadcaster();
241}
242
Chris Lattner24943d22010-06-08 16:52:24 +0000243StateType
244Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
245{
Greg Claytone005f2c2010-11-06 01:53:30 +0000246 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000247
248 if (log)
249 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
250
251 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000252 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
253 this,
254 eBroadcastBitStateChanged,
255 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000256 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
257
Caroline Tice926060e2010-10-29 21:48:37 +0000258 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000259 if (log)
260 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
261 __FUNCTION__,
262 timeout,
263 StateAsCString(state));
264 return state;
265}
266
267Event *
268Process::PeekAtStateChangedEvents ()
269{
Greg Claytone005f2c2010-11-06 01:53:30 +0000270 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000271
272 if (log)
273 log->Printf ("Process::%s...", __FUNCTION__);
274
275 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000276 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
277 eBroadcastBitStateChanged);
Caroline Tice926060e2010-10-29 21:48:37 +0000278 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000279 if (log)
280 {
281 if (event_ptr)
282 {
283 log->Printf ("Process::%s (event_ptr) => %s",
284 __FUNCTION__,
285 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
286 }
287 else
288 {
289 log->Printf ("Process::%s no events found",
290 __FUNCTION__);
291 }
292 }
293 return event_ptr;
294}
295
296StateType
297Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
298{
Greg Claytone005f2c2010-11-06 01:53:30 +0000299 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000300
301 if (log)
302 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
303
304 StateType state = eStateInvalid;
305 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
306 &m_private_state_broadcaster,
307 eBroadcastBitStateChanged,
308 event_sp))
309 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
310
311 // This is a bit of a hack, but when we wait here we could very well return
312 // to the command-line, and that could disable the log, which would render the
313 // log we got above invalid.
314 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
315 if (log)
316 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
317 return state;
318}
319
320bool
321Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
322{
Greg Claytone005f2c2010-11-06 01:53:30 +0000323 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000324
325 if (log)
326 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
327
328 if (control_only)
329 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
330 else
331 return m_private_state_listener.WaitForEvent(timeout, event_sp);
332}
333
334bool
335Process::IsRunning () const
336{
337 return StateIsRunningState (m_public_state.GetValue());
338}
339
340int
341Process::GetExitStatus ()
342{
343 if (m_public_state.GetValue() == eStateExited)
344 return m_exit_status;
345 return -1;
346}
347
348const char *
349Process::GetExitDescription ()
350{
351 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
352 return m_exit_string.c_str();
353 return NULL;
354}
355
356void
357Process::SetExitStatus (int status, const char *cstr)
358{
359 m_exit_status = status;
360 if (cstr)
361 m_exit_string = cstr;
362 else
363 m_exit_string.clear();
364
365 SetPrivateState (eStateExited);
366}
367
368// This static callback can be used to watch for local child processes on
369// the current host. The the child process exits, the process will be
370// found in the global target list (we want to be completely sure that the
371// lldb_private::Process doesn't go away before we can deliver the signal.
372bool
373Process::SetProcessExitStatus
374(
375 void *callback_baton,
376 lldb::pid_t pid,
377 int signo, // Zero for no signal
378 int exit_status // Exit value of process if signal is zero
379)
380{
381 if (signo == 0 || exit_status)
382 {
Greg Clayton63094e02010-06-23 01:19:29 +0000383 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000384 if (target_sp)
385 {
386 ProcessSP process_sp (target_sp->GetProcessSP());
387 if (process_sp)
388 {
389 const char *signal_cstr = NULL;
390 if (signo)
391 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
392
393 process_sp->SetExitStatus (exit_status, signal_cstr);
394 }
395 }
396 return true;
397 }
398 return false;
399}
400
401
402uint32_t
403Process::GetNextThreadIndexID ()
404{
405 return ++m_thread_index_id;
406}
407
408StateType
409Process::GetState()
410{
411 // If any other threads access this we will need a mutex for it
412 return m_public_state.GetValue ();
413}
414
415void
416Process::SetPublicState (StateType new_state)
417{
Greg Claytone005f2c2010-11-06 01:53:30 +0000418 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000419 if (log)
420 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
421 m_public_state.SetValue (new_state);
422}
423
424StateType
425Process::GetPrivateState ()
426{
427 return m_private_state.GetValue();
428}
429
430void
431Process::SetPrivateState (StateType new_state)
432{
Greg Claytone005f2c2010-11-06 01:53:30 +0000433 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000434 bool state_changed = false;
435
436 if (log)
437 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
438
439 Mutex::Locker locker(m_private_state.GetMutex());
440
441 const StateType old_state = m_private_state.GetValueNoLock ();
442 state_changed = old_state != new_state;
443 if (state_changed)
444 {
445 m_private_state.SetValueNoLock (new_state);
446 if (StateIsStoppedState(new_state))
447 {
448 m_stop_id++;
449 if (log)
450 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
451 }
452 // Use our target to get a shared pointer to ourselves...
453 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
454 }
455 else
456 {
457 if (log)
458 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
459 }
460}
461
462
463uint32_t
464Process::GetStopID() const
465{
466 return m_stop_id;
467}
468
469addr_t
470Process::GetImageInfoAddress()
471{
472 return LLDB_INVALID_ADDRESS;
473}
474
Greg Clayton0baa3942010-11-04 01:54:29 +0000475//----------------------------------------------------------------------
476// LoadImage
477//
478// This function provides a default implementation that works for most
479// unix variants. Any Process subclasses that need to do shared library
480// loading differently should override LoadImage and UnloadImage and
481// do what is needed.
482//----------------------------------------------------------------------
483uint32_t
484Process::LoadImage (const FileSpec &image_spec, Error &error)
485{
486 DynamicLoader *loader = GetDynamicLoader();
487 if (loader)
488 {
489 error = loader->CanLoadImage();
490 if (error.Fail())
491 return LLDB_INVALID_IMAGE_TOKEN;
492 }
493
494 if (error.Success())
495 {
496 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
497 if (thread_sp == NULL)
498 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
499
500 if (thread_sp)
501 {
502 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
503
504 if (frame_sp)
505 {
506 ExecutionContext exe_ctx;
507 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000508 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000509 StreamString expr;
510 char path[PATH_MAX];
511 image_spec.GetPath(path, sizeof(path));
512 expr.Printf("dlopen (\"%s\", 2)", path);
513 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamea9d4262010-11-05 19:25:48 +0000514 lldb::ValueObjectSP result_valobj_sp (ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix));
Greg Clayton0baa3942010-11-04 01:54:29 +0000515 if (result_valobj_sp->GetError().Success())
516 {
517 Scalar scalar;
518 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
519 {
520 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
521 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
522 {
523 uint32_t image_token = m_image_tokens.size();
524 m_image_tokens.push_back (image_ptr);
525 return image_token;
526 }
527 }
528 }
529 }
530 }
531 }
532 return LLDB_INVALID_IMAGE_TOKEN;
533}
534
535//----------------------------------------------------------------------
536// UnloadImage
537//
538// This function provides a default implementation that works for most
539// unix variants. Any Process subclasses that need to do shared library
540// loading differently should override LoadImage and UnloadImage and
541// do what is needed.
542//----------------------------------------------------------------------
543Error
544Process::UnloadImage (uint32_t image_token)
545{
546 Error error;
547 if (image_token < m_image_tokens.size())
548 {
549 const addr_t image_addr = m_image_tokens[image_token];
550 if (image_addr == LLDB_INVALID_ADDRESS)
551 {
552 error.SetErrorString("image already unloaded");
553 }
554 else
555 {
556 DynamicLoader *loader = GetDynamicLoader();
557 if (loader)
558 error = loader->CanLoadImage();
559
560 if (error.Success())
561 {
562 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
563 if (thread_sp == NULL)
564 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
565
566 if (thread_sp)
567 {
568 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
569
570 if (frame_sp)
571 {
572 ExecutionContext exe_ctx;
573 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000574 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000575 StreamString expr;
576 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
577 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamea9d4262010-11-05 19:25:48 +0000578 lldb::ValueObjectSP result_valobj_sp (ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix));
Greg Clayton0baa3942010-11-04 01:54:29 +0000579 if (result_valobj_sp->GetError().Success())
580 {
581 Scalar scalar;
582 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
583 {
584 if (scalar.UInt(1))
585 {
586 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
587 }
588 else
589 {
590 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
591 }
592 }
593 }
594 else
595 {
596 error = result_valobj_sp->GetError();
597 }
598 }
599 }
600 }
601 }
602 }
603 else
604 {
605 error.SetErrorString("invalid image token");
606 }
607 return error;
608}
609
Chris Lattner24943d22010-06-08 16:52:24 +0000610DynamicLoader *
611Process::GetDynamicLoader()
612{
613 return NULL;
614}
615
616const ABI *
617Process::GetABI()
618{
619 ConstString& triple = m_target_triple;
620
621 if (triple.IsEmpty())
622 return NULL;
623
624 if (m_abi_sp.get() == NULL)
625 {
626 m_abi_sp.reset(ABI::FindPlugin(triple));
627 }
628
629 return m_abi_sp.get();
630}
631
Jim Ingham642036f2010-09-23 02:01:19 +0000632LanguageRuntime *
633Process::GetLanguageRuntime(lldb::LanguageType language)
634{
635 LanguageRuntimeCollection::iterator pos;
636 pos = m_language_runtimes.find (language);
637 if (pos == m_language_runtimes.end())
638 {
639 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
640
641 m_language_runtimes[language]
642 = runtime;
643 return runtime.get();
644 }
645 else
646 return (*pos).second.get();
647}
648
649CPPLanguageRuntime *
650Process::GetCPPLanguageRuntime ()
651{
652 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
653 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
654 return static_cast<CPPLanguageRuntime *> (runtime);
655 return NULL;
656}
657
658ObjCLanguageRuntime *
659Process::GetObjCLanguageRuntime ()
660{
661 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
662 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
663 return static_cast<ObjCLanguageRuntime *> (runtime);
664 return NULL;
665}
666
Chris Lattner24943d22010-06-08 16:52:24 +0000667BreakpointSiteList &
668Process::GetBreakpointSiteList()
669{
670 return m_breakpoint_site_list;
671}
672
673const BreakpointSiteList &
674Process::GetBreakpointSiteList() const
675{
676 return m_breakpoint_site_list;
677}
678
679
680void
681Process::DisableAllBreakpointSites ()
682{
683 m_breakpoint_site_list.SetEnabledForAll (false);
684}
685
686Error
687Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
688{
689 Error error (DisableBreakpointSiteByID (break_id));
690
691 if (error.Success())
692 m_breakpoint_site_list.Remove(break_id);
693
694 return error;
695}
696
697Error
698Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
699{
700 Error error;
701 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
702 if (bp_site_sp)
703 {
704 if (bp_site_sp->IsEnabled())
705 error = DisableBreakpoint (bp_site_sp.get());
706 }
707 else
708 {
709 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
710 }
711
712 return error;
713}
714
715Error
716Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
717{
718 Error error;
719 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
720 if (bp_site_sp)
721 {
722 if (!bp_site_sp->IsEnabled())
723 error = EnableBreakpoint (bp_site_sp.get());
724 }
725 else
726 {
727 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
728 }
729 return error;
730}
731
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000732lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000733Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
734{
Greg Claytoneea26402010-09-14 23:36:40 +0000735 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000736 if (load_addr != LLDB_INVALID_ADDRESS)
737 {
738 BreakpointSiteSP bp_site_sp;
739
740 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
741 // create a new breakpoint site and add it.
742
743 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
744
745 if (bp_site_sp)
746 {
747 bp_site_sp->AddOwner (owner);
748 owner->SetBreakpointSite (bp_site_sp);
749 return bp_site_sp->GetID();
750 }
751 else
752 {
753 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
754 if (bp_site_sp)
755 {
756 if (EnableBreakpoint (bp_site_sp.get()).Success())
757 {
758 owner->SetBreakpointSite (bp_site_sp);
759 return m_breakpoint_site_list.Add (bp_site_sp);
760 }
761 }
762 }
763 }
764 // We failed to enable the breakpoint
765 return LLDB_INVALID_BREAK_ID;
766
767}
768
769void
770Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
771{
772 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
773 if (num_owners == 0)
774 {
775 DisableBreakpoint(bp_site_sp.get());
776 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
777 }
778}
779
780
781size_t
782Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
783{
784 size_t bytes_removed = 0;
785 addr_t intersect_addr;
786 size_t intersect_size;
787 size_t opcode_offset;
788 size_t idx;
789 BreakpointSiteSP bp;
790
791 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
792 {
793 if (bp->GetType() == BreakpointSite::eSoftware)
794 {
795 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
796 {
797 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
798 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
799 assert(opcode_offset + intersect_size <= bp->GetByteSize());
800 size_t buf_offset = intersect_addr - bp_addr;
801 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
802 }
803 }
804 }
805 return bytes_removed;
806}
807
808
809Error
810Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
811{
812 Error error;
813 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000814 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000815 const addr_t bp_addr = bp_site->GetLoadAddress();
816 if (log)
817 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
818 if (bp_site->IsEnabled())
819 {
820 if (log)
821 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
822 return error;
823 }
824
825 if (bp_addr == LLDB_INVALID_ADDRESS)
826 {
827 error.SetErrorString("BreakpointSite contains an invalid load address.");
828 return error;
829 }
830 // Ask the lldb::Process subclass to fill in the correct software breakpoint
831 // trap for the breakpoint site
832 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
833
834 if (bp_opcode_size == 0)
835 {
836 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
837 }
838 else
839 {
840 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
841
842 if (bp_opcode_bytes == NULL)
843 {
844 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
845 return error;
846 }
847
848 // Save the original opcode by reading it
849 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
850 {
851 // Write a software breakpoint in place of the original opcode
852 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
853 {
854 uint8_t verify_bp_opcode_bytes[64];
855 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
856 {
857 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
858 {
859 bp_site->SetEnabled(true);
860 bp_site->SetType (BreakpointSite::eSoftware);
861 if (log)
862 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
863 bp_site->GetID(),
864 (uint64_t)bp_addr);
865 }
866 else
867 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
868 }
869 else
870 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
871 }
872 else
873 error.SetErrorString("Unable to write breakpoint trap to memory.");
874 }
875 else
876 error.SetErrorString("Unable to read memory at breakpoint address.");
877 }
878 if (log)
879 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
880 bp_site->GetID(),
881 (uint64_t)bp_addr,
882 error.AsCString());
883 return error;
884}
885
886Error
887Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
888{
889 Error error;
890 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000891 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000892 addr_t bp_addr = bp_site->GetLoadAddress();
893 lldb::user_id_t breakID = bp_site->GetID();
894 if (log)
895 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
896
897 if (bp_site->IsHardware())
898 {
899 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
900 }
901 else if (bp_site->IsEnabled())
902 {
903 const size_t break_op_size = bp_site->GetByteSize();
904 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
905 if (break_op_size > 0)
906 {
907 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +0000908 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000909 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +0000910 bool break_op_found = false;
911
912 // Read the breakpoint opcode
913 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
914 {
915 bool verify = false;
916 // Make sure we have the a breakpoint opcode exists at this address
917 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
918 {
919 break_op_found = true;
920 // We found a valid breakpoint opcode at this address, now restore
921 // the saved opcode.
922 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
923 {
924 verify = true;
925 }
926 else
927 error.SetErrorString("Memory write failed when restoring original opcode.");
928 }
929 else
930 {
931 error.SetErrorString("Original breakpoint trap is no longer in memory.");
932 // Set verify to true and so we can check if the original opcode has already been restored
933 verify = true;
934 }
935
936 if (verify)
937 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000938 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000939 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +0000940 // Verify that our original opcode made it back to the inferior
941 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
942 {
943 // compare the memory we just read with the original opcode
944 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
945 {
946 // SUCCESS
947 bp_site->SetEnabled(false);
948 if (log)
949 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
950 return error;
951 }
952 else
953 {
954 if (break_op_found)
955 error.SetErrorString("Failed to restore original opcode.");
956 }
957 }
958 else
959 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
960 }
961 }
962 else
963 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
964 }
965 }
966 else
967 {
968 if (log)
969 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
970 return error;
971 }
972
973 if (log)
974 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
975 bp_site->GetID(),
976 (uint64_t)bp_addr,
977 error.AsCString());
978 return error;
979
980}
981
982
983size_t
984Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
985{
986 if (buf == NULL || size == 0)
987 return 0;
988
989 size_t bytes_read = 0;
990 uint8_t *bytes = (uint8_t *)buf;
991
992 while (bytes_read < size)
993 {
994 const size_t curr_size = size - bytes_read;
995 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
996 bytes + bytes_read,
997 curr_size,
998 error);
999 bytes_read += curr_bytes_read;
1000 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1001 break;
1002 }
1003
1004 // Replace any software breakpoint opcodes that fall into this range back
1005 // into "buf" before we return
1006 if (bytes_read > 0)
1007 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1008 return bytes_read;
1009}
1010
1011size_t
1012Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1013{
1014 size_t bytes_written = 0;
1015 const uint8_t *bytes = (const uint8_t *)buf;
1016
1017 while (bytes_written < size)
1018 {
1019 const size_t curr_size = size - bytes_written;
1020 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1021 bytes + bytes_written,
1022 curr_size,
1023 error);
1024 bytes_written += curr_bytes_written;
1025 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1026 break;
1027 }
1028 return bytes_written;
1029}
1030
1031size_t
1032Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1033{
1034 if (buf == NULL || size == 0)
1035 return 0;
1036 // We need to write any data that would go where any current software traps
1037 // (enabled software breakpoints) any software traps (breakpoints) that we
1038 // may have placed in our tasks memory.
1039
1040 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1041 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1042
1043 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1044 return DoWriteMemory(addr, buf, size, error);
1045
1046 BreakpointSiteList::collection::const_iterator pos;
1047 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001048 addr_t intersect_addr = 0;
1049 size_t intersect_size = 0;
1050 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001051 const uint8_t *ubuf = (const uint8_t *)buf;
1052
1053 for (pos = iter; pos != end; ++pos)
1054 {
1055 BreakpointSiteSP bp;
1056 bp = pos->second;
1057
1058 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1059 assert(addr <= intersect_addr && intersect_addr < addr + size);
1060 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1061 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1062
1063 // Check for bytes before this breakpoint
1064 const addr_t curr_addr = addr + bytes_written;
1065 if (intersect_addr > curr_addr)
1066 {
1067 // There are some bytes before this breakpoint that we need to
1068 // just write to memory
1069 size_t curr_size = intersect_addr - curr_addr;
1070 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1071 ubuf + bytes_written,
1072 curr_size,
1073 error);
1074 bytes_written += curr_bytes_written;
1075 if (curr_bytes_written != curr_size)
1076 {
1077 // We weren't able to write all of the requested bytes, we
1078 // are done looping and will return the number of bytes that
1079 // we have written so far.
1080 break;
1081 }
1082 }
1083
1084 // Now write any bytes that would cover up any software breakpoints
1085 // directly into the breakpoint opcode buffer
1086 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1087 bytes_written += intersect_size;
1088 }
1089
1090 // Write any remaining bytes after the last breakpoint if we have any left
1091 if (bytes_written < size)
1092 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1093 ubuf + bytes_written,
1094 size - bytes_written,
1095 error);
1096
1097 return bytes_written;
1098}
1099
1100addr_t
1101Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1102{
1103 // Fixme: we should track the blocks we've allocated, and clean them up...
1104 // We could even do our own allocator here if that ends up being more efficient.
1105 return DoAllocateMemory (size, permissions, error);
1106}
1107
1108Error
1109Process::DeallocateMemory (addr_t ptr)
1110{
1111 return DoDeallocateMemory (ptr);
1112}
1113
1114
1115Error
1116Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1117{
1118 Error error;
1119 error.SetErrorString("watchpoints are not supported");
1120 return error;
1121}
1122
1123Error
1124Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1125{
1126 Error error;
1127 error.SetErrorString("watchpoints are not supported");
1128 return error;
1129}
1130
1131StateType
1132Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1133{
1134 StateType state;
1135 // Now wait for the process to launch and return control to us, and then
1136 // call DidLaunch:
1137 while (1)
1138 {
1139 // FIXME: Might want to put a timeout in here:
1140 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1141 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1142 break;
1143 else
1144 HandlePrivateEvent (event_sp);
1145 }
1146 return state;
1147}
1148
1149Error
1150Process::Launch
1151(
1152 char const *argv[],
1153 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001154 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001155 const char *stdin_path,
1156 const char *stdout_path,
1157 const char *stderr_path
1158)
1159{
1160 Error error;
1161 m_target_triple.Clear();
1162 m_abi_sp.reset();
1163
1164 Module *exe_module = m_target.GetExecutableModule().get();
1165 if (exe_module)
1166 {
1167 char exec_file_path[PATH_MAX];
1168 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1169 if (exe_module->GetFileSpec().Exists())
1170 {
1171 error = WillLaunch (exe_module);
1172 if (error.Success())
1173 {
Greg Claytond8c62532010-10-07 04:19:01 +00001174 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001175 // The args coming in should not contain the application name, the
1176 // lldb_private::Process class will add this in case the executable
1177 // gets resolved to a different file than was given on the command
1178 // line (like when an applicaiton bundle is specified and will
1179 // resolve to the contained exectuable file, or the file given was
1180 // a symlink or other file system link that resolves to a different
1181 // file).
1182
1183 // Get the resolved exectuable path
1184
1185 // Make a new argument vector
1186 std::vector<const char *> exec_path_plus_argv;
1187 // Append the resolved executable path
1188 exec_path_plus_argv.push_back (exec_file_path);
1189
1190 // Push all args if there are any
1191 if (argv)
1192 {
1193 for (int i = 0; argv[i]; ++i)
1194 exec_path_plus_argv.push_back(argv[i]);
1195 }
1196
1197 // Push a NULL to terminate the args.
1198 exec_path_plus_argv.push_back(NULL);
1199
1200 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001201 error = DoLaunch (exe_module,
1202 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1203 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001204 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001205 stdin_path,
1206 stdout_path,
1207 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001208
1209 if (error.Fail())
1210 {
1211 if (GetID() != LLDB_INVALID_PROCESS_ID)
1212 {
1213 SetID (LLDB_INVALID_PROCESS_ID);
1214 const char *error_string = error.AsCString();
1215 if (error_string == NULL)
1216 error_string = "launch failed";
1217 SetExitStatus (-1, error_string);
1218 }
1219 }
1220 else
1221 {
1222 EventSP event_sp;
1223 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1224
1225 if (state == eStateStopped || state == eStateCrashed)
1226 {
1227 DidLaunch ();
1228
1229 // This delays passing the stopped event to listeners till DidLaunch gets
1230 // a chance to complete...
1231 HandlePrivateEvent (event_sp);
1232 StartPrivateStateThread ();
1233 }
1234 else if (state == eStateExited)
1235 {
1236 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1237 // not likely to work, and return an invalid pid.
1238 HandlePrivateEvent (event_sp);
1239 }
1240 }
1241 }
1242 }
1243 else
1244 {
1245 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1246 }
1247 }
1248 return error;
1249}
1250
1251Error
1252Process::CompleteAttach ()
1253{
1254 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001255
1256 if (GetID() == LLDB_INVALID_PROCESS_ID)
1257 {
1258 error.SetErrorString("no process");
1259 }
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261 EventSP event_sp;
1262 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1263 if (state == eStateStopped || state == eStateCrashed)
1264 {
1265 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001266 // Figure out which one is the executable, and set that in our target:
1267 ModuleList &modules = GetTarget().GetImages();
1268
1269 size_t num_modules = modules.GetSize();
1270 for (int i = 0; i < num_modules; i++)
1271 {
1272 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1273 if (module_sp->IsExecutable())
1274 {
1275 ModuleSP exec_module = GetTarget().GetExecutableModule();
1276 if (!exec_module || exec_module != module_sp)
1277 {
1278
1279 GetTarget().SetExecutableModule (module_sp, false);
1280 }
1281 break;
1282 }
1283 }
Chris Lattner24943d22010-06-08 16:52:24 +00001284
1285 // This delays passing the stopped event to listeners till DidLaunch gets
1286 // a chance to complete...
1287 HandlePrivateEvent(event_sp);
1288 StartPrivateStateThread();
1289 }
1290 else
1291 {
1292 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1293 // not likely to work, and return an invalid pid.
1294 if (state == eStateExited)
1295 HandlePrivateEvent (event_sp);
1296 error.SetErrorStringWithFormat("invalid state after attach: %s",
1297 lldb_private::StateAsCString(state));
1298 }
1299 return error;
1300}
1301
1302Error
1303Process::Attach (lldb::pid_t attach_pid)
1304{
1305
1306 m_target_triple.Clear();
1307 m_abi_sp.reset();
1308
Jim Ingham7508e732010-08-09 23:31:02 +00001309 // Find the process and its architecture. Make sure it matches the architecture
1310 // of the current Target, and if not adjust it.
1311
1312 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1313 if (attach_spec != GetTarget().GetArchitecture())
1314 {
1315 // Set the architecture on the target.
1316 GetTarget().SetArchitecture(attach_spec);
1317 }
1318
Greg Clayton54e7afa2010-07-09 20:39:50 +00001319 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001320 if (error.Success())
1321 {
Greg Claytond8c62532010-10-07 04:19:01 +00001322 SetPublicState (eStateAttaching);
1323
Greg Clayton54e7afa2010-07-09 20:39:50 +00001324 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001325 if (error.Success())
1326 {
1327 error = CompleteAttach();
1328 }
1329 else
1330 {
1331 if (GetID() != LLDB_INVALID_PROCESS_ID)
1332 {
1333 SetID (LLDB_INVALID_PROCESS_ID);
1334 const char *error_string = error.AsCString();
1335 if (error_string == NULL)
1336 error_string = "attach failed";
1337
1338 SetExitStatus(-1, error_string);
1339 }
1340 }
1341 }
1342 return error;
1343}
1344
1345Error
1346Process::Attach (const char *process_name, bool wait_for_launch)
1347{
1348 m_target_triple.Clear();
1349 m_abi_sp.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001350
1351 // Find the process and its architecture. Make sure it matches the architecture
1352 // of the current Target, and if not adjust it.
1353
Jim Inghamea294182010-08-17 21:54:19 +00001354 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001355 {
Jim Inghamea294182010-08-17 21:54:19 +00001356 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001357 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001358 {
1359 // Set the architecture on the target.
1360 GetTarget().SetArchitecture(attach_spec);
1361 }
Jim Ingham7508e732010-08-09 23:31:02 +00001362 }
Jim Inghamea294182010-08-17 21:54:19 +00001363
Greg Clayton54e7afa2010-07-09 20:39:50 +00001364 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001365 if (error.Success())
1366 {
Greg Claytond8c62532010-10-07 04:19:01 +00001367 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001368 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001369 if (error.Fail())
1370 {
1371 if (GetID() != LLDB_INVALID_PROCESS_ID)
1372 {
1373 SetID (LLDB_INVALID_PROCESS_ID);
1374 const char *error_string = error.AsCString();
1375 if (error_string == NULL)
1376 error_string = "attach failed";
1377
1378 SetExitStatus(-1, error_string);
1379 }
1380 }
1381 else
1382 {
1383 error = CompleteAttach();
1384 }
1385 }
1386 return error;
1387}
1388
1389Error
1390Process::Resume ()
1391{
Greg Claytone005f2c2010-11-06 01:53:30 +00001392 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001393 if (log)
1394 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1395
1396 Error error (WillResume());
1397 // Tell the process it is about to resume before the thread list
1398 if (error.Success())
1399 {
1400 // Now let the thread list know we are about to resume to it
1401 // can let all of our threads know that they are about to be
1402 // resumed. Threads will each be called with
1403 // Thread::WillResume(StateType) where StateType contains the state
1404 // that they are supposed to have when the process is resumed
1405 // (suspended/running/stepping). Threads should also check
1406 // their resume signal in lldb::Thread::GetResumeSignal()
1407 // to see if they are suppoed to start back up with a signal.
1408 if (m_thread_list.WillResume())
1409 {
1410 error = DoResume();
1411 if (error.Success())
1412 {
1413 DidResume();
1414 m_thread_list.DidResume();
1415 }
1416 }
1417 else
1418 {
1419 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1420 }
1421 }
1422 return error;
1423}
1424
1425Error
1426Process::Halt ()
1427{
1428 Error error (WillHalt());
1429
1430 if (error.Success())
1431 {
1432 error = DoHalt();
1433 if (error.Success())
1434 DidHalt();
1435 }
1436 return error;
1437}
1438
1439Error
1440Process::Detach ()
1441{
1442 Error error (WillDetach());
1443
1444 if (error.Success())
1445 {
1446 DisableAllBreakpointSites();
1447 error = DoDetach();
1448 if (error.Success())
1449 {
1450 DidDetach();
1451 StopPrivateStateThread();
1452 }
1453 }
1454 return error;
1455}
1456
1457Error
1458Process::Destroy ()
1459{
1460 Error error (WillDestroy());
1461 if (error.Success())
1462 {
1463 DisableAllBreakpointSites();
1464 error = DoDestroy();
1465 if (error.Success())
1466 {
1467 DidDestroy();
1468 StopPrivateStateThread();
1469 }
1470 }
1471 return error;
1472}
1473
1474Error
1475Process::Signal (int signal)
1476{
1477 Error error (WillSignal());
1478 if (error.Success())
1479 {
1480 error = DoSignal(signal);
1481 if (error.Success())
1482 DidSignal();
1483 }
1484 return error;
1485}
1486
1487UnixSignals &
1488Process::GetUnixSignals ()
1489{
1490 return m_unix_signals;
1491}
1492
1493Target &
1494Process::GetTarget ()
1495{
1496 return m_target;
1497}
1498
1499const Target &
1500Process::GetTarget () const
1501{
1502 return m_target;
1503}
1504
1505uint32_t
1506Process::GetAddressByteSize()
1507{
1508 return m_target.GetArchitecture().GetAddressByteSize();
1509}
1510
1511bool
1512Process::ShouldBroadcastEvent (Event *event_ptr)
1513{
1514 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1515 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001516 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001517
1518 switch (state)
1519 {
1520 case eStateAttaching:
1521 case eStateLaunching:
1522 case eStateDetached:
1523 case eStateExited:
1524 case eStateUnloaded:
1525 // These events indicate changes in the state of the debugging session, always report them.
1526 return_value = true;
1527 break;
1528 case eStateInvalid:
1529 // We stopped for no apparent reason, don't report it.
1530 return_value = false;
1531 break;
1532 case eStateRunning:
1533 case eStateStepping:
1534 // If we've started the target running, we handle the cases where we
1535 // are already running and where there is a transition from stopped to
1536 // running differently.
1537 // running -> running: Automatically suppress extra running events
1538 // stopped -> running: Report except when there is one or more no votes
1539 // and no yes votes.
1540 SynchronouslyNotifyStateChanged (state);
1541 switch (m_public_state.GetValue())
1542 {
1543 case eStateRunning:
1544 case eStateStepping:
1545 // We always suppress multiple runnings with no PUBLIC stop in between.
1546 return_value = false;
1547 break;
1548 default:
1549 // TODO: make this work correctly. For now always report
1550 // run if we aren't running so we don't miss any runnning
1551 // events. If I run the lldb/test/thread/a.out file and
1552 // break at main.cpp:58, run and hit the breakpoints on
1553 // multiple threads, then somehow during the stepping over
1554 // of all breakpoints no run gets reported.
1555 return_value = true;
1556
1557 // This is a transition from stop to run.
1558 switch (m_thread_list.ShouldReportRun (event_ptr))
1559 {
1560 case eVoteYes:
1561 case eVoteNoOpinion:
1562 return_value = true;
1563 break;
1564 case eVoteNo:
1565 return_value = false;
1566 break;
1567 }
1568 break;
1569 }
1570 break;
1571 case eStateStopped:
1572 case eStateCrashed:
1573 case eStateSuspended:
1574 {
1575 // We've stopped. First see if we're going to restart the target.
1576 // If we are going to stop, then we always broadcast the event.
1577 // 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 +00001578 // If no thread has an opinion, we don't report it.
Chris Lattner24943d22010-06-08 16:52:24 +00001579 if (state != eStateInvalid)
1580 {
1581
1582 RefreshStateAfterStop ();
1583
1584 if (m_thread_list.ShouldStop (event_ptr) == false)
1585 {
1586 switch (m_thread_list.ShouldReportStop (event_ptr))
1587 {
1588 case eVoteYes:
1589 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001590 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001591 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001592 case eVoteNo:
1593 return_value = false;
1594 break;
1595 }
1596
1597 if (log)
1598 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state));
1599 Resume ();
1600 }
1601 else
1602 {
1603 return_value = true;
1604 SynchronouslyNotifyStateChanged (state);
1605 }
1606 }
1607 }
1608 }
1609
1610 if (log)
1611 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1612 return return_value;
1613}
1614
1615//------------------------------------------------------------------
1616// Thread Queries
1617//------------------------------------------------------------------
1618
1619ThreadList &
1620Process::GetThreadList ()
1621{
1622 return m_thread_list;
1623}
1624
1625const ThreadList &
1626Process::GetThreadList () const
1627{
1628 return m_thread_list;
1629}
1630
1631
1632bool
1633Process::StartPrivateStateThread ()
1634{
Greg Claytone005f2c2010-11-06 01:53:30 +00001635 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001636
1637 if (log)
1638 log->Printf ("Process::%s ( )", __FUNCTION__);
1639
1640 // Create a thread that watches our internal state and controls which
1641 // events make it to clients (into the DCProcess event queue).
1642 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1643 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1644}
1645
1646void
1647Process::PausePrivateStateThread ()
1648{
1649 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1650}
1651
1652void
1653Process::ResumePrivateStateThread ()
1654{
1655 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1656}
1657
1658void
1659Process::StopPrivateStateThread ()
1660{
1661 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1662}
1663
1664void
1665Process::ControlPrivateStateThread (uint32_t signal)
1666{
Greg Claytone005f2c2010-11-06 01:53:30 +00001667 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001668
1669 assert (signal == eBroadcastInternalStateControlStop ||
1670 signal == eBroadcastInternalStateControlPause ||
1671 signal == eBroadcastInternalStateControlResume);
1672
1673 if (log)
1674 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1675
1676 // Signal the private state thread
1677 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1678 {
1679 TimeValue timeout_time;
1680 bool timed_out;
1681
1682 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1683
1684 timeout_time = TimeValue::Now();
1685 timeout_time.OffsetWithSeconds(2);
1686 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1687 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1688
1689 if (signal == eBroadcastInternalStateControlStop)
1690 {
1691 if (timed_out)
1692 Host::ThreadCancel (m_private_state_thread, NULL);
1693
1694 thread_result_t result = NULL;
1695 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00001696 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001697 }
1698 }
1699}
1700
1701void
1702Process::HandlePrivateEvent (EventSP &event_sp)
1703{
Greg Claytone005f2c2010-11-06 01:53:30 +00001704 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001705 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1706 // See if we should broadcast this state to external clients?
1707 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1708 if (log)
1709 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1710
1711 if (should_broadcast)
1712 {
1713 if (log)
1714 {
1715 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1716 }
1717 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1718 BroadcastEvent (event_sp);
1719 }
1720 else
1721 {
1722 if (log)
1723 {
1724 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1725 }
1726 }
1727}
1728
1729void *
1730Process::PrivateStateThread (void *arg)
1731{
1732 Process *proc = static_cast<Process*> (arg);
1733 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001734 return result;
1735}
1736
1737void *
1738Process::RunPrivateStateThread ()
1739{
1740 bool control_only = false;
1741 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1742
Greg Claytone005f2c2010-11-06 01:53:30 +00001743 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001744 if (log)
1745 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1746
1747 bool exit_now = false;
1748 while (!exit_now)
1749 {
1750 EventSP event_sp;
1751 WaitForEventsPrivate (NULL, event_sp, control_only);
1752 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1753 {
1754 switch (event_sp->GetType())
1755 {
1756 case eBroadcastInternalStateControlStop:
1757 exit_now = true;
1758 continue; // Go to next loop iteration so we exit without
1759 break; // doing any internal state managment below
1760
1761 case eBroadcastInternalStateControlPause:
1762 control_only = true;
1763 break;
1764
1765 case eBroadcastInternalStateControlResume:
1766 control_only = false;
1767 break;
1768 }
1769 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1770 }
1771
1772
1773 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1774
1775 if (internal_state != eStateInvalid)
1776 {
1777 HandlePrivateEvent (event_sp);
1778 }
1779
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001780 if (internal_state == eStateInvalid ||
1781 internal_state == eStateExited ||
1782 internal_state == eStateDetached )
Chris Lattner24943d22010-06-08 16:52:24 +00001783 break;
1784 }
1785
Caroline Tice926060e2010-10-29 21:48:37 +00001786 // Verify log is still enabled before attempting to write to it...
1787 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001788 if (log)
1789 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1790
Greg Clayton8b4c16e2010-08-19 21:50:06 +00001791 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001792 return NULL;
1793}
1794
Chris Lattner24943d22010-06-08 16:52:24 +00001795//------------------------------------------------------------------
1796// Process Event Data
1797//------------------------------------------------------------------
1798
1799Process::ProcessEventData::ProcessEventData () :
1800 EventData (),
1801 m_process_sp (),
1802 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001803 m_restarted (false),
1804 m_update_state (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001805{
1806}
1807
1808Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1809 EventData (),
1810 m_process_sp (process_sp),
1811 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001812 m_restarted (false),
1813 m_update_state (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001814{
1815}
1816
1817Process::ProcessEventData::~ProcessEventData()
1818{
1819}
1820
1821const ConstString &
1822Process::ProcessEventData::GetFlavorString ()
1823{
1824 static ConstString g_flavor ("Process::ProcessEventData");
1825 return g_flavor;
1826}
1827
1828const ConstString &
1829Process::ProcessEventData::GetFlavor () const
1830{
1831 return ProcessEventData::GetFlavorString ();
1832}
1833
1834const ProcessSP &
1835Process::ProcessEventData::GetProcessSP () const
1836{
1837 return m_process_sp;
1838}
1839
1840StateType
1841Process::ProcessEventData::GetState () const
1842{
1843 return m_state;
1844}
1845
1846bool
1847Process::ProcessEventData::GetRestarted () const
1848{
1849 return m_restarted;
1850}
1851
1852void
1853Process::ProcessEventData::SetRestarted (bool new_value)
1854{
1855 m_restarted = new_value;
1856}
1857
1858void
1859Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1860{
1861 // This function gets called twice for each event, once when the event gets pulled
1862 // off of the private process event queue, and once when it gets pulled off of
1863 // the public event queue. m_update_state is used to distinguish these
1864 // two cases; it is false when we're just pulling it off for private handling,
1865 // and we don't want to do the breakpoint command handling then.
1866
1867 if (!m_update_state)
1868 return;
1869
1870 m_process_sp->SetPublicState (m_state);
1871
1872 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1873 if (m_state == eStateStopped && ! m_restarted)
1874 {
1875 int num_threads = m_process_sp->GetThreadList().GetSize();
1876 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00001877
Chris Lattner24943d22010-06-08 16:52:24 +00001878 for (idx = 0; idx < num_threads; ++idx)
1879 {
1880 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1881
Jim Ingham6297a3a2010-10-20 00:39:53 +00001882 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
1883 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001884 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00001885 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00001886 }
1887 }
Greg Clayton643ee732010-08-04 01:40:35 +00001888
Jim Ingham6fb8baa2010-08-10 00:59:59 +00001889 // The stop action might restart the target. If it does, then we want to mark that in the
1890 // event so that whoever is receiving it will know to wait for the running event and reflect
1891 // that state appropriately.
1892
Chris Lattner24943d22010-06-08 16:52:24 +00001893 if (m_process_sp->GetPrivateState() == eStateRunning)
1894 SetRestarted(true);
1895 }
1896}
1897
1898void
1899Process::ProcessEventData::Dump (Stream *s) const
1900{
1901 if (m_process_sp)
1902 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1903
1904 s->Printf("state = %s", StateAsCString(GetState()));;
1905}
1906
1907const Process::ProcessEventData *
1908Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1909{
1910 if (event_ptr)
1911 {
1912 const EventData *event_data = event_ptr->GetData();
1913 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1914 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1915 }
1916 return NULL;
1917}
1918
1919ProcessSP
1920Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
1921{
1922 ProcessSP process_sp;
1923 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1924 if (data)
1925 process_sp = data->GetProcessSP();
1926 return process_sp;
1927}
1928
1929StateType
1930Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
1931{
1932 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1933 if (data == NULL)
1934 return eStateInvalid;
1935 else
1936 return data->GetState();
1937}
1938
1939bool
1940Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
1941{
1942 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1943 if (data == NULL)
1944 return false;
1945 else
1946 return data->GetRestarted();
1947}
1948
1949void
1950Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
1951{
1952 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1953 if (data != NULL)
1954 data->SetRestarted(new_value);
1955}
1956
1957bool
1958Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
1959{
1960 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1961 if (data)
1962 {
1963 data->SetUpdateStateOnRemoval();
1964 return true;
1965 }
1966 return false;
1967}
1968
1969void
1970Process::ProcessEventData::SetUpdateStateOnRemoval()
1971{
1972 m_update_state = true;
1973}
1974
1975Target *
1976Process::CalculateTarget ()
1977{
1978 return &m_target;
1979}
1980
1981Process *
1982Process::CalculateProcess ()
1983{
1984 return this;
1985}
1986
1987Thread *
1988Process::CalculateThread ()
1989{
1990 return NULL;
1991}
1992
1993StackFrame *
1994Process::CalculateStackFrame ()
1995{
1996 return NULL;
1997}
1998
1999void
Greg Claytona830adb2010-10-04 01:05:56 +00002000Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002001{
2002 exe_ctx.target = &m_target;
2003 exe_ctx.process = this;
2004 exe_ctx.thread = NULL;
2005 exe_ctx.frame = NULL;
2006}
2007
2008lldb::ProcessSP
2009Process::GetSP ()
2010{
2011 return GetTarget().GetProcessSP();
2012}
2013
Sean Callanana48fe162010-08-11 03:57:18 +00002014ClangPersistentVariables &
2015Process::GetPersistentVariables()
2016{
2017 return m_persistent_vars;
2018}
2019
Jim Ingham7508e732010-08-09 23:31:02 +00002020uint32_t
2021Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2022{
2023 return 0;
2024}
2025
2026ArchSpec
2027Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2028{
2029 return Host::GetArchSpecForExistingProcess (pid);
2030}
2031
2032ArchSpec
2033Process::GetArchSpecForExistingProcess (const char *process_name)
2034{
2035 return Host::GetArchSpecForExistingProcess (process_name);
2036}
2037
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002038lldb::UserSettingsControllerSP
2039Process::GetSettingsController (bool finish)
2040{
Greg Claytond0a5a232010-09-19 02:33:57 +00002041 static UserSettingsControllerSP g_settings_controller (new SettingsController);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002042 static bool initialized = false;
2043
2044 if (!initialized)
2045 {
Jim Ingham7ac83bd2010-09-07 20:27:09 +00002046 initialized = UserSettingsController::InitializeSettingsController (g_settings_controller,
Greg Claytond0a5a232010-09-19 02:33:57 +00002047 Process::SettingsController::global_settings_table,
2048 Process::SettingsController::instance_settings_table);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002049 }
2050
2051 if (finish)
2052 {
Jim Ingham7ac83bd2010-09-07 20:27:09 +00002053 UserSettingsController::FinalizeSettingsController (g_settings_controller);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002054 g_settings_controller.reset();
Jim Ingham7ac83bd2010-09-07 20:27:09 +00002055 initialized = false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002056 }
2057
2058 return g_settings_controller;
2059}
2060
Caroline Tice1ebef442010-09-27 00:30:10 +00002061void
2062Process::UpdateInstanceName ()
2063{
2064 ModuleSP module_sp = GetTarget().GetExecutableModule();
2065 if (module_sp)
2066 {
2067 StreamString sstr;
2068 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2069
2070 Process::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
2071 sstr.GetData());
2072 }
2073}
2074
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002075//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002076// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002077//--------------------------------------------------------------
2078
Greg Claytond0a5a232010-09-19 02:33:57 +00002079Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002080 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002081{
Caroline Tice004afcb2010-09-08 17:48:55 +00002082 m_default_settings.reset (new ProcessInstanceSettings (*this, false,
2083 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002084}
2085
Greg Claytond0a5a232010-09-19 02:33:57 +00002086Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002087{
2088}
2089
2090lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002091Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002092{
Caroline Tice004afcb2010-09-08 17:48:55 +00002093 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*(Process::GetSettingsController().get()),
2094 false, instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002095 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2096 return new_settings_sp;
2097}
2098
2099//--------------------------------------------------------------
2100// class ProcessInstanceSettings
2101//--------------------------------------------------------------
2102
Caroline Tice004afcb2010-09-08 17:48:55 +00002103ProcessInstanceSettings::ProcessInstanceSettings (UserSettingsController &owner, bool live_instance,
2104 const char *name) :
Caroline Tice75b11a32010-09-16 19:05:55 +00002105 InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002106 m_run_args (),
2107 m_env_vars (),
2108 m_input_path (),
2109 m_output_path (),
2110 m_error_path (),
2111 m_plugin (),
2112 m_disable_aslr (true)
2113{
Caroline Tice396704b2010-09-09 18:26:37 +00002114 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2115 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2116 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00002117 // This is true for CreateInstanceName() too.
2118
2119 if (GetInstanceName () == InstanceSettings::InvalidName())
2120 {
2121 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2122 m_owner.RegisterInstanceSettings (this);
2123 }
Caroline Tice396704b2010-09-09 18:26:37 +00002124
2125 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002126 {
2127 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2128 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002129 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002130 }
2131}
2132
2133ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
2134 InstanceSettings (*(Process::GetSettingsController().get()), CreateInstanceName().AsCString()),
2135 m_run_args (rhs.m_run_args),
2136 m_env_vars (rhs.m_env_vars),
2137 m_input_path (rhs.m_input_path),
2138 m_output_path (rhs.m_output_path),
2139 m_error_path (rhs.m_error_path),
2140 m_plugin (rhs.m_plugin),
2141 m_disable_aslr (rhs.m_disable_aslr)
2142{
2143 if (m_instance_name != InstanceSettings::GetDefaultName())
2144 {
2145 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2146 CopyInstanceSettings (pending_settings,false);
2147 m_owner.RemovePendingSettings (m_instance_name);
2148 }
2149}
2150
2151ProcessInstanceSettings::~ProcessInstanceSettings ()
2152{
2153}
2154
2155ProcessInstanceSettings&
2156ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2157{
2158 if (this != &rhs)
2159 {
2160 m_run_args = rhs.m_run_args;
2161 m_env_vars = rhs.m_env_vars;
2162 m_input_path = rhs.m_input_path;
2163 m_output_path = rhs.m_output_path;
2164 m_error_path = rhs.m_error_path;
2165 m_plugin = rhs.m_plugin;
2166 m_disable_aslr = rhs.m_disable_aslr;
2167 }
2168
2169 return *this;
2170}
2171
2172
2173void
2174ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2175 const char *index_value,
2176 const char *value,
2177 const ConstString &instance_name,
2178 const SettingEntry &entry,
2179 lldb::VarSetOperationType op,
2180 Error &err,
2181 bool pending)
2182{
2183 if (var_name == RunArgsVarName())
2184 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2185 else if (var_name == EnvVarsVarName())
2186 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2187 else if (var_name == InputPathVarName())
2188 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2189 else if (var_name == OutputPathVarName())
2190 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2191 else if (var_name == ErrorPathVarName())
2192 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2193 else if (var_name == PluginVarName())
2194 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
2195 else if (var_name == DisableASLRVarName())
2196 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
2197}
2198
2199void
2200ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2201 bool pending)
2202{
2203 if (new_settings.get() == NULL)
2204 return;
2205
2206 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2207
2208 m_run_args = new_process_settings->m_run_args;
2209 m_env_vars = new_process_settings->m_env_vars;
2210 m_input_path = new_process_settings->m_input_path;
2211 m_output_path = new_process_settings->m_output_path;
2212 m_error_path = new_process_settings->m_error_path;
2213 m_plugin = new_process_settings->m_plugin;
2214 m_disable_aslr = new_process_settings->m_disable_aslr;
2215}
2216
Caroline Ticebcb5b452010-09-20 21:37:42 +00002217bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002218ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2219 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00002220 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00002221 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002222{
2223 if (var_name == RunArgsVarName())
2224 {
2225 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00002226 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002227 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2228 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00002229 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002230 }
2231 else if (var_name == EnvVarsVarName())
2232 {
2233 if (m_env_vars.size() > 0)
2234 {
2235 std::map<std::string, std::string>::iterator pos;
2236 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2237 {
2238 StreamString value_str;
2239 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2240 value.AppendString (value_str.GetData());
2241 }
2242 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002243 }
2244 else if (var_name == InputPathVarName())
2245 {
2246 value.AppendString (m_input_path.c_str());
2247 }
2248 else if (var_name == OutputPathVarName())
2249 {
2250 value.AppendString (m_output_path.c_str());
2251 }
2252 else if (var_name == ErrorPathVarName())
2253 {
2254 value.AppendString (m_error_path.c_str());
2255 }
2256 else if (var_name == PluginVarName())
2257 {
2258 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2259 }
2260 else if (var_name == DisableASLRVarName())
2261 {
2262 if (m_disable_aslr)
2263 value.AppendString ("true");
2264 else
2265 value.AppendString ("false");
2266 }
2267 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00002268 {
2269 if (err)
2270 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2271 return false;
2272 }
2273 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002274}
2275
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002276const ConstString
2277ProcessInstanceSettings::CreateInstanceName ()
2278{
2279 static int instance_count = 1;
2280 StreamString sstr;
2281
2282 sstr.Printf ("process_%d", instance_count);
2283 ++instance_count;
2284
2285 const ConstString ret_val (sstr.GetData());
2286 return ret_val;
2287}
2288
2289const ConstString &
2290ProcessInstanceSettings::RunArgsVarName ()
2291{
2292 static ConstString run_args_var_name ("run-args");
2293
2294 return run_args_var_name;
2295}
2296
2297const ConstString &
2298ProcessInstanceSettings::EnvVarsVarName ()
2299{
2300 static ConstString env_vars_var_name ("env-vars");
2301
2302 return env_vars_var_name;
2303}
2304
2305const ConstString &
2306ProcessInstanceSettings::InputPathVarName ()
2307{
2308 static ConstString input_path_var_name ("input-path");
2309
2310 return input_path_var_name;
2311}
2312
2313const ConstString &
2314ProcessInstanceSettings::OutputPathVarName ()
2315{
Caroline Tice87097232010-09-07 18:35:40 +00002316 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002317
2318 return output_path_var_name;
2319}
2320
2321const ConstString &
2322ProcessInstanceSettings::ErrorPathVarName ()
2323{
Caroline Tice87097232010-09-07 18:35:40 +00002324 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002325
2326 return error_path_var_name;
2327}
2328
2329const ConstString &
2330ProcessInstanceSettings::PluginVarName ()
2331{
2332 static ConstString plugin_var_name ("plugin");
2333
2334 return plugin_var_name;
2335}
2336
2337
2338const ConstString &
2339ProcessInstanceSettings::DisableASLRVarName ()
2340{
2341 static ConstString disable_aslr_var_name ("disable-aslr");
2342
2343 return disable_aslr_var_name;
2344}
2345
2346
2347//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002348// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002349//--------------------------------------------------
2350
2351SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002352Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002353{
2354 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2355 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2356};
2357
2358
2359lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00002360Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002361{
Caroline Ticef2c330d2010-09-09 18:01:59 +00002362 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2363 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2364 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002365};
2366
2367SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002368Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002369{
2370 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2371 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2372 { "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." },
2373 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2374 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2375 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2376 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
Jim Ingham745ac7a2010-11-11 19:26:09 +00002377 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002378 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2379};
2380
2381
Jim Ingham7508e732010-08-09 23:31:02 +00002382