blob: b025970a477f0af4ad2f5da154bbdffa0f464754 [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"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
40Process*
41Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
42{
43 ProcessCreateInstance create_callback = NULL;
44 if (plugin_name)
45 {
46 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
47 if (create_callback)
48 {
49 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
50 if (debugger_ap->CanDebug(target))
51 return debugger_ap.release();
52 }
53 }
54 else
55 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000056 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +000057 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000058 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
59 if (debugger_ap->CanDebug(target))
60 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +000061 }
62 }
63 return NULL;
64}
65
66
67//----------------------------------------------------------------------
68// Process constructor
69//----------------------------------------------------------------------
70Process::Process(Target &target, Listener &listener) :
71 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +000072 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +000073 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +000074 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +000075 m_public_state (eStateUnloaded),
76 m_private_state (eStateUnloaded),
77 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
78 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
79 m_private_state_listener ("lldb.process.internal_state_listener"),
80 m_private_state_control_wait(),
81 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
82 m_stop_id (0),
83 m_thread_index_id (0),
84 m_exit_status (-1),
85 m_exit_string (),
86 m_thread_list (this),
87 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +000088 m_image_tokens (),
89 m_listener (listener),
90 m_breakpoint_site_list (),
91 m_persistent_vars (),
92 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +000093 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +000094 m_target_triple (),
95 m_byte_order (eByteOrderHost),
96 m_addr_byte_size (0),
97 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +000098 m_process_input_reader (),
99 m_stdio_communication ("lldb.process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000100 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Caroline Tice861efb32010-11-16 05:07:41 +0000101 m_stdout_data ()
Chris Lattner24943d22010-06-08 16:52:24 +0000102{
Caroline Tice1ebef442010-09-27 00:30:10 +0000103 UpdateInstanceName();
104
Greg Claytone005f2c2010-11-06 01:53:30 +0000105 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000106 if (log)
107 log->Printf ("%p Process::Process()", this);
108
Greg Clayton49ce6822010-10-31 03:01:06 +0000109 SetEventName (eBroadcastBitStateChanged, "state-changed");
110 SetEventName (eBroadcastBitInterrupt, "interrupt");
111 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
112 SetEventName (eBroadcastBitSTDERR, "stderr-available");
113
Chris Lattner24943d22010-06-08 16:52:24 +0000114 listener.StartListeningForEvents (this,
115 eBroadcastBitStateChanged |
116 eBroadcastBitInterrupt |
117 eBroadcastBitSTDOUT |
118 eBroadcastBitSTDERR);
119
120 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
121 eBroadcastBitStateChanged);
122
123 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
124 eBroadcastInternalStateControlStop |
125 eBroadcastInternalStateControlPause |
126 eBroadcastInternalStateControlResume);
127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132Process::~Process()
133{
Greg Claytone005f2c2010-11-06 01:53:30 +0000134 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000135 if (log)
136 log->Printf ("%p Process::~Process()", this);
137 StopPrivateStateThread();
138}
139
140void
141Process::Finalize()
142{
143 // Do any cleanup needed prior to being destructed... Subclasses
144 // that override this method should call this superclass method as well.
145}
146
147void
148Process::RegisterNotificationCallbacks (const Notifications& callbacks)
149{
150 m_notifications.push_back(callbacks);
151 if (callbacks.initialize != NULL)
152 callbacks.initialize (callbacks.baton, this);
153}
154
155bool
156Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
157{
158 std::vector<Notifications>::iterator pos, end = m_notifications.end();
159 for (pos = m_notifications.begin(); pos != end; ++pos)
160 {
161 if (pos->baton == callbacks.baton &&
162 pos->initialize == callbacks.initialize &&
163 pos->process_state_changed == callbacks.process_state_changed)
164 {
165 m_notifications.erase(pos);
166 return true;
167 }
168 }
169 return false;
170}
171
172void
173Process::SynchronouslyNotifyStateChanged (StateType state)
174{
175 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
176 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
177 {
178 if (notification_pos->process_state_changed)
179 notification_pos->process_state_changed (notification_pos->baton, this, state);
180 }
181}
182
183// FIXME: We need to do some work on events before the general Listener sees them.
184// For instance if we are continuing from a breakpoint, we need to ensure that we do
185// the little "insert real insn, step & stop" trick. But we can't do that when the
186// event is delivered by the broadcaster - since that is done on the thread that is
187// waiting for new events, so if we needed more than one event for our handling, we would
188// stall. So instead we do it when we fetch the event off of the queue.
189//
190
191StateType
192Process::GetNextEvent (EventSP &event_sp)
193{
194 StateType state = eStateInvalid;
195
196 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
197 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
198
199 return state;
200}
201
202
203StateType
204Process::WaitForProcessToStop (const TimeValue *timeout)
205{
206 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
207 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
208}
209
210
211StateType
212Process::WaitForState
213(
214 const TimeValue *timeout,
215 const StateType *match_states, const uint32_t num_match_states
216)
217{
218 EventSP event_sp;
219 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000220 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000221 while (state != eStateInvalid)
222 {
Greg Claytond8c62532010-10-07 04:19:01 +0000223 // If we are exited or detached, we won't ever get back to any
224 // other valid state...
225 if (state == eStateDetached || state == eStateExited)
226 return state;
227
Chris Lattner24943d22010-06-08 16:52:24 +0000228 state = WaitForStateChangedEvents (timeout, event_sp);
229
230 for (i=0; i<num_match_states; ++i)
231 {
232 if (match_states[i] == state)
233 return state;
234 }
235 }
236 return state;
237}
238
Jim Ingham63e24d72010-10-11 23:53:14 +0000239bool
240Process::HijackProcessEvents (Listener *listener)
241{
242 if (listener != NULL)
243 {
244 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
245 }
246 else
247 return false;
248}
249
250void
251Process::RestoreProcessEvents ()
252{
253 RestoreBroadcaster();
254}
255
Chris Lattner24943d22010-06-08 16:52:24 +0000256StateType
257Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
258{
Greg Claytone005f2c2010-11-06 01:53:30 +0000259 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000260
261 if (log)
262 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
263
264 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000265 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
266 this,
267 eBroadcastBitStateChanged,
268 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000269 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
270
Caroline Tice926060e2010-10-29 21:48:37 +0000271 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000272 if (log)
273 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
274 __FUNCTION__,
275 timeout,
276 StateAsCString(state));
277 return state;
278}
279
280Event *
281Process::PeekAtStateChangedEvents ()
282{
Greg Claytone005f2c2010-11-06 01:53:30 +0000283 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000284
285 if (log)
286 log->Printf ("Process::%s...", __FUNCTION__);
287
288 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000289 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
290 eBroadcastBitStateChanged);
Caroline Tice926060e2010-10-29 21:48:37 +0000291 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000292 if (log)
293 {
294 if (event_ptr)
295 {
296 log->Printf ("Process::%s (event_ptr) => %s",
297 __FUNCTION__,
298 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
299 }
300 else
301 {
302 log->Printf ("Process::%s no events found",
303 __FUNCTION__);
304 }
305 }
306 return event_ptr;
307}
308
309StateType
310Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
311{
Greg Claytone005f2c2010-11-06 01:53:30 +0000312 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000313
314 if (log)
315 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
316
317 StateType state = eStateInvalid;
318 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
319 &m_private_state_broadcaster,
320 eBroadcastBitStateChanged,
321 event_sp))
322 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
323
324 // This is a bit of a hack, but when we wait here we could very well return
325 // to the command-line, and that could disable the log, which would render the
326 // log we got above invalid.
327 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
328 if (log)
329 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
330 return state;
331}
332
333bool
334Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
335{
Greg Claytone005f2c2010-11-06 01:53:30 +0000336 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000337
338 if (log)
339 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
340
341 if (control_only)
342 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
343 else
344 return m_private_state_listener.WaitForEvent(timeout, event_sp);
345}
346
347bool
348Process::IsRunning () const
349{
350 return StateIsRunningState (m_public_state.GetValue());
351}
352
353int
354Process::GetExitStatus ()
355{
356 if (m_public_state.GetValue() == eStateExited)
357 return m_exit_status;
358 return -1;
359}
360
361const char *
362Process::GetExitDescription ()
363{
364 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
365 return m_exit_string.c_str();
366 return NULL;
367}
368
369void
370Process::SetExitStatus (int status, const char *cstr)
371{
372 m_exit_status = status;
373 if (cstr)
374 m_exit_string = cstr;
375 else
376 m_exit_string.clear();
377
378 SetPrivateState (eStateExited);
379}
380
381// This static callback can be used to watch for local child processes on
382// the current host. The the child process exits, the process will be
383// found in the global target list (we want to be completely sure that the
384// lldb_private::Process doesn't go away before we can deliver the signal.
385bool
386Process::SetProcessExitStatus
387(
388 void *callback_baton,
389 lldb::pid_t pid,
390 int signo, // Zero for no signal
391 int exit_status // Exit value of process if signal is zero
392)
393{
394 if (signo == 0 || exit_status)
395 {
Greg Clayton63094e02010-06-23 01:19:29 +0000396 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000397 if (target_sp)
398 {
399 ProcessSP process_sp (target_sp->GetProcessSP());
400 if (process_sp)
401 {
402 const char *signal_cstr = NULL;
403 if (signo)
404 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
405
406 process_sp->SetExitStatus (exit_status, signal_cstr);
407 }
408 }
409 return true;
410 }
411 return false;
412}
413
414
415uint32_t
416Process::GetNextThreadIndexID ()
417{
418 return ++m_thread_index_id;
419}
420
421StateType
422Process::GetState()
423{
424 // If any other threads access this we will need a mutex for it
425 return m_public_state.GetValue ();
426}
427
428void
429Process::SetPublicState (StateType new_state)
430{
Greg Claytone005f2c2010-11-06 01:53:30 +0000431 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000432 if (log)
433 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
434 m_public_state.SetValue (new_state);
435}
436
437StateType
438Process::GetPrivateState ()
439{
440 return m_private_state.GetValue();
441}
442
443void
444Process::SetPrivateState (StateType new_state)
445{
Greg Claytone005f2c2010-11-06 01:53:30 +0000446 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000447 bool state_changed = false;
448
449 if (log)
450 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
451
452 Mutex::Locker locker(m_private_state.GetMutex());
453
454 const StateType old_state = m_private_state.GetValueNoLock ();
455 state_changed = old_state != new_state;
456 if (state_changed)
457 {
458 m_private_state.SetValueNoLock (new_state);
459 if (StateIsStoppedState(new_state))
460 {
461 m_stop_id++;
462 if (log)
463 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
464 }
465 // Use our target to get a shared pointer to ourselves...
466 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
467 }
468 else
469 {
470 if (log)
471 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
472 }
473}
474
475
476uint32_t
477Process::GetStopID() const
478{
479 return m_stop_id;
480}
481
482addr_t
483Process::GetImageInfoAddress()
484{
485 return LLDB_INVALID_ADDRESS;
486}
487
Greg Clayton0baa3942010-11-04 01:54:29 +0000488//----------------------------------------------------------------------
489// LoadImage
490//
491// This function provides a default implementation that works for most
492// unix variants. Any Process subclasses that need to do shared library
493// loading differently should override LoadImage and UnloadImage and
494// do what is needed.
495//----------------------------------------------------------------------
496uint32_t
497Process::LoadImage (const FileSpec &image_spec, Error &error)
498{
499 DynamicLoader *loader = GetDynamicLoader();
500 if (loader)
501 {
502 error = loader->CanLoadImage();
503 if (error.Fail())
504 return LLDB_INVALID_IMAGE_TOKEN;
505 }
506
507 if (error.Success())
508 {
509 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
510 if (thread_sp == NULL)
511 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
512
513 if (thread_sp)
514 {
515 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
516
517 if (frame_sp)
518 {
519 ExecutionContext exe_ctx;
520 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000521 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000522 StreamString expr;
523 char path[PATH_MAX];
524 image_spec.GetPath(path, sizeof(path));
525 expr.Printf("dlopen (\"%s\", 2)", path);
526 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000527 lldb::ValueObjectSP result_valobj_sp;
528 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000529 if (result_valobj_sp->GetError().Success())
530 {
531 Scalar scalar;
532 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
533 {
534 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
535 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
536 {
537 uint32_t image_token = m_image_tokens.size();
538 m_image_tokens.push_back (image_ptr);
539 return image_token;
540 }
541 }
542 }
543 }
544 }
545 }
546 return LLDB_INVALID_IMAGE_TOKEN;
547}
548
549//----------------------------------------------------------------------
550// UnloadImage
551//
552// This function provides a default implementation that works for most
553// unix variants. Any Process subclasses that need to do shared library
554// loading differently should override LoadImage and UnloadImage and
555// do what is needed.
556//----------------------------------------------------------------------
557Error
558Process::UnloadImage (uint32_t image_token)
559{
560 Error error;
561 if (image_token < m_image_tokens.size())
562 {
563 const addr_t image_addr = m_image_tokens[image_token];
564 if (image_addr == LLDB_INVALID_ADDRESS)
565 {
566 error.SetErrorString("image already unloaded");
567 }
568 else
569 {
570 DynamicLoader *loader = GetDynamicLoader();
571 if (loader)
572 error = loader->CanLoadImage();
573
574 if (error.Success())
575 {
576 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
577 if (thread_sp == NULL)
578 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
579
580 if (thread_sp)
581 {
582 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
583
584 if (frame_sp)
585 {
586 ExecutionContext exe_ctx;
587 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000588 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000589 StreamString expr;
590 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
591 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000592 lldb::ValueObjectSP result_valobj_sp;
593 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000594 if (result_valobj_sp->GetError().Success())
595 {
596 Scalar scalar;
597 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
598 {
599 if (scalar.UInt(1))
600 {
601 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
602 }
603 else
604 {
605 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
606 }
607 }
608 }
609 else
610 {
611 error = result_valobj_sp->GetError();
612 }
613 }
614 }
615 }
616 }
617 }
618 else
619 {
620 error.SetErrorString("invalid image token");
621 }
622 return error;
623}
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625DynamicLoader *
626Process::GetDynamicLoader()
627{
628 return NULL;
629}
630
631const ABI *
632Process::GetABI()
633{
634 ConstString& triple = m_target_triple;
635
636 if (triple.IsEmpty())
637 return NULL;
638
639 if (m_abi_sp.get() == NULL)
640 {
641 m_abi_sp.reset(ABI::FindPlugin(triple));
642 }
643
644 return m_abi_sp.get();
645}
646
Jim Ingham642036f2010-09-23 02:01:19 +0000647LanguageRuntime *
648Process::GetLanguageRuntime(lldb::LanguageType language)
649{
650 LanguageRuntimeCollection::iterator pos;
651 pos = m_language_runtimes.find (language);
652 if (pos == m_language_runtimes.end())
653 {
654 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
655
656 m_language_runtimes[language]
657 = runtime;
658 return runtime.get();
659 }
660 else
661 return (*pos).second.get();
662}
663
664CPPLanguageRuntime *
665Process::GetCPPLanguageRuntime ()
666{
667 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
668 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
669 return static_cast<CPPLanguageRuntime *> (runtime);
670 return NULL;
671}
672
673ObjCLanguageRuntime *
674Process::GetObjCLanguageRuntime ()
675{
676 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
677 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
678 return static_cast<ObjCLanguageRuntime *> (runtime);
679 return NULL;
680}
681
Chris Lattner24943d22010-06-08 16:52:24 +0000682BreakpointSiteList &
683Process::GetBreakpointSiteList()
684{
685 return m_breakpoint_site_list;
686}
687
688const BreakpointSiteList &
689Process::GetBreakpointSiteList() const
690{
691 return m_breakpoint_site_list;
692}
693
694
695void
696Process::DisableAllBreakpointSites ()
697{
698 m_breakpoint_site_list.SetEnabledForAll (false);
699}
700
701Error
702Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
703{
704 Error error (DisableBreakpointSiteByID (break_id));
705
706 if (error.Success())
707 m_breakpoint_site_list.Remove(break_id);
708
709 return error;
710}
711
712Error
713Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
714{
715 Error error;
716 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
717 if (bp_site_sp)
718 {
719 if (bp_site_sp->IsEnabled())
720 error = DisableBreakpoint (bp_site_sp.get());
721 }
722 else
723 {
724 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
725 }
726
727 return error;
728}
729
730Error
731Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
732{
733 Error error;
734 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
735 if (bp_site_sp)
736 {
737 if (!bp_site_sp->IsEnabled())
738 error = EnableBreakpoint (bp_site_sp.get());
739 }
740 else
741 {
742 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
743 }
744 return error;
745}
746
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000747lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000748Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
749{
Greg Claytoneea26402010-09-14 23:36:40 +0000750 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000751 if (load_addr != LLDB_INVALID_ADDRESS)
752 {
753 BreakpointSiteSP bp_site_sp;
754
755 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
756 // create a new breakpoint site and add it.
757
758 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
759
760 if (bp_site_sp)
761 {
762 bp_site_sp->AddOwner (owner);
763 owner->SetBreakpointSite (bp_site_sp);
764 return bp_site_sp->GetID();
765 }
766 else
767 {
768 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
769 if (bp_site_sp)
770 {
771 if (EnableBreakpoint (bp_site_sp.get()).Success())
772 {
773 owner->SetBreakpointSite (bp_site_sp);
774 return m_breakpoint_site_list.Add (bp_site_sp);
775 }
776 }
777 }
778 }
779 // We failed to enable the breakpoint
780 return LLDB_INVALID_BREAK_ID;
781
782}
783
784void
785Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
786{
787 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
788 if (num_owners == 0)
789 {
790 DisableBreakpoint(bp_site_sp.get());
791 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
792 }
793}
794
795
796size_t
797Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
798{
799 size_t bytes_removed = 0;
800 addr_t intersect_addr;
801 size_t intersect_size;
802 size_t opcode_offset;
803 size_t idx;
804 BreakpointSiteSP bp;
805
806 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
807 {
808 if (bp->GetType() == BreakpointSite::eSoftware)
809 {
810 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
811 {
812 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
813 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
814 assert(opcode_offset + intersect_size <= bp->GetByteSize());
815 size_t buf_offset = intersect_addr - bp_addr;
816 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
817 }
818 }
819 }
820 return bytes_removed;
821}
822
823
824Error
825Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
826{
827 Error error;
828 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000829 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000830 const addr_t bp_addr = bp_site->GetLoadAddress();
831 if (log)
832 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
833 if (bp_site->IsEnabled())
834 {
835 if (log)
836 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
837 return error;
838 }
839
840 if (bp_addr == LLDB_INVALID_ADDRESS)
841 {
842 error.SetErrorString("BreakpointSite contains an invalid load address.");
843 return error;
844 }
845 // Ask the lldb::Process subclass to fill in the correct software breakpoint
846 // trap for the breakpoint site
847 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
848
849 if (bp_opcode_size == 0)
850 {
851 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
852 }
853 else
854 {
855 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
856
857 if (bp_opcode_bytes == NULL)
858 {
859 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
860 return error;
861 }
862
863 // Save the original opcode by reading it
864 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
865 {
866 // Write a software breakpoint in place of the original opcode
867 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
868 {
869 uint8_t verify_bp_opcode_bytes[64];
870 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
871 {
872 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
873 {
874 bp_site->SetEnabled(true);
875 bp_site->SetType (BreakpointSite::eSoftware);
876 if (log)
877 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
878 bp_site->GetID(),
879 (uint64_t)bp_addr);
880 }
881 else
882 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
883 }
884 else
885 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
886 }
887 else
888 error.SetErrorString("Unable to write breakpoint trap to memory.");
889 }
890 else
891 error.SetErrorString("Unable to read memory at breakpoint address.");
892 }
893 if (log)
894 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
895 bp_site->GetID(),
896 (uint64_t)bp_addr,
897 error.AsCString());
898 return error;
899}
900
901Error
902Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
903{
904 Error error;
905 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000906 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000907 addr_t bp_addr = bp_site->GetLoadAddress();
908 lldb::user_id_t breakID = bp_site->GetID();
909 if (log)
910 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
911
912 if (bp_site->IsHardware())
913 {
914 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
915 }
916 else if (bp_site->IsEnabled())
917 {
918 const size_t break_op_size = bp_site->GetByteSize();
919 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
920 if (break_op_size > 0)
921 {
922 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +0000923 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000924 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +0000925 bool break_op_found = false;
926
927 // Read the breakpoint opcode
928 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
929 {
930 bool verify = false;
931 // Make sure we have the a breakpoint opcode exists at this address
932 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
933 {
934 break_op_found = true;
935 // We found a valid breakpoint opcode at this address, now restore
936 // the saved opcode.
937 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
938 {
939 verify = true;
940 }
941 else
942 error.SetErrorString("Memory write failed when restoring original opcode.");
943 }
944 else
945 {
946 error.SetErrorString("Original breakpoint trap is no longer in memory.");
947 // Set verify to true and so we can check if the original opcode has already been restored
948 verify = true;
949 }
950
951 if (verify)
952 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000953 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000954 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +0000955 // Verify that our original opcode made it back to the inferior
956 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
957 {
958 // compare the memory we just read with the original opcode
959 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
960 {
961 // SUCCESS
962 bp_site->SetEnabled(false);
963 if (log)
964 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
965 return error;
966 }
967 else
968 {
969 if (break_op_found)
970 error.SetErrorString("Failed to restore original opcode.");
971 }
972 }
973 else
974 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
975 }
976 }
977 else
978 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
979 }
980 }
981 else
982 {
983 if (log)
984 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
985 return error;
986 }
987
988 if (log)
989 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
990 bp_site->GetID(),
991 (uint64_t)bp_addr,
992 error.AsCString());
993 return error;
994
995}
996
997
998size_t
999Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1000{
1001 if (buf == NULL || size == 0)
1002 return 0;
1003
1004 size_t bytes_read = 0;
1005 uint8_t *bytes = (uint8_t *)buf;
1006
1007 while (bytes_read < size)
1008 {
1009 const size_t curr_size = size - bytes_read;
1010 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1011 bytes + bytes_read,
1012 curr_size,
1013 error);
1014 bytes_read += curr_bytes_read;
1015 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1016 break;
1017 }
1018
1019 // Replace any software breakpoint opcodes that fall into this range back
1020 // into "buf" before we return
1021 if (bytes_read > 0)
1022 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1023 return bytes_read;
1024}
1025
1026size_t
1027Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1028{
1029 size_t bytes_written = 0;
1030 const uint8_t *bytes = (const uint8_t *)buf;
1031
1032 while (bytes_written < size)
1033 {
1034 const size_t curr_size = size - bytes_written;
1035 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1036 bytes + bytes_written,
1037 curr_size,
1038 error);
1039 bytes_written += curr_bytes_written;
1040 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1041 break;
1042 }
1043 return bytes_written;
1044}
1045
1046size_t
1047Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1048{
1049 if (buf == NULL || size == 0)
1050 return 0;
1051 // We need to write any data that would go where any current software traps
1052 // (enabled software breakpoints) any software traps (breakpoints) that we
1053 // may have placed in our tasks memory.
1054
1055 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1056 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1057
1058 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1059 return DoWriteMemory(addr, buf, size, error);
1060
1061 BreakpointSiteList::collection::const_iterator pos;
1062 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001063 addr_t intersect_addr = 0;
1064 size_t intersect_size = 0;
1065 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001066 const uint8_t *ubuf = (const uint8_t *)buf;
1067
1068 for (pos = iter; pos != end; ++pos)
1069 {
1070 BreakpointSiteSP bp;
1071 bp = pos->second;
1072
1073 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1074 assert(addr <= intersect_addr && intersect_addr < addr + size);
1075 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1076 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1077
1078 // Check for bytes before this breakpoint
1079 const addr_t curr_addr = addr + bytes_written;
1080 if (intersect_addr > curr_addr)
1081 {
1082 // There are some bytes before this breakpoint that we need to
1083 // just write to memory
1084 size_t curr_size = intersect_addr - curr_addr;
1085 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1086 ubuf + bytes_written,
1087 curr_size,
1088 error);
1089 bytes_written += curr_bytes_written;
1090 if (curr_bytes_written != curr_size)
1091 {
1092 // We weren't able to write all of the requested bytes, we
1093 // are done looping and will return the number of bytes that
1094 // we have written so far.
1095 break;
1096 }
1097 }
1098
1099 // Now write any bytes that would cover up any software breakpoints
1100 // directly into the breakpoint opcode buffer
1101 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1102 bytes_written += intersect_size;
1103 }
1104
1105 // Write any remaining bytes after the last breakpoint if we have any left
1106 if (bytes_written < size)
1107 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1108 ubuf + bytes_written,
1109 size - bytes_written,
1110 error);
1111
1112 return bytes_written;
1113}
1114
1115addr_t
1116Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1117{
1118 // Fixme: we should track the blocks we've allocated, and clean them up...
1119 // We could even do our own allocator here if that ends up being more efficient.
1120 return DoAllocateMemory (size, permissions, error);
1121}
1122
1123Error
1124Process::DeallocateMemory (addr_t ptr)
1125{
1126 return DoDeallocateMemory (ptr);
1127}
1128
1129
1130Error
1131Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1132{
1133 Error error;
1134 error.SetErrorString("watchpoints are not supported");
1135 return error;
1136}
1137
1138Error
1139Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1140{
1141 Error error;
1142 error.SetErrorString("watchpoints are not supported");
1143 return error;
1144}
1145
1146StateType
1147Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1148{
1149 StateType state;
1150 // Now wait for the process to launch and return control to us, and then
1151 // call DidLaunch:
1152 while (1)
1153 {
1154 // FIXME: Might want to put a timeout in here:
1155 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1156 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1157 break;
1158 else
1159 HandlePrivateEvent (event_sp);
1160 }
1161 return state;
1162}
1163
1164Error
1165Process::Launch
1166(
1167 char const *argv[],
1168 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001169 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001170 const char *stdin_path,
1171 const char *stdout_path,
1172 const char *stderr_path
1173)
1174{
1175 Error error;
1176 m_target_triple.Clear();
1177 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001178 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001179
1180 Module *exe_module = m_target.GetExecutableModule().get();
1181 if (exe_module)
1182 {
1183 char exec_file_path[PATH_MAX];
1184 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1185 if (exe_module->GetFileSpec().Exists())
1186 {
1187 error = WillLaunch (exe_module);
1188 if (error.Success())
1189 {
Greg Claytond8c62532010-10-07 04:19:01 +00001190 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001191 // The args coming in should not contain the application name, the
1192 // lldb_private::Process class will add this in case the executable
1193 // gets resolved to a different file than was given on the command
1194 // line (like when an applicaiton bundle is specified and will
1195 // resolve to the contained exectuable file, or the file given was
1196 // a symlink or other file system link that resolves to a different
1197 // file).
1198
1199 // Get the resolved exectuable path
1200
1201 // Make a new argument vector
1202 std::vector<const char *> exec_path_plus_argv;
1203 // Append the resolved executable path
1204 exec_path_plus_argv.push_back (exec_file_path);
1205
1206 // Push all args if there are any
1207 if (argv)
1208 {
1209 for (int i = 0; argv[i]; ++i)
1210 exec_path_plus_argv.push_back(argv[i]);
1211 }
1212
1213 // Push a NULL to terminate the args.
1214 exec_path_plus_argv.push_back(NULL);
1215
1216 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001217 error = DoLaunch (exe_module,
1218 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1219 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001220 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001221 stdin_path,
1222 stdout_path,
1223 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001224
1225 if (error.Fail())
1226 {
1227 if (GetID() != LLDB_INVALID_PROCESS_ID)
1228 {
1229 SetID (LLDB_INVALID_PROCESS_ID);
1230 const char *error_string = error.AsCString();
1231 if (error_string == NULL)
1232 error_string = "launch failed";
1233 SetExitStatus (-1, error_string);
1234 }
1235 }
1236 else
1237 {
1238 EventSP event_sp;
1239 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1240
1241 if (state == eStateStopped || state == eStateCrashed)
1242 {
1243 DidLaunch ();
1244
1245 // This delays passing the stopped event to listeners till DidLaunch gets
1246 // a chance to complete...
1247 HandlePrivateEvent (event_sp);
1248 StartPrivateStateThread ();
1249 }
1250 else if (state == eStateExited)
1251 {
1252 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1253 // not likely to work, and return an invalid pid.
1254 HandlePrivateEvent (event_sp);
1255 }
1256 }
1257 }
1258 }
1259 else
1260 {
1261 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1262 }
1263 }
1264 return error;
1265}
1266
1267Error
1268Process::CompleteAttach ()
1269{
1270 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001271
1272 if (GetID() == LLDB_INVALID_PROCESS_ID)
1273 {
1274 error.SetErrorString("no process");
1275 }
1276
Chris Lattner24943d22010-06-08 16:52:24 +00001277 EventSP event_sp;
1278 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1279 if (state == eStateStopped || state == eStateCrashed)
1280 {
1281 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001282 // Figure out which one is the executable, and set that in our target:
1283 ModuleList &modules = GetTarget().GetImages();
1284
1285 size_t num_modules = modules.GetSize();
1286 for (int i = 0; i < num_modules; i++)
1287 {
1288 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1289 if (module_sp->IsExecutable())
1290 {
1291 ModuleSP exec_module = GetTarget().GetExecutableModule();
1292 if (!exec_module || exec_module != module_sp)
1293 {
1294
1295 GetTarget().SetExecutableModule (module_sp, false);
1296 }
1297 break;
1298 }
1299 }
Chris Lattner24943d22010-06-08 16:52:24 +00001300
1301 // This delays passing the stopped event to listeners till DidLaunch gets
1302 // a chance to complete...
1303 HandlePrivateEvent(event_sp);
1304 StartPrivateStateThread();
1305 }
1306 else
1307 {
1308 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1309 // not likely to work, and return an invalid pid.
1310 if (state == eStateExited)
1311 HandlePrivateEvent (event_sp);
1312 error.SetErrorStringWithFormat("invalid state after attach: %s",
1313 lldb_private::StateAsCString(state));
1314 }
1315 return error;
1316}
1317
1318Error
1319Process::Attach (lldb::pid_t attach_pid)
1320{
1321
1322 m_target_triple.Clear();
1323 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001324 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001325
Jim Ingham7508e732010-08-09 23:31:02 +00001326 // Find the process and its architecture. Make sure it matches the architecture
1327 // of the current Target, and if not adjust it.
1328
1329 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1330 if (attach_spec != GetTarget().GetArchitecture())
1331 {
1332 // Set the architecture on the target.
1333 GetTarget().SetArchitecture(attach_spec);
1334 }
1335
Greg Clayton54e7afa2010-07-09 20:39:50 +00001336 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001337 if (error.Success())
1338 {
Greg Claytond8c62532010-10-07 04:19:01 +00001339 SetPublicState (eStateAttaching);
1340
Greg Clayton54e7afa2010-07-09 20:39:50 +00001341 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001342 if (error.Success())
1343 {
1344 error = CompleteAttach();
1345 }
1346 else
1347 {
1348 if (GetID() != LLDB_INVALID_PROCESS_ID)
1349 {
1350 SetID (LLDB_INVALID_PROCESS_ID);
1351 const char *error_string = error.AsCString();
1352 if (error_string == NULL)
1353 error_string = "attach failed";
1354
1355 SetExitStatus(-1, error_string);
1356 }
1357 }
1358 }
1359 return error;
1360}
1361
1362Error
1363Process::Attach (const char *process_name, bool wait_for_launch)
1364{
1365 m_target_triple.Clear();
1366 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001367 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001368
1369 // Find the process and its architecture. Make sure it matches the architecture
1370 // of the current Target, and if not adjust it.
1371
Jim Inghamea294182010-08-17 21:54:19 +00001372 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001373 {
Jim Inghamea294182010-08-17 21:54:19 +00001374 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001375 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001376 {
1377 // Set the architecture on the target.
1378 GetTarget().SetArchitecture(attach_spec);
1379 }
Jim Ingham7508e732010-08-09 23:31:02 +00001380 }
Jim Inghamea294182010-08-17 21:54:19 +00001381
Greg Clayton54e7afa2010-07-09 20:39:50 +00001382 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001383 if (error.Success())
1384 {
Greg Claytond8c62532010-10-07 04:19:01 +00001385 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001386 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001387 if (error.Fail())
1388 {
1389 if (GetID() != LLDB_INVALID_PROCESS_ID)
1390 {
1391 SetID (LLDB_INVALID_PROCESS_ID);
1392 const char *error_string = error.AsCString();
1393 if (error_string == NULL)
1394 error_string = "attach failed";
1395
1396 SetExitStatus(-1, error_string);
1397 }
1398 }
1399 else
1400 {
1401 error = CompleteAttach();
1402 }
1403 }
1404 return error;
1405}
1406
1407Error
1408Process::Resume ()
1409{
Greg Claytone005f2c2010-11-06 01:53:30 +00001410 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001411 if (log)
1412 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1413
1414 Error error (WillResume());
1415 // Tell the process it is about to resume before the thread list
1416 if (error.Success())
1417 {
1418 // Now let the thread list know we are about to resume to it
1419 // can let all of our threads know that they are about to be
1420 // resumed. Threads will each be called with
1421 // Thread::WillResume(StateType) where StateType contains the state
1422 // that they are supposed to have when the process is resumed
1423 // (suspended/running/stepping). Threads should also check
1424 // their resume signal in lldb::Thread::GetResumeSignal()
1425 // to see if they are suppoed to start back up with a signal.
1426 if (m_thread_list.WillResume())
1427 {
1428 error = DoResume();
1429 if (error.Success())
1430 {
1431 DidResume();
1432 m_thread_list.DidResume();
1433 }
1434 }
1435 else
1436 {
1437 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1438 }
1439 }
1440 return error;
1441}
1442
1443Error
1444Process::Halt ()
1445{
1446 Error error (WillHalt());
1447
1448 if (error.Success())
1449 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001450
1451 bool caused_stop = false;
1452 EventSP event_sp;
1453
1454 // Pause our private state thread so we can ensure no one else eats
1455 // the stop event out from under us.
1456 PausePrivateStateThread();
1457
1458 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001459 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001460 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001461 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001462 // If "caused_stop" is true, then DoHalt stopped the process. If
1463 // "caused_stop" is false, the process was already stopped.
1464 // If the DoHalt caused the process to stop, then we want to catch
1465 // this event and set the interrupted bool to true before we pass
1466 // this along so clients know that the process was interrupted by
1467 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001468 if (caused_stop)
1469 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001470 // Wait for 2 seconds for the process to stop.
1471 TimeValue timeout_time;
1472 timeout_time = TimeValue::Now();
1473 timeout_time.OffsetWithSeconds(2);
1474 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1475
1476 if (state == eStateInvalid)
1477 {
1478 // We timeout out and didn't get a stop event...
1479 error.SetErrorString ("Halt timed out.");
1480 }
1481 else
1482 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001483 if (StateIsStoppedState (state))
1484 {
1485 // We caused the process to interrupt itself, so mark this
1486 // as such in the stop event so clients can tell an interrupted
1487 // process from a natural stop
1488 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1489 }
1490 else
1491 {
1492 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1493 if (log)
1494 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1495 error.SetErrorString ("Did not get stopped event after halt.");
1496 }
1497 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001498 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001499 DidHalt();
1500
Jim Ingham3ae449a2010-11-17 02:32:00 +00001501 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001502 // Resume our private state thread before we post the event (if any)
1503 ResumePrivateStateThread();
1504
1505 // Post any event we might have consumed. If all goes well, we will have
1506 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001507 // bool in the event. Post it to the private event queue and that will end up
1508 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001509 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001510 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001511
Chris Lattner24943d22010-06-08 16:52:24 +00001512 }
1513 return error;
1514}
1515
1516Error
1517Process::Detach ()
1518{
1519 Error error (WillDetach());
1520
1521 if (error.Success())
1522 {
1523 DisableAllBreakpointSites();
1524 error = DoDetach();
1525 if (error.Success())
1526 {
1527 DidDetach();
1528 StopPrivateStateThread();
1529 }
1530 }
1531 return error;
1532}
1533
1534Error
1535Process::Destroy ()
1536{
1537 Error error (WillDestroy());
1538 if (error.Success())
1539 {
1540 DisableAllBreakpointSites();
1541 error = DoDestroy();
1542 if (error.Success())
1543 {
1544 DidDestroy();
1545 StopPrivateStateThread();
1546 }
Caroline Tice861efb32010-11-16 05:07:41 +00001547 m_stdio_communication.StopReadThread();
1548 m_stdio_communication.Disconnect();
1549 if (m_process_input_reader && m_process_input_reader->IsActive())
1550 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1551 if (m_process_input_reader)
1552 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001553 }
1554 return error;
1555}
1556
1557Error
1558Process::Signal (int signal)
1559{
1560 Error error (WillSignal());
1561 if (error.Success())
1562 {
1563 error = DoSignal(signal);
1564 if (error.Success())
1565 DidSignal();
1566 }
1567 return error;
1568}
1569
1570UnixSignals &
1571Process::GetUnixSignals ()
1572{
1573 return m_unix_signals;
1574}
1575
1576Target &
1577Process::GetTarget ()
1578{
1579 return m_target;
1580}
1581
1582const Target &
1583Process::GetTarget () const
1584{
1585 return m_target;
1586}
1587
1588uint32_t
1589Process::GetAddressByteSize()
1590{
Greg Clayton20d338f2010-11-18 05:57:03 +00001591 if (m_addr_byte_size == 0)
1592 return m_target.GetArchitecture().GetAddressByteSize();
1593 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001594}
1595
1596bool
1597Process::ShouldBroadcastEvent (Event *event_ptr)
1598{
1599 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1600 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001601 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001602
1603 switch (state)
1604 {
1605 case eStateAttaching:
1606 case eStateLaunching:
1607 case eStateDetached:
1608 case eStateExited:
1609 case eStateUnloaded:
1610 // These events indicate changes in the state of the debugging session, always report them.
1611 return_value = true;
1612 break;
1613 case eStateInvalid:
1614 // We stopped for no apparent reason, don't report it.
1615 return_value = false;
1616 break;
1617 case eStateRunning:
1618 case eStateStepping:
1619 // If we've started the target running, we handle the cases where we
1620 // are already running and where there is a transition from stopped to
1621 // running differently.
1622 // running -> running: Automatically suppress extra running events
1623 // stopped -> running: Report except when there is one or more no votes
1624 // and no yes votes.
1625 SynchronouslyNotifyStateChanged (state);
1626 switch (m_public_state.GetValue())
1627 {
1628 case eStateRunning:
1629 case eStateStepping:
1630 // We always suppress multiple runnings with no PUBLIC stop in between.
1631 return_value = false;
1632 break;
1633 default:
1634 // TODO: make this work correctly. For now always report
1635 // run if we aren't running so we don't miss any runnning
1636 // events. If I run the lldb/test/thread/a.out file and
1637 // break at main.cpp:58, run and hit the breakpoints on
1638 // multiple threads, then somehow during the stepping over
1639 // of all breakpoints no run gets reported.
1640 return_value = true;
1641
1642 // This is a transition from stop to run.
1643 switch (m_thread_list.ShouldReportRun (event_ptr))
1644 {
1645 case eVoteYes:
1646 case eVoteNoOpinion:
1647 return_value = true;
1648 break;
1649 case eVoteNo:
1650 return_value = false;
1651 break;
1652 }
1653 break;
1654 }
1655 break;
1656 case eStateStopped:
1657 case eStateCrashed:
1658 case eStateSuspended:
1659 {
1660 // We've stopped. First see if we're going to restart the target.
1661 // If we are going to stop, then we always broadcast the event.
1662 // 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 +00001663 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001664 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001665 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001666 if (log)
1667 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001668 return true;
1669 }
1670 else
1671 {
Chris Lattner24943d22010-06-08 16:52:24 +00001672 RefreshStateAfterStop ();
1673
1674 if (m_thread_list.ShouldStop (event_ptr) == false)
1675 {
1676 switch (m_thread_list.ShouldReportStop (event_ptr))
1677 {
1678 case eVoteYes:
1679 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001680 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001681 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001682 case eVoteNo:
1683 return_value = false;
1684 break;
1685 }
1686
1687 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001688 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001689 Resume ();
1690 }
1691 else
1692 {
1693 return_value = true;
1694 SynchronouslyNotifyStateChanged (state);
1695 }
1696 }
1697 }
1698 }
1699
1700 if (log)
1701 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1702 return return_value;
1703}
1704
1705//------------------------------------------------------------------
1706// Thread Queries
1707//------------------------------------------------------------------
1708
1709ThreadList &
1710Process::GetThreadList ()
1711{
1712 return m_thread_list;
1713}
1714
1715const ThreadList &
1716Process::GetThreadList () const
1717{
1718 return m_thread_list;
1719}
1720
1721
1722bool
1723Process::StartPrivateStateThread ()
1724{
Greg Claytone005f2c2010-11-06 01:53:30 +00001725 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001726
1727 if (log)
1728 log->Printf ("Process::%s ( )", __FUNCTION__);
1729
1730 // Create a thread that watches our internal state and controls which
1731 // events make it to clients (into the DCProcess event queue).
1732 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1733 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1734}
1735
1736void
1737Process::PausePrivateStateThread ()
1738{
1739 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1740}
1741
1742void
1743Process::ResumePrivateStateThread ()
1744{
1745 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1746}
1747
1748void
1749Process::StopPrivateStateThread ()
1750{
1751 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1752}
1753
1754void
1755Process::ControlPrivateStateThread (uint32_t signal)
1756{
Greg Claytone005f2c2010-11-06 01:53:30 +00001757 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001758
1759 assert (signal == eBroadcastInternalStateControlStop ||
1760 signal == eBroadcastInternalStateControlPause ||
1761 signal == eBroadcastInternalStateControlResume);
1762
1763 if (log)
1764 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1765
1766 // Signal the private state thread
1767 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1768 {
1769 TimeValue timeout_time;
1770 bool timed_out;
1771
1772 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1773
1774 timeout_time = TimeValue::Now();
1775 timeout_time.OffsetWithSeconds(2);
1776 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1777 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1778
1779 if (signal == eBroadcastInternalStateControlStop)
1780 {
1781 if (timed_out)
1782 Host::ThreadCancel (m_private_state_thread, NULL);
1783
1784 thread_result_t result = NULL;
1785 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00001786 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001787 }
1788 }
1789}
1790
1791void
1792Process::HandlePrivateEvent (EventSP &event_sp)
1793{
Greg Claytone005f2c2010-11-06 01:53:30 +00001794 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001795 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1796 // See if we should broadcast this state to external clients?
1797 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1798 if (log)
1799 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1800
1801 if (should_broadcast)
1802 {
1803 if (log)
1804 {
1805 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1806 }
Caroline Tice861efb32010-11-16 05:07:41 +00001807 if (StateIsRunningState (internal_state))
1808 PushProcessInputReader ();
1809 else
1810 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00001811 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1812 BroadcastEvent (event_sp);
1813 }
1814 else
1815 {
1816 if (log)
1817 {
1818 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1819 }
1820 }
1821}
1822
1823void *
1824Process::PrivateStateThread (void *arg)
1825{
1826 Process *proc = static_cast<Process*> (arg);
1827 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001828 return result;
1829}
1830
1831void *
1832Process::RunPrivateStateThread ()
1833{
1834 bool control_only = false;
1835 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1836
Greg Claytone005f2c2010-11-06 01:53:30 +00001837 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001838 if (log)
1839 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1840
1841 bool exit_now = false;
1842 while (!exit_now)
1843 {
1844 EventSP event_sp;
1845 WaitForEventsPrivate (NULL, event_sp, control_only);
1846 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1847 {
1848 switch (event_sp->GetType())
1849 {
1850 case eBroadcastInternalStateControlStop:
1851 exit_now = true;
1852 continue; // Go to next loop iteration so we exit without
1853 break; // doing any internal state managment below
1854
1855 case eBroadcastInternalStateControlPause:
1856 control_only = true;
1857 break;
1858
1859 case eBroadcastInternalStateControlResume:
1860 control_only = false;
1861 break;
1862 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001863
1864 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1865 if (log)
1866 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
1867
Chris Lattner24943d22010-06-08 16:52:24 +00001868 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00001869 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00001870 }
1871
1872
1873 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1874
1875 if (internal_state != eStateInvalid)
1876 {
1877 HandlePrivateEvent (event_sp);
1878 }
1879
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001880 if (internal_state == eStateInvalid ||
1881 internal_state == eStateExited ||
1882 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00001883 {
1884 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1885 if (log)
1886 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
1887
Chris Lattner24943d22010-06-08 16:52:24 +00001888 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001889 }
Chris Lattner24943d22010-06-08 16:52:24 +00001890 }
1891
Caroline Tice926060e2010-10-29 21:48:37 +00001892 // Verify log is still enabled before attempting to write to it...
1893 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001894 if (log)
1895 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1896
Greg Clayton8b4c16e2010-08-19 21:50:06 +00001897 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001898 return NULL;
1899}
1900
Chris Lattner24943d22010-06-08 16:52:24 +00001901//------------------------------------------------------------------
1902// Process Event Data
1903//------------------------------------------------------------------
1904
1905Process::ProcessEventData::ProcessEventData () :
1906 EventData (),
1907 m_process_sp (),
1908 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001909 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00001910 m_update_state (false),
1911 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001912{
1913}
1914
1915Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1916 EventData (),
1917 m_process_sp (process_sp),
1918 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001919 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00001920 m_update_state (false),
1921 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001922{
1923}
1924
1925Process::ProcessEventData::~ProcessEventData()
1926{
1927}
1928
1929const ConstString &
1930Process::ProcessEventData::GetFlavorString ()
1931{
1932 static ConstString g_flavor ("Process::ProcessEventData");
1933 return g_flavor;
1934}
1935
1936const ConstString &
1937Process::ProcessEventData::GetFlavor () const
1938{
1939 return ProcessEventData::GetFlavorString ();
1940}
1941
Chris Lattner24943d22010-06-08 16:52:24 +00001942void
1943Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1944{
1945 // This function gets called twice for each event, once when the event gets pulled
1946 // off of the private process event queue, and once when it gets pulled off of
1947 // the public event queue. m_update_state is used to distinguish these
1948 // two cases; it is false when we're just pulling it off for private handling,
1949 // and we don't want to do the breakpoint command handling then.
1950
1951 if (!m_update_state)
1952 return;
1953
1954 m_process_sp->SetPublicState (m_state);
1955
1956 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1957 if (m_state == eStateStopped && ! m_restarted)
1958 {
1959 int num_threads = m_process_sp->GetThreadList().GetSize();
1960 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00001961
Chris Lattner24943d22010-06-08 16:52:24 +00001962 for (idx = 0; idx < num_threads; ++idx)
1963 {
1964 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1965
Jim Ingham6297a3a2010-10-20 00:39:53 +00001966 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
1967 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001968 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00001969 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00001970 }
1971 }
Greg Clayton643ee732010-08-04 01:40:35 +00001972
Jim Ingham6fb8baa2010-08-10 00:59:59 +00001973 // The stop action might restart the target. If it does, then we want to mark that in the
1974 // event so that whoever is receiving it will know to wait for the running event and reflect
1975 // that state appropriately.
1976
Chris Lattner24943d22010-06-08 16:52:24 +00001977 if (m_process_sp->GetPrivateState() == eStateRunning)
1978 SetRestarted(true);
1979 }
1980}
1981
1982void
1983Process::ProcessEventData::Dump (Stream *s) const
1984{
1985 if (m_process_sp)
1986 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1987
1988 s->Printf("state = %s", StateAsCString(GetState()));;
1989}
1990
1991const Process::ProcessEventData *
1992Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1993{
1994 if (event_ptr)
1995 {
1996 const EventData *event_data = event_ptr->GetData();
1997 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1998 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1999 }
2000 return NULL;
2001}
2002
2003ProcessSP
2004Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2005{
2006 ProcessSP process_sp;
2007 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2008 if (data)
2009 process_sp = data->GetProcessSP();
2010 return process_sp;
2011}
2012
2013StateType
2014Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2015{
2016 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2017 if (data == NULL)
2018 return eStateInvalid;
2019 else
2020 return data->GetState();
2021}
2022
2023bool
2024Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2025{
2026 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2027 if (data == NULL)
2028 return false;
2029 else
2030 return data->GetRestarted();
2031}
2032
2033void
2034Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2035{
2036 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2037 if (data != NULL)
2038 data->SetRestarted(new_value);
2039}
2040
2041bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002042Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2043{
2044 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2045 if (data == NULL)
2046 return false;
2047 else
2048 return data->GetInterrupted ();
2049}
2050
2051void
2052Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2053{
2054 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2055 if (data != NULL)
2056 data->SetInterrupted(new_value);
2057}
2058
2059bool
Chris Lattner24943d22010-06-08 16:52:24 +00002060Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2061{
2062 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2063 if (data)
2064 {
2065 data->SetUpdateStateOnRemoval();
2066 return true;
2067 }
2068 return false;
2069}
2070
Chris Lattner24943d22010-06-08 16:52:24 +00002071Target *
2072Process::CalculateTarget ()
2073{
2074 return &m_target;
2075}
2076
2077Process *
2078Process::CalculateProcess ()
2079{
2080 return this;
2081}
2082
2083Thread *
2084Process::CalculateThread ()
2085{
2086 return NULL;
2087}
2088
2089StackFrame *
2090Process::CalculateStackFrame ()
2091{
2092 return NULL;
2093}
2094
2095void
Greg Claytona830adb2010-10-04 01:05:56 +00002096Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002097{
2098 exe_ctx.target = &m_target;
2099 exe_ctx.process = this;
2100 exe_ctx.thread = NULL;
2101 exe_ctx.frame = NULL;
2102}
2103
2104lldb::ProcessSP
2105Process::GetSP ()
2106{
2107 return GetTarget().GetProcessSP();
2108}
2109
Sean Callanana48fe162010-08-11 03:57:18 +00002110ClangPersistentVariables &
2111Process::GetPersistentVariables()
2112{
2113 return m_persistent_vars;
2114}
2115
Jim Ingham7508e732010-08-09 23:31:02 +00002116uint32_t
2117Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2118{
2119 return 0;
2120}
2121
2122ArchSpec
2123Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2124{
2125 return Host::GetArchSpecForExistingProcess (pid);
2126}
2127
2128ArchSpec
2129Process::GetArchSpecForExistingProcess (const char *process_name)
2130{
2131 return Host::GetArchSpecForExistingProcess (process_name);
2132}
2133
Caroline Tice861efb32010-11-16 05:07:41 +00002134void
2135Process::AppendSTDOUT (const char * s, size_t len)
2136{
Greg Clayton20d338f2010-11-18 05:57:03 +00002137 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002138 m_stdout_data.append (s, len);
2139
2140 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
2141}
2142
2143void
2144Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2145{
2146 Process *process = (Process *) baton;
2147 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2148}
2149
2150size_t
2151Process::ProcessInputReaderCallback (void *baton,
2152 InputReader &reader,
2153 lldb::InputReaderAction notification,
2154 const char *bytes,
2155 size_t bytes_len)
2156{
2157 Process *process = (Process *) baton;
2158
2159 switch (notification)
2160 {
2161 case eInputReaderActivate:
2162 break;
2163
2164 case eInputReaderDeactivate:
2165 break;
2166
2167 case eInputReaderReactivate:
2168 break;
2169
2170 case eInputReaderGotToken:
2171 {
2172 Error error;
2173 process->PutSTDIN (bytes, bytes_len, error);
2174 }
2175 break;
2176
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002177 case eInputReaderInterrupt:
2178 process->Halt ();
2179 break;
2180
2181 case eInputReaderEndOfFile:
2182 process->AppendSTDOUT ("^D", 2);
2183 break;
2184
Caroline Tice861efb32010-11-16 05:07:41 +00002185 case eInputReaderDone:
2186 break;
2187
2188 }
2189
2190 return bytes_len;
2191}
2192
2193void
2194Process::ResetProcessInputReader ()
2195{
2196 m_process_input_reader.reset();
2197}
2198
2199void
2200Process::SetUpProcessInputReader (int file_descriptor)
2201{
2202 // First set up the Read Thread for reading/handling process I/O
2203
2204 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2205
2206 if (conn_ap.get())
2207 {
2208 m_stdio_communication.SetConnection (conn_ap.release());
2209 if (m_stdio_communication.IsConnected())
2210 {
2211 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2212 m_stdio_communication.StartReadThread();
2213
2214 // Now read thread is set up, set up input reader.
2215
2216 if (!m_process_input_reader.get())
2217 {
2218 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2219 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2220 this,
2221 eInputReaderGranularityByte,
2222 NULL,
2223 NULL,
2224 false));
2225
2226 if (err.Fail())
2227 m_process_input_reader.reset();
2228 }
2229 }
2230 }
2231}
2232
2233void
2234Process::PushProcessInputReader ()
2235{
2236 if (m_process_input_reader && !m_process_input_reader->IsActive())
2237 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2238}
2239
2240void
2241Process::PopProcessInputReader ()
2242{
2243 if (m_process_input_reader && m_process_input_reader->IsActive())
2244 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2245}
2246
Greg Clayton990de7b2010-11-18 23:32:35 +00002247
2248void
2249Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002250{
Greg Clayton990de7b2010-11-18 23:32:35 +00002251 UserSettingsControllerSP &usc = GetSettingsController();
2252 usc.reset (new SettingsController);
2253 UserSettingsController::InitializeSettingsController (usc,
2254 SettingsController::global_settings_table,
2255 SettingsController::instance_settings_table);
2256}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002257
Greg Clayton990de7b2010-11-18 23:32:35 +00002258void
2259Process::Terminate ()
2260{
2261 UserSettingsControllerSP &usc = GetSettingsController();
2262 UserSettingsController::FinalizeSettingsController (usc);
2263 usc.reset();
2264}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002265
Greg Clayton990de7b2010-11-18 23:32:35 +00002266UserSettingsControllerSP &
2267Process::GetSettingsController ()
2268{
2269 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002270 return g_settings_controller;
2271}
2272
Caroline Tice1ebef442010-09-27 00:30:10 +00002273void
2274Process::UpdateInstanceName ()
2275{
2276 ModuleSP module_sp = GetTarget().GetExecutableModule();
2277 if (module_sp)
2278 {
2279 StreamString sstr;
2280 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2281
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002282 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002283 sstr.GetData());
2284 }
2285}
2286
Jim Ingham360f53f2010-11-30 02:22:11 +00002287Process::ExecutionResults
2288Process::RunThreadPlan (ExecutionContext &exe_ctx,
2289 lldb::ThreadPlanSP &thread_plan_sp,
2290 bool stop_others,
2291 bool try_all_threads,
2292 bool discard_on_error,
2293 uint32_t single_thread_timeout_usec,
2294 Stream &errors)
2295{
2296 ExecutionResults return_value = eExecutionSetupError;
2297
2298 // Save this value for restoration of the execution context after we run
2299 uint32_t tid = exe_ctx.thread->GetIndexID();
2300
2301 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2302 // so we should arrange to reset them as well.
2303
2304 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2305 lldb::StackFrameSP selected_frame_sp;
2306
2307 uint32_t selected_tid;
2308 if (selected_thread_sp != NULL)
2309 {
2310 selected_tid = selected_thread_sp->GetIndexID();
2311 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2312 }
2313 else
2314 {
2315 selected_tid = LLDB_INVALID_THREAD_ID;
2316 }
2317
2318 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2319
2320 Listener listener("ClangFunction temporary listener");
2321 exe_ctx.process->HijackProcessEvents(&listener);
2322
2323 Error resume_error = exe_ctx.process->Resume ();
2324 if (!resume_error.Success())
2325 {
2326 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2327 exe_ctx.process->RestoreProcessEvents();
2328 return Process::eExecutionSetupError;
2329 }
2330
2331 // We need to call the function synchronously, so spin waiting for it to return.
2332 // If we get interrupted while executing, we're going to lose our context, and
2333 // won't be able to gather the result at this point.
2334 // We set the timeout AFTER the resume, since the resume takes some time and we
2335 // don't want to charge that to the timeout.
2336
2337 TimeValue* timeout_ptr = NULL;
2338 TimeValue real_timeout;
2339
2340 if (single_thread_timeout_usec != 0)
2341 {
2342 real_timeout = TimeValue::Now();
2343 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2344 timeout_ptr = &real_timeout;
2345 }
2346
2347 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2348 while (1)
2349 {
2350 lldb::EventSP event_sp;
2351 lldb::StateType stop_state = lldb::eStateInvalid;
2352 // Now wait for the process to stop again:
2353 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2354
2355 if (!got_event)
2356 {
2357 // Right now this is the only way to tell we've timed out...
2358 // We should interrupt the process here...
2359 // Not really sure what to do if Halt fails here...
2360 if (log)
2361 if (try_all_threads)
2362 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2363 single_thread_timeout_usec);
2364 else
2365 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2366 single_thread_timeout_usec);
2367
2368 if (exe_ctx.process->Halt().Success())
2369 {
2370 timeout_ptr = NULL;
2371 if (log)
2372 log->Printf ("Halt succeeded.");
2373
2374 // Between the time that we got the timeout and the time we halted, but target
2375 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2376 // timeout to
2377 got_event = listener.WaitForEvent(NULL, event_sp);
2378
2379 if (got_event)
2380 {
2381 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2382 if (log)
2383 {
2384 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2385 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2386 log->Printf (" Event was the Halt interruption event.");
2387 }
2388
2389 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2390 {
2391 if (log)
2392 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
2393 return_value = Process::eExecutionCompleted;
2394 break;
2395 }
2396
2397 if (try_all_threads
2398 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2399 {
2400
2401 thread_plan_sp->SetStopOthers (false);
2402 if (log)
2403 log->Printf ("About to resume.");
2404
2405 exe_ctx.process->Resume();
2406 continue;
2407 }
2408 else
2409 {
2410 exe_ctx.process->RestoreProcessEvents ();
2411 return Process::eExecutionInterrupted;
2412 }
2413 }
2414 }
2415 }
2416
2417 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2418 if (log)
2419 log->Printf("Got event: %s.", StateAsCString(stop_state));
2420
2421 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2422 continue;
2423
2424 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2425 {
2426 return_value = Process::eExecutionCompleted;
2427 break;
2428 }
2429 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2430 {
2431 return_value = Process::eExecutionDiscarded;
2432 break;
2433 }
2434 else
2435 {
2436 if (log)
2437 {
2438 StreamString s;
2439 event_sp->Dump (&s);
2440 StreamString ts;
2441
2442 const char *event_explanation;
2443
2444 do
2445 {
2446 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2447
2448 if (!event_data)
2449 {
2450 event_explanation = "<no event data>";
2451 break;
2452 }
2453
2454 Process *process = event_data->GetProcessSP().get();
2455
2456 if (!process)
2457 {
2458 event_explanation = "<no process>";
2459 break;
2460 }
2461
2462 ThreadList &thread_list = process->GetThreadList();
2463
2464 uint32_t num_threads = thread_list.GetSize();
2465 uint32_t thread_index;
2466
2467 ts.Printf("<%u threads> ", num_threads);
2468
2469 for (thread_index = 0;
2470 thread_index < num_threads;
2471 ++thread_index)
2472 {
2473 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2474
2475 if (!thread)
2476 {
2477 ts.Printf("<?> ");
2478 continue;
2479 }
2480
2481 ts.Printf("<");
2482 RegisterContext *register_context = thread->GetRegisterContext();
2483
2484 if (register_context)
2485 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2486 else
2487 ts.Printf("[ip unknown] ");
2488
2489 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2490 if (stop_info_sp)
2491 {
2492 const char *stop_desc = stop_info_sp->GetDescription();
2493 if (stop_desc)
2494 ts.PutCString (stop_desc);
2495 }
2496 ts.Printf(">");
2497 }
2498
2499 event_explanation = ts.GetData();
2500 } while (0);
2501
2502 if (log)
2503 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2504 }
2505
2506 if (discard_on_error && thread_plan_sp)
2507 {
2508 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2509 }
2510 return_value = Process::eExecutionInterrupted;
2511 break;
2512 }
2513 }
2514
2515 if (exe_ctx.process)
2516 exe_ctx.process->RestoreProcessEvents ();
2517
2518 // Thread we ran the function in may have gone away because we ran the target
2519 // Check that it's still there.
2520 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2521 if (exe_ctx.thread)
2522 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2523
2524 // Also restore the current process'es selected frame & thread, since this function calling may
2525 // be done behind the user's back.
2526
2527 if (selected_tid != LLDB_INVALID_THREAD_ID)
2528 {
2529 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2530 {
2531 // We were able to restore the selected thread, now restore the frame:
2532 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2533 }
2534 }
2535
2536 return return_value;
2537}
2538
2539const char *
2540Process::ExecutionResultAsCString (ExecutionResults result)
2541{
2542 const char *result_name;
2543
2544 switch (result)
2545 {
2546 case Process::eExecutionCompleted:
2547 result_name = "eExecutionCompleted";
2548 break;
2549 case Process::eExecutionDiscarded:
2550 result_name = "eExecutionDiscarded";
2551 break;
2552 case Process::eExecutionInterrupted:
2553 result_name = "eExecutionInterrupted";
2554 break;
2555 case Process::eExecutionSetupError:
2556 result_name = "eExecutionSetupError";
2557 break;
2558 case Process::eExecutionTimedOut:
2559 result_name = "eExecutionTimedOut";
2560 break;
2561 }
2562 return result_name;
2563}
2564
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002565//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002566// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002567//--------------------------------------------------------------
2568
Greg Claytond0a5a232010-09-19 02:33:57 +00002569Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002570 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002571{
Caroline Tice004afcb2010-09-08 17:48:55 +00002572 m_default_settings.reset (new ProcessInstanceSettings (*this, false,
2573 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002574}
2575
Greg Claytond0a5a232010-09-19 02:33:57 +00002576Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002577{
2578}
2579
2580lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002581Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002582{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002583 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2584 false,
2585 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002586 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2587 return new_settings_sp;
2588}
2589
2590//--------------------------------------------------------------
2591// class ProcessInstanceSettings
2592//--------------------------------------------------------------
2593
Caroline Tice004afcb2010-09-08 17:48:55 +00002594ProcessInstanceSettings::ProcessInstanceSettings (UserSettingsController &owner, bool live_instance,
2595 const char *name) :
Caroline Tice75b11a32010-09-16 19:05:55 +00002596 InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002597 m_run_args (),
2598 m_env_vars (),
2599 m_input_path (),
2600 m_output_path (),
2601 m_error_path (),
2602 m_plugin (),
2603 m_disable_aslr (true)
2604{
Caroline Tice396704b2010-09-09 18:26:37 +00002605 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2606 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2607 // 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 +00002608 // This is true for CreateInstanceName() too.
2609
2610 if (GetInstanceName () == InstanceSettings::InvalidName())
2611 {
2612 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2613 m_owner.RegisterInstanceSettings (this);
2614 }
Caroline Tice396704b2010-09-09 18:26:37 +00002615
2616 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002617 {
2618 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2619 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002620 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002621 }
2622}
2623
2624ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002625 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002626 m_run_args (rhs.m_run_args),
2627 m_env_vars (rhs.m_env_vars),
2628 m_input_path (rhs.m_input_path),
2629 m_output_path (rhs.m_output_path),
2630 m_error_path (rhs.m_error_path),
2631 m_plugin (rhs.m_plugin),
2632 m_disable_aslr (rhs.m_disable_aslr)
2633{
2634 if (m_instance_name != InstanceSettings::GetDefaultName())
2635 {
2636 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2637 CopyInstanceSettings (pending_settings,false);
2638 m_owner.RemovePendingSettings (m_instance_name);
2639 }
2640}
2641
2642ProcessInstanceSettings::~ProcessInstanceSettings ()
2643{
2644}
2645
2646ProcessInstanceSettings&
2647ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2648{
2649 if (this != &rhs)
2650 {
2651 m_run_args = rhs.m_run_args;
2652 m_env_vars = rhs.m_env_vars;
2653 m_input_path = rhs.m_input_path;
2654 m_output_path = rhs.m_output_path;
2655 m_error_path = rhs.m_error_path;
2656 m_plugin = rhs.m_plugin;
2657 m_disable_aslr = rhs.m_disable_aslr;
2658 }
2659
2660 return *this;
2661}
2662
2663
2664void
2665ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2666 const char *index_value,
2667 const char *value,
2668 const ConstString &instance_name,
2669 const SettingEntry &entry,
2670 lldb::VarSetOperationType op,
2671 Error &err,
2672 bool pending)
2673{
2674 if (var_name == RunArgsVarName())
2675 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2676 else if (var_name == EnvVarsVarName())
2677 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2678 else if (var_name == InputPathVarName())
2679 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2680 else if (var_name == OutputPathVarName())
2681 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2682 else if (var_name == ErrorPathVarName())
2683 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2684 else if (var_name == PluginVarName())
2685 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
2686 else if (var_name == DisableASLRVarName())
2687 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
2688}
2689
2690void
2691ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2692 bool pending)
2693{
2694 if (new_settings.get() == NULL)
2695 return;
2696
2697 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2698
2699 m_run_args = new_process_settings->m_run_args;
2700 m_env_vars = new_process_settings->m_env_vars;
2701 m_input_path = new_process_settings->m_input_path;
2702 m_output_path = new_process_settings->m_output_path;
2703 m_error_path = new_process_settings->m_error_path;
2704 m_plugin = new_process_settings->m_plugin;
2705 m_disable_aslr = new_process_settings->m_disable_aslr;
2706}
2707
Caroline Ticebcb5b452010-09-20 21:37:42 +00002708bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002709ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2710 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00002711 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00002712 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002713{
2714 if (var_name == RunArgsVarName())
2715 {
2716 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00002717 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002718 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2719 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00002720 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002721 }
2722 else if (var_name == EnvVarsVarName())
2723 {
2724 if (m_env_vars.size() > 0)
2725 {
2726 std::map<std::string, std::string>::iterator pos;
2727 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2728 {
2729 StreamString value_str;
2730 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2731 value.AppendString (value_str.GetData());
2732 }
2733 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002734 }
2735 else if (var_name == InputPathVarName())
2736 {
2737 value.AppendString (m_input_path.c_str());
2738 }
2739 else if (var_name == OutputPathVarName())
2740 {
2741 value.AppendString (m_output_path.c_str());
2742 }
2743 else if (var_name == ErrorPathVarName())
2744 {
2745 value.AppendString (m_error_path.c_str());
2746 }
2747 else if (var_name == PluginVarName())
2748 {
2749 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2750 }
2751 else if (var_name == DisableASLRVarName())
2752 {
2753 if (m_disable_aslr)
2754 value.AppendString ("true");
2755 else
2756 value.AppendString ("false");
2757 }
2758 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00002759 {
2760 if (err)
2761 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2762 return false;
2763 }
2764 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002765}
2766
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002767const ConstString
2768ProcessInstanceSettings::CreateInstanceName ()
2769{
2770 static int instance_count = 1;
2771 StreamString sstr;
2772
2773 sstr.Printf ("process_%d", instance_count);
2774 ++instance_count;
2775
2776 const ConstString ret_val (sstr.GetData());
2777 return ret_val;
2778}
2779
2780const ConstString &
2781ProcessInstanceSettings::RunArgsVarName ()
2782{
2783 static ConstString run_args_var_name ("run-args");
2784
2785 return run_args_var_name;
2786}
2787
2788const ConstString &
2789ProcessInstanceSettings::EnvVarsVarName ()
2790{
2791 static ConstString env_vars_var_name ("env-vars");
2792
2793 return env_vars_var_name;
2794}
2795
2796const ConstString &
2797ProcessInstanceSettings::InputPathVarName ()
2798{
2799 static ConstString input_path_var_name ("input-path");
2800
2801 return input_path_var_name;
2802}
2803
2804const ConstString &
2805ProcessInstanceSettings::OutputPathVarName ()
2806{
Caroline Tice87097232010-09-07 18:35:40 +00002807 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002808
2809 return output_path_var_name;
2810}
2811
2812const ConstString &
2813ProcessInstanceSettings::ErrorPathVarName ()
2814{
Caroline Tice87097232010-09-07 18:35:40 +00002815 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002816
2817 return error_path_var_name;
2818}
2819
2820const ConstString &
2821ProcessInstanceSettings::PluginVarName ()
2822{
2823 static ConstString plugin_var_name ("plugin");
2824
2825 return plugin_var_name;
2826}
2827
2828
2829const ConstString &
2830ProcessInstanceSettings::DisableASLRVarName ()
2831{
2832 static ConstString disable_aslr_var_name ("disable-aslr");
2833
2834 return disable_aslr_var_name;
2835}
2836
2837
2838//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002839// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002840//--------------------------------------------------
2841
2842SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002843Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002844{
2845 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2846 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2847};
2848
2849
2850lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00002851Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002852{
Caroline Ticef2c330d2010-09-09 18:01:59 +00002853 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2854 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2855 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002856};
2857
2858SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002859Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002860{
2861 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2862 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2863 { "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." },
2864 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2865 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2866 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2867 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
Jim Ingham745ac7a2010-11-11 19:26:09 +00002868 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002869 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2870};
2871
2872
Jim Ingham7508e732010-08-09 23:31:02 +00002873