blob: f91c6194ea52fe87454a046cc728bc4d411f5b41 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham22777012010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Claytonc982c762010-07-09 20:39:50 +000056 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057 {
Greg Claytonc982c762010-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 Lattner30fdc8d2010-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 Claytoncfd1ace2010-10-31 03:01:06 +000072 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +000073 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074 m_target (target),
Chris Lattner30fdc8d2010-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 Clayton3af9ea52010-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 Ticeef5c6d02010-11-16 05:07:41 +000093 m_unix_signals (),
Greg Clayton3af9ea52010-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 Ticeef5c6d02010-11-16 05:07:41 +000098 m_process_input_reader (),
Greg Claytond46c87a2010-12-04 02:39:47 +000099 m_stdio_communication ("lldb.process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000100 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000101 m_stdout_data ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102{
Caroline Tice1559a462010-09-27 00:30:10 +0000103 UpdateInstanceName();
104
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000105 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106 if (log)
107 log->Printf ("%p Process::Process()", this);
108
Greg Claytoncfd1ace2010-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 Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000134 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-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 Clayton05faeb72010-10-07 04:19:01 +0000220 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000221 while (state != eStateInvalid)
222 {
Greg Clayton05faeb72010-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 Lattner30fdc8d2010-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 Ingham30f9b212010-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 Lattner30fdc8d2010-06-08 16:52:24 +0000256StateType
257Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
258{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000259 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-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 Clayton3fcbed62010-10-19 03:25:40 +0000265 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
266 this,
267 eBroadcastBitStateChanged,
268 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
270
Caroline Tice20ad3c42010-10-29 21:48:37 +0000271 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000283 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284
285 if (log)
286 log->Printf ("Process::%s...", __FUNCTION__);
287
288 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000289 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
290 eBroadcastBitStateChanged);
Caroline Tice20ad3c42010-10-29 21:48:37 +0000291 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000312 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000336 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-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
Greg Clayton85851dd2010-12-04 00:10:17 +0000361
362void
363Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
364{
365 if (m_inherit_host_env && !m_got_host_env)
366 {
367 m_got_host_env = true;
368 StringList host_env;
369 const size_t host_env_count = Host::GetEnvironment (host_env);
370 for (size_t idx=0; idx<host_env_count; idx++)
371 {
372 const char *env_entry = host_env.GetStringAtIndex (idx);
373 if (env_entry)
374 {
375 char *equal_pos = ::strchr(env_entry, '=');
376 if (equal_pos)
377 {
378 std::string key (env_entry, equal_pos - env_entry);
379 std::string value (equal_pos + 1);
380 if (m_env_vars.find (key) == m_env_vars.end())
381 m_env_vars[key] = value;
382 }
383 }
384 }
385 }
386}
387
388
389size_t
390Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
391{
392 GetHostEnvironmentIfNeeded ();
393
394 dictionary::const_iterator pos, end = m_env_vars.end();
395 for (pos = m_env_vars.begin(); pos != end; ++pos)
396 {
397 std::string env_var_equal_value (pos->first);
398 env_var_equal_value.append(1, '=');
399 env_var_equal_value.append (pos->second);
400 env.AppendArgument (env_var_equal_value.c_str());
401 }
402 return env.GetArgumentCount();
403}
404
405
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406const char *
407Process::GetExitDescription ()
408{
409 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
410 return m_exit_string.c_str();
411 return NULL;
412}
413
414void
415Process::SetExitStatus (int status, const char *cstr)
416{
Greg Clayton10177aa2010-12-08 05:08:21 +0000417 if (m_private_state.GetValue() != eStateExited)
418 {
419 m_exit_status = status;
420 if (cstr)
421 m_exit_string = cstr;
422 else
423 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000424
Greg Clayton10177aa2010-12-08 05:08:21 +0000425 DidExit ();
426
427 SetPrivateState (eStateExited);
428 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429}
430
431// This static callback can be used to watch for local child processes on
432// the current host. The the child process exits, the process will be
433// found in the global target list (we want to be completely sure that the
434// lldb_private::Process doesn't go away before we can deliver the signal.
435bool
436Process::SetProcessExitStatus
437(
438 void *callback_baton,
439 lldb::pid_t pid,
440 int signo, // Zero for no signal
441 int exit_status // Exit value of process if signal is zero
442)
443{
444 if (signo == 0 || exit_status)
445 {
Greg Clayton66111032010-06-23 01:19:29 +0000446 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447 if (target_sp)
448 {
449 ProcessSP process_sp (target_sp->GetProcessSP());
450 if (process_sp)
451 {
452 const char *signal_cstr = NULL;
453 if (signo)
454 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
455
456 process_sp->SetExitStatus (exit_status, signal_cstr);
457 }
458 }
459 return true;
460 }
461 return false;
462}
463
464
465uint32_t
466Process::GetNextThreadIndexID ()
467{
468 return ++m_thread_index_id;
469}
470
471StateType
472Process::GetState()
473{
474 // If any other threads access this we will need a mutex for it
475 return m_public_state.GetValue ();
476}
477
478void
479Process::SetPublicState (StateType new_state)
480{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000481 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000482 if (log)
483 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
484 m_public_state.SetValue (new_state);
485}
486
487StateType
488Process::GetPrivateState ()
489{
490 return m_private_state.GetValue();
491}
492
493void
494Process::SetPrivateState (StateType new_state)
495{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000496 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497 bool state_changed = false;
498
499 if (log)
500 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
501
502 Mutex::Locker locker(m_private_state.GetMutex());
503
504 const StateType old_state = m_private_state.GetValueNoLock ();
505 state_changed = old_state != new_state;
506 if (state_changed)
507 {
508 m_private_state.SetValueNoLock (new_state);
509 if (StateIsStoppedState(new_state))
510 {
511 m_stop_id++;
512 if (log)
513 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
514 }
515 // Use our target to get a shared pointer to ourselves...
516 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
517 }
518 else
519 {
520 if (log)
521 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
522 }
523}
524
525
526uint32_t
527Process::GetStopID() const
528{
529 return m_stop_id;
530}
531
532addr_t
533Process::GetImageInfoAddress()
534{
535 return LLDB_INVALID_ADDRESS;
536}
537
Greg Clayton8f343b02010-11-04 01:54:29 +0000538//----------------------------------------------------------------------
539// LoadImage
540//
541// This function provides a default implementation that works for most
542// unix variants. Any Process subclasses that need to do shared library
543// loading differently should override LoadImage and UnloadImage and
544// do what is needed.
545//----------------------------------------------------------------------
546uint32_t
547Process::LoadImage (const FileSpec &image_spec, Error &error)
548{
549 DynamicLoader *loader = GetDynamicLoader();
550 if (loader)
551 {
552 error = loader->CanLoadImage();
553 if (error.Fail())
554 return LLDB_INVALID_IMAGE_TOKEN;
555 }
556
557 if (error.Success())
558 {
559 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
560 if (thread_sp == NULL)
561 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
562
563 if (thread_sp)
564 {
565 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
566
567 if (frame_sp)
568 {
569 ExecutionContext exe_ctx;
570 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000571 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +0000572 StreamString expr;
573 char path[PATH_MAX];
574 image_spec.GetPath(path, sizeof(path));
575 expr.Printf("dlopen (\"%s\", 2)", path);
576 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000577 lldb::ValueObjectSP result_valobj_sp;
578 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000579 if (result_valobj_sp->GetError().Success())
580 {
581 Scalar scalar;
582 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
583 {
584 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
585 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
586 {
587 uint32_t image_token = m_image_tokens.size();
588 m_image_tokens.push_back (image_ptr);
589 return image_token;
590 }
591 }
592 }
593 }
594 }
595 }
596 return LLDB_INVALID_IMAGE_TOKEN;
597}
598
599//----------------------------------------------------------------------
600// UnloadImage
601//
602// This function provides a default implementation that works for most
603// unix variants. Any Process subclasses that need to do shared library
604// loading differently should override LoadImage and UnloadImage and
605// do what is needed.
606//----------------------------------------------------------------------
607Error
608Process::UnloadImage (uint32_t image_token)
609{
610 Error error;
611 if (image_token < m_image_tokens.size())
612 {
613 const addr_t image_addr = m_image_tokens[image_token];
614 if (image_addr == LLDB_INVALID_ADDRESS)
615 {
616 error.SetErrorString("image already unloaded");
617 }
618 else
619 {
620 DynamicLoader *loader = GetDynamicLoader();
621 if (loader)
622 error = loader->CanLoadImage();
623
624 if (error.Success())
625 {
626 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
627 if (thread_sp == NULL)
628 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
629
630 if (thread_sp)
631 {
632 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
633
634 if (frame_sp)
635 {
636 ExecutionContext exe_ctx;
637 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000638 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +0000639 StreamString expr;
640 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
641 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000642 lldb::ValueObjectSP result_valobj_sp;
643 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000644 if (result_valobj_sp->GetError().Success())
645 {
646 Scalar scalar;
647 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
648 {
649 if (scalar.UInt(1))
650 {
651 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
652 }
653 else
654 {
655 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
656 }
657 }
658 }
659 else
660 {
661 error = result_valobj_sp->GetError();
662 }
663 }
664 }
665 }
666 }
667 }
668 else
669 {
670 error.SetErrorString("invalid image token");
671 }
672 return error;
673}
674
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675DynamicLoader *
676Process::GetDynamicLoader()
677{
678 return NULL;
679}
680
681const ABI *
682Process::GetABI()
683{
684 ConstString& triple = m_target_triple;
685
686 if (triple.IsEmpty())
687 return NULL;
688
689 if (m_abi_sp.get() == NULL)
690 {
691 m_abi_sp.reset(ABI::FindPlugin(triple));
692 }
693
694 return m_abi_sp.get();
695}
696
Jim Ingham22777012010-09-23 02:01:19 +0000697LanguageRuntime *
698Process::GetLanguageRuntime(lldb::LanguageType language)
699{
700 LanguageRuntimeCollection::iterator pos;
701 pos = m_language_runtimes.find (language);
702 if (pos == m_language_runtimes.end())
703 {
704 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
705
706 m_language_runtimes[language]
707 = runtime;
708 return runtime.get();
709 }
710 else
711 return (*pos).second.get();
712}
713
714CPPLanguageRuntime *
715Process::GetCPPLanguageRuntime ()
716{
717 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
718 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
719 return static_cast<CPPLanguageRuntime *> (runtime);
720 return NULL;
721}
722
723ObjCLanguageRuntime *
724Process::GetObjCLanguageRuntime ()
725{
726 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
727 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
728 return static_cast<ObjCLanguageRuntime *> (runtime);
729 return NULL;
730}
731
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732BreakpointSiteList &
733Process::GetBreakpointSiteList()
734{
735 return m_breakpoint_site_list;
736}
737
738const BreakpointSiteList &
739Process::GetBreakpointSiteList() const
740{
741 return m_breakpoint_site_list;
742}
743
744
745void
746Process::DisableAllBreakpointSites ()
747{
748 m_breakpoint_site_list.SetEnabledForAll (false);
749}
750
751Error
752Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
753{
754 Error error (DisableBreakpointSiteByID (break_id));
755
756 if (error.Success())
757 m_breakpoint_site_list.Remove(break_id);
758
759 return error;
760}
761
762Error
763Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
764{
765 Error error;
766 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
767 if (bp_site_sp)
768 {
769 if (bp_site_sp->IsEnabled())
770 error = DisableBreakpoint (bp_site_sp.get());
771 }
772 else
773 {
774 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
775 }
776
777 return error;
778}
779
780Error
781Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
782{
783 Error error;
784 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
785 if (bp_site_sp)
786 {
787 if (!bp_site_sp->IsEnabled())
788 error = EnableBreakpoint (bp_site_sp.get());
789 }
790 else
791 {
792 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
793 }
794 return error;
795}
796
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000797lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
799{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000800 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801 if (load_addr != LLDB_INVALID_ADDRESS)
802 {
803 BreakpointSiteSP bp_site_sp;
804
805 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
806 // create a new breakpoint site and add it.
807
808 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
809
810 if (bp_site_sp)
811 {
812 bp_site_sp->AddOwner (owner);
813 owner->SetBreakpointSite (bp_site_sp);
814 return bp_site_sp->GetID();
815 }
816 else
817 {
818 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
819 if (bp_site_sp)
820 {
821 if (EnableBreakpoint (bp_site_sp.get()).Success())
822 {
823 owner->SetBreakpointSite (bp_site_sp);
824 return m_breakpoint_site_list.Add (bp_site_sp);
825 }
826 }
827 }
828 }
829 // We failed to enable the breakpoint
830 return LLDB_INVALID_BREAK_ID;
831
832}
833
834void
835Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
836{
837 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
838 if (num_owners == 0)
839 {
840 DisableBreakpoint(bp_site_sp.get());
841 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
842 }
843}
844
845
846size_t
847Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
848{
849 size_t bytes_removed = 0;
850 addr_t intersect_addr;
851 size_t intersect_size;
852 size_t opcode_offset;
853 size_t idx;
854 BreakpointSiteSP bp;
855
856 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
857 {
858 if (bp->GetType() == BreakpointSite::eSoftware)
859 {
860 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
861 {
862 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
863 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
864 assert(opcode_offset + intersect_size <= bp->GetByteSize());
865 size_t buf_offset = intersect_addr - bp_addr;
866 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
867 }
868 }
869 }
870 return bytes_removed;
871}
872
873
874Error
875Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
876{
877 Error error;
878 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000879 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 const addr_t bp_addr = bp_site->GetLoadAddress();
881 if (log)
882 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
883 if (bp_site->IsEnabled())
884 {
885 if (log)
886 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
887 return error;
888 }
889
890 if (bp_addr == LLDB_INVALID_ADDRESS)
891 {
892 error.SetErrorString("BreakpointSite contains an invalid load address.");
893 return error;
894 }
895 // Ask the lldb::Process subclass to fill in the correct software breakpoint
896 // trap for the breakpoint site
897 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
898
899 if (bp_opcode_size == 0)
900 {
901 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
902 }
903 else
904 {
905 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
906
907 if (bp_opcode_bytes == NULL)
908 {
909 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
910 return error;
911 }
912
913 // Save the original opcode by reading it
914 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
915 {
916 // Write a software breakpoint in place of the original opcode
917 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
918 {
919 uint8_t verify_bp_opcode_bytes[64];
920 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
921 {
922 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
923 {
924 bp_site->SetEnabled(true);
925 bp_site->SetType (BreakpointSite::eSoftware);
926 if (log)
927 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
928 bp_site->GetID(),
929 (uint64_t)bp_addr);
930 }
931 else
932 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
933 }
934 else
935 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
936 }
937 else
938 error.SetErrorString("Unable to write breakpoint trap to memory.");
939 }
940 else
941 error.SetErrorString("Unable to read memory at breakpoint address.");
942 }
943 if (log)
944 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
945 bp_site->GetID(),
946 (uint64_t)bp_addr,
947 error.AsCString());
948 return error;
949}
950
951Error
952Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
953{
954 Error error;
955 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000956 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957 addr_t bp_addr = bp_site->GetLoadAddress();
958 lldb::user_id_t breakID = bp_site->GetID();
959 if (log)
960 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
961
962 if (bp_site->IsHardware())
963 {
964 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
965 }
966 else if (bp_site->IsEnabled())
967 {
968 const size_t break_op_size = bp_site->GetByteSize();
969 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
970 if (break_op_size > 0)
971 {
972 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +0000973 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000974 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 bool break_op_found = false;
976
977 // Read the breakpoint opcode
978 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
979 {
980 bool verify = false;
981 // Make sure we have the a breakpoint opcode exists at this address
982 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
983 {
984 break_op_found = true;
985 // We found a valid breakpoint opcode at this address, now restore
986 // the saved opcode.
987 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
988 {
989 verify = true;
990 }
991 else
992 error.SetErrorString("Memory write failed when restoring original opcode.");
993 }
994 else
995 {
996 error.SetErrorString("Original breakpoint trap is no longer in memory.");
997 // Set verify to true and so we can check if the original opcode has already been restored
998 verify = true;
999 }
1000
1001 if (verify)
1002 {
Greg Claytonc982c762010-07-09 20:39:50 +00001003 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001004 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 // Verify that our original opcode made it back to the inferior
1006 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1007 {
1008 // compare the memory we just read with the original opcode
1009 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1010 {
1011 // SUCCESS
1012 bp_site->SetEnabled(false);
1013 if (log)
1014 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1015 return error;
1016 }
1017 else
1018 {
1019 if (break_op_found)
1020 error.SetErrorString("Failed to restore original opcode.");
1021 }
1022 }
1023 else
1024 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1025 }
1026 }
1027 else
1028 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1029 }
1030 }
1031 else
1032 {
1033 if (log)
1034 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1035 return error;
1036 }
1037
1038 if (log)
1039 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1040 bp_site->GetID(),
1041 (uint64_t)bp_addr,
1042 error.AsCString());
1043 return error;
1044
1045}
1046
1047
1048size_t
1049Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1050{
1051 if (buf == NULL || size == 0)
1052 return 0;
1053
1054 size_t bytes_read = 0;
1055 uint8_t *bytes = (uint8_t *)buf;
1056
1057 while (bytes_read < size)
1058 {
1059 const size_t curr_size = size - bytes_read;
1060 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1061 bytes + bytes_read,
1062 curr_size,
1063 error);
1064 bytes_read += curr_bytes_read;
1065 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1066 break;
1067 }
1068
1069 // Replace any software breakpoint opcodes that fall into this range back
1070 // into "buf" before we return
1071 if (bytes_read > 0)
1072 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1073 return bytes_read;
1074}
1075
1076size_t
1077Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1078{
1079 size_t bytes_written = 0;
1080 const uint8_t *bytes = (const uint8_t *)buf;
1081
1082 while (bytes_written < size)
1083 {
1084 const size_t curr_size = size - bytes_written;
1085 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1086 bytes + bytes_written,
1087 curr_size,
1088 error);
1089 bytes_written += curr_bytes_written;
1090 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1091 break;
1092 }
1093 return bytes_written;
1094}
1095
1096size_t
1097Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1098{
1099 if (buf == NULL || size == 0)
1100 return 0;
1101 // We need to write any data that would go where any current software traps
1102 // (enabled software breakpoints) any software traps (breakpoints) that we
1103 // may have placed in our tasks memory.
1104
1105 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1106 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1107
1108 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1109 return DoWriteMemory(addr, buf, size, error);
1110
1111 BreakpointSiteList::collection::const_iterator pos;
1112 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001113 addr_t intersect_addr = 0;
1114 size_t intersect_size = 0;
1115 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 const uint8_t *ubuf = (const uint8_t *)buf;
1117
1118 for (pos = iter; pos != end; ++pos)
1119 {
1120 BreakpointSiteSP bp;
1121 bp = pos->second;
1122
1123 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1124 assert(addr <= intersect_addr && intersect_addr < addr + size);
1125 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1126 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1127
1128 // Check for bytes before this breakpoint
1129 const addr_t curr_addr = addr + bytes_written;
1130 if (intersect_addr > curr_addr)
1131 {
1132 // There are some bytes before this breakpoint that we need to
1133 // just write to memory
1134 size_t curr_size = intersect_addr - curr_addr;
1135 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1136 ubuf + bytes_written,
1137 curr_size,
1138 error);
1139 bytes_written += curr_bytes_written;
1140 if (curr_bytes_written != curr_size)
1141 {
1142 // We weren't able to write all of the requested bytes, we
1143 // are done looping and will return the number of bytes that
1144 // we have written so far.
1145 break;
1146 }
1147 }
1148
1149 // Now write any bytes that would cover up any software breakpoints
1150 // directly into the breakpoint opcode buffer
1151 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1152 bytes_written += intersect_size;
1153 }
1154
1155 // Write any remaining bytes after the last breakpoint if we have any left
1156 if (bytes_written < size)
1157 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1158 ubuf + bytes_written,
1159 size - bytes_written,
1160 error);
1161
1162 return bytes_written;
1163}
1164
1165addr_t
1166Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1167{
1168 // Fixme: we should track the blocks we've allocated, and clean them up...
1169 // We could even do our own allocator here if that ends up being more efficient.
1170 return DoAllocateMemory (size, permissions, error);
1171}
1172
1173Error
1174Process::DeallocateMemory (addr_t ptr)
1175{
1176 return DoDeallocateMemory (ptr);
1177}
1178
1179
1180Error
1181Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1182{
1183 Error error;
1184 error.SetErrorString("watchpoints are not supported");
1185 return error;
1186}
1187
1188Error
1189Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1190{
1191 Error error;
1192 error.SetErrorString("watchpoints are not supported");
1193 return error;
1194}
1195
1196StateType
1197Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1198{
1199 StateType state;
1200 // Now wait for the process to launch and return control to us, and then
1201 // call DidLaunch:
1202 while (1)
1203 {
1204 // FIXME: Might want to put a timeout in here:
1205 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1206 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1207 break;
1208 else
1209 HandlePrivateEvent (event_sp);
1210 }
1211 return state;
1212}
1213
1214Error
1215Process::Launch
1216(
1217 char const *argv[],
1218 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001219 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001220 const char *stdin_path,
1221 const char *stdout_path,
1222 const char *stderr_path
1223)
1224{
1225 Error error;
1226 m_target_triple.Clear();
1227 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001228 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001229
1230 Module *exe_module = m_target.GetExecutableModule().get();
1231 if (exe_module)
1232 {
1233 char exec_file_path[PATH_MAX];
1234 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1235 if (exe_module->GetFileSpec().Exists())
1236 {
1237 error = WillLaunch (exe_module);
1238 if (error.Success())
1239 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001240 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001241 // The args coming in should not contain the application name, the
1242 // lldb_private::Process class will add this in case the executable
1243 // gets resolved to a different file than was given on the command
1244 // line (like when an applicaiton bundle is specified and will
1245 // resolve to the contained exectuable file, or the file given was
1246 // a symlink or other file system link that resolves to a different
1247 // file).
1248
1249 // Get the resolved exectuable path
1250
1251 // Make a new argument vector
1252 std::vector<const char *> exec_path_plus_argv;
1253 // Append the resolved executable path
1254 exec_path_plus_argv.push_back (exec_file_path);
1255
1256 // Push all args if there are any
1257 if (argv)
1258 {
1259 for (int i = 0; argv[i]; ++i)
1260 exec_path_plus_argv.push_back(argv[i]);
1261 }
1262
1263 // Push a NULL to terminate the args.
1264 exec_path_plus_argv.push_back(NULL);
1265
1266 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001267 error = DoLaunch (exe_module,
1268 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1269 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001270 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001271 stdin_path,
1272 stdout_path,
1273 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001274
1275 if (error.Fail())
1276 {
1277 if (GetID() != LLDB_INVALID_PROCESS_ID)
1278 {
1279 SetID (LLDB_INVALID_PROCESS_ID);
1280 const char *error_string = error.AsCString();
1281 if (error_string == NULL)
1282 error_string = "launch failed";
1283 SetExitStatus (-1, error_string);
1284 }
1285 }
1286 else
1287 {
1288 EventSP event_sp;
1289 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1290
1291 if (state == eStateStopped || state == eStateCrashed)
1292 {
1293 DidLaunch ();
1294
1295 // This delays passing the stopped event to listeners till DidLaunch gets
1296 // a chance to complete...
1297 HandlePrivateEvent (event_sp);
1298 StartPrivateStateThread ();
1299 }
1300 else if (state == eStateExited)
1301 {
1302 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1303 // not likely to work, and return an invalid pid.
1304 HandlePrivateEvent (event_sp);
1305 }
1306 }
1307 }
1308 }
1309 else
1310 {
1311 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1312 }
1313 }
1314 return error;
1315}
1316
1317Error
1318Process::CompleteAttach ()
1319{
1320 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001321
1322 if (GetID() == LLDB_INVALID_PROCESS_ID)
1323 {
1324 error.SetErrorString("no process");
1325 }
1326
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001327 EventSP event_sp;
1328 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1329 if (state == eStateStopped || state == eStateCrashed)
1330 {
1331 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001332 // Figure out which one is the executable, and set that in our target:
1333 ModuleList &modules = GetTarget().GetImages();
1334
1335 size_t num_modules = modules.GetSize();
1336 for (int i = 0; i < num_modules; i++)
1337 {
1338 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1339 if (module_sp->IsExecutable())
1340 {
1341 ModuleSP exec_module = GetTarget().GetExecutableModule();
1342 if (!exec_module || exec_module != module_sp)
1343 {
1344
1345 GetTarget().SetExecutableModule (module_sp, false);
1346 }
1347 break;
1348 }
1349 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350
1351 // This delays passing the stopped event to listeners till DidLaunch gets
1352 // a chance to complete...
1353 HandlePrivateEvent(event_sp);
1354 StartPrivateStateThread();
1355 }
1356 else
1357 {
1358 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1359 // not likely to work, and return an invalid pid.
1360 if (state == eStateExited)
1361 HandlePrivateEvent (event_sp);
1362 error.SetErrorStringWithFormat("invalid state after attach: %s",
1363 lldb_private::StateAsCString(state));
1364 }
1365 return error;
1366}
1367
1368Error
1369Process::Attach (lldb::pid_t attach_pid)
1370{
1371
1372 m_target_triple.Clear();
1373 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001374 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375
Jim Ingham5aee1622010-08-09 23:31:02 +00001376 // Find the process and its architecture. Make sure it matches the architecture
1377 // of the current Target, and if not adjust it.
1378
1379 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1380 if (attach_spec != GetTarget().GetArchitecture())
1381 {
1382 // Set the architecture on the target.
1383 GetTarget().SetArchitecture(attach_spec);
1384 }
1385
Greg Claytonc982c762010-07-09 20:39:50 +00001386 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387 if (error.Success())
1388 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001389 SetPublicState (eStateAttaching);
1390
Greg Claytonc982c762010-07-09 20:39:50 +00001391 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 if (error.Success())
1393 {
1394 error = CompleteAttach();
1395 }
1396 else
1397 {
1398 if (GetID() != LLDB_INVALID_PROCESS_ID)
1399 {
1400 SetID (LLDB_INVALID_PROCESS_ID);
1401 const char *error_string = error.AsCString();
1402 if (error_string == NULL)
1403 error_string = "attach failed";
1404
1405 SetExitStatus(-1, error_string);
1406 }
1407 }
1408 }
1409 return error;
1410}
1411
1412Error
1413Process::Attach (const char *process_name, bool wait_for_launch)
1414{
1415 m_target_triple.Clear();
1416 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001417 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001418
1419 // Find the process and its architecture. Make sure it matches the architecture
1420 // of the current Target, and if not adjust it.
1421
Jim Ingham2ecb7422010-08-17 21:54:19 +00001422 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001423 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001424 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001425 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001426 {
1427 // Set the architecture on the target.
1428 GetTarget().SetArchitecture(attach_spec);
1429 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001430 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001431
Greg Claytonc982c762010-07-09 20:39:50 +00001432 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433 if (error.Success())
1434 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001435 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001436 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 if (error.Fail())
1438 {
1439 if (GetID() != LLDB_INVALID_PROCESS_ID)
1440 {
1441 SetID (LLDB_INVALID_PROCESS_ID);
1442 const char *error_string = error.AsCString();
1443 if (error_string == NULL)
1444 error_string = "attach failed";
1445
1446 SetExitStatus(-1, error_string);
1447 }
1448 }
1449 else
1450 {
1451 error = CompleteAttach();
1452 }
1453 }
1454 return error;
1455}
1456
1457Error
1458Process::Resume ()
1459{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001460 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001461 if (log)
1462 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1463
1464 Error error (WillResume());
1465 // Tell the process it is about to resume before the thread list
1466 if (error.Success())
1467 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001468 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 // can let all of our threads know that they are about to be
1470 // resumed. Threads will each be called with
1471 // Thread::WillResume(StateType) where StateType contains the state
1472 // that they are supposed to have when the process is resumed
1473 // (suspended/running/stepping). Threads should also check
1474 // their resume signal in lldb::Thread::GetResumeSignal()
1475 // to see if they are suppoed to start back up with a signal.
1476 if (m_thread_list.WillResume())
1477 {
1478 error = DoResume();
1479 if (error.Success())
1480 {
1481 DidResume();
1482 m_thread_list.DidResume();
1483 }
1484 }
1485 else
1486 {
1487 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1488 }
1489 }
1490 return error;
1491}
1492
1493Error
1494Process::Halt ()
1495{
1496 Error error (WillHalt());
1497
1498 if (error.Success())
1499 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001500
1501 bool caused_stop = false;
1502 EventSP event_sp;
1503
1504 // Pause our private state thread so we can ensure no one else eats
1505 // the stop event out from under us.
1506 PausePrivateStateThread();
1507
1508 // Ask the process subclass to actually halt our process
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001509 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001511 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001512 // If "caused_stop" is true, then DoHalt stopped the process. If
1513 // "caused_stop" is false, the process was already stopped.
1514 // If the DoHalt caused the process to stop, then we want to catch
1515 // this event and set the interrupted bool to true before we pass
1516 // this along so clients know that the process was interrupted by
1517 // a halt command.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001518 if (caused_stop)
1519 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001520 // Wait for 2 seconds for the process to stop.
1521 TimeValue timeout_time;
1522 timeout_time = TimeValue::Now();
1523 timeout_time.OffsetWithSeconds(2);
1524 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1525
1526 if (state == eStateInvalid)
1527 {
1528 // We timeout out and didn't get a stop event...
1529 error.SetErrorString ("Halt timed out.");
1530 }
1531 else
1532 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001533 if (StateIsStoppedState (state))
1534 {
1535 // We caused the process to interrupt itself, so mark this
1536 // as such in the stop event so clients can tell an interrupted
1537 // process from a natural stop
1538 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1539 }
1540 else
1541 {
1542 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1543 if (log)
1544 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1545 error.SetErrorString ("Did not get stopped event after halt.");
1546 }
1547 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001548 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001549 DidHalt();
1550
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001551 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001552 // Resume our private state thread before we post the event (if any)
1553 ResumePrivateStateThread();
1554
1555 // Post any event we might have consumed. If all goes well, we will have
1556 // stopped the process, intercepted the event and set the interrupted
Jim Inghamf48169b2010-11-30 02:22:11 +00001557 // bool in the event. Post it to the private event queue and that will end up
1558 // correctly setting the state.
Greg Clayton3af9ea52010-11-18 05:57:03 +00001559 if (event_sp)
Caroline Ticeefed6132010-11-19 20:47:54 +00001560 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001561
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001562 }
1563 return error;
1564}
1565
1566Error
1567Process::Detach ()
1568{
1569 Error error (WillDetach());
1570
1571 if (error.Success())
1572 {
1573 DisableAllBreakpointSites();
1574 error = DoDetach();
1575 if (error.Success())
1576 {
1577 DidDetach();
1578 StopPrivateStateThread();
1579 }
1580 }
1581 return error;
1582}
1583
1584Error
1585Process::Destroy ()
1586{
1587 Error error (WillDestroy());
1588 if (error.Success())
1589 {
1590 DisableAllBreakpointSites();
1591 error = DoDestroy();
1592 if (error.Success())
1593 {
1594 DidDestroy();
1595 StopPrivateStateThread();
1596 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001597 m_stdio_communication.StopReadThread();
1598 m_stdio_communication.Disconnect();
1599 if (m_process_input_reader && m_process_input_reader->IsActive())
1600 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1601 if (m_process_input_reader)
1602 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001603 }
1604 return error;
1605}
1606
1607Error
1608Process::Signal (int signal)
1609{
1610 Error error (WillSignal());
1611 if (error.Success())
1612 {
1613 error = DoSignal(signal);
1614 if (error.Success())
1615 DidSignal();
1616 }
1617 return error;
1618}
1619
1620UnixSignals &
1621Process::GetUnixSignals ()
1622{
1623 return m_unix_signals;
1624}
1625
1626Target &
1627Process::GetTarget ()
1628{
1629 return m_target;
1630}
1631
1632const Target &
1633Process::GetTarget () const
1634{
1635 return m_target;
1636}
1637
1638uint32_t
1639Process::GetAddressByteSize()
1640{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001641 if (m_addr_byte_size == 0)
1642 return m_target.GetArchitecture().GetAddressByteSize();
1643 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001644}
1645
1646bool
1647Process::ShouldBroadcastEvent (Event *event_ptr)
1648{
1649 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1650 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001651 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652
1653 switch (state)
1654 {
1655 case eStateAttaching:
1656 case eStateLaunching:
1657 case eStateDetached:
1658 case eStateExited:
1659 case eStateUnloaded:
1660 // These events indicate changes in the state of the debugging session, always report them.
1661 return_value = true;
1662 break;
1663 case eStateInvalid:
1664 // We stopped for no apparent reason, don't report it.
1665 return_value = false;
1666 break;
1667 case eStateRunning:
1668 case eStateStepping:
1669 // If we've started the target running, we handle the cases where we
1670 // are already running and where there is a transition from stopped to
1671 // running differently.
1672 // running -> running: Automatically suppress extra running events
1673 // stopped -> running: Report except when there is one or more no votes
1674 // and no yes votes.
1675 SynchronouslyNotifyStateChanged (state);
1676 switch (m_public_state.GetValue())
1677 {
1678 case eStateRunning:
1679 case eStateStepping:
1680 // We always suppress multiple runnings with no PUBLIC stop in between.
1681 return_value = false;
1682 break;
1683 default:
1684 // TODO: make this work correctly. For now always report
1685 // run if we aren't running so we don't miss any runnning
1686 // events. If I run the lldb/test/thread/a.out file and
1687 // break at main.cpp:58, run and hit the breakpoints on
1688 // multiple threads, then somehow during the stepping over
1689 // of all breakpoints no run gets reported.
1690 return_value = true;
1691
1692 // This is a transition from stop to run.
1693 switch (m_thread_list.ShouldReportRun (event_ptr))
1694 {
1695 case eVoteYes:
1696 case eVoteNoOpinion:
1697 return_value = true;
1698 break;
1699 case eVoteNo:
1700 return_value = false;
1701 break;
1702 }
1703 break;
1704 }
1705 break;
1706 case eStateStopped:
1707 case eStateCrashed:
1708 case eStateSuspended:
1709 {
1710 // We've stopped. First see if we're going to restart the target.
1711 // If we are going to stop, then we always broadcast the event.
1712 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00001713 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001714 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001716 if (log)
1717 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001718 return true;
1719 }
1720 else
1721 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001722 RefreshStateAfterStop ();
1723
1724 if (m_thread_list.ShouldStop (event_ptr) == false)
1725 {
1726 switch (m_thread_list.ShouldReportStop (event_ptr))
1727 {
1728 case eVoteYes:
1729 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00001730 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 case eVoteNo:
1733 return_value = false;
1734 break;
1735 }
1736
1737 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001738 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001739 Resume ();
1740 }
1741 else
1742 {
1743 return_value = true;
1744 SynchronouslyNotifyStateChanged (state);
1745 }
1746 }
1747 }
1748 }
1749
1750 if (log)
1751 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1752 return return_value;
1753}
1754
1755//------------------------------------------------------------------
1756// Thread Queries
1757//------------------------------------------------------------------
1758
1759ThreadList &
1760Process::GetThreadList ()
1761{
1762 return m_thread_list;
1763}
1764
1765const ThreadList &
1766Process::GetThreadList () const
1767{
1768 return m_thread_list;
1769}
1770
1771
1772bool
1773Process::StartPrivateStateThread ()
1774{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001775 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001776
1777 if (log)
1778 log->Printf ("Process::%s ( )", __FUNCTION__);
1779
1780 // Create a thread that watches our internal state and controls which
1781 // events make it to clients (into the DCProcess event queue).
1782 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1783 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1784}
1785
1786void
1787Process::PausePrivateStateThread ()
1788{
1789 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1790}
1791
1792void
1793Process::ResumePrivateStateThread ()
1794{
1795 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1796}
1797
1798void
1799Process::StopPrivateStateThread ()
1800{
1801 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1802}
1803
1804void
1805Process::ControlPrivateStateThread (uint32_t signal)
1806{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001807 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808
1809 assert (signal == eBroadcastInternalStateControlStop ||
1810 signal == eBroadcastInternalStateControlPause ||
1811 signal == eBroadcastInternalStateControlResume);
1812
1813 if (log)
1814 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1815
1816 // Signal the private state thread
1817 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1818 {
1819 TimeValue timeout_time;
1820 bool timed_out;
1821
1822 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1823
1824 timeout_time = TimeValue::Now();
1825 timeout_time.OffsetWithSeconds(2);
1826 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1827 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1828
1829 if (signal == eBroadcastInternalStateControlStop)
1830 {
1831 if (timed_out)
1832 Host::ThreadCancel (m_private_state_thread, NULL);
1833
1834 thread_result_t result = NULL;
1835 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00001836 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
1838 }
1839}
1840
1841void
1842Process::HandlePrivateEvent (EventSP &event_sp)
1843{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001844 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1846 // See if we should broadcast this state to external clients?
1847 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1848 if (log)
1849 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1850
1851 if (should_broadcast)
1852 {
1853 if (log)
1854 {
1855 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1856 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001857 if (StateIsRunningState (internal_state))
1858 PushProcessInputReader ();
1859 else
1860 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001861 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1862 BroadcastEvent (event_sp);
1863 }
1864 else
1865 {
1866 if (log)
1867 {
1868 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1869 }
1870 }
1871}
1872
1873void *
1874Process::PrivateStateThread (void *arg)
1875{
1876 Process *proc = static_cast<Process*> (arg);
1877 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878 return result;
1879}
1880
1881void *
1882Process::RunPrivateStateThread ()
1883{
1884 bool control_only = false;
1885 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1886
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001887 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888 if (log)
1889 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1890
1891 bool exit_now = false;
1892 while (!exit_now)
1893 {
1894 EventSP event_sp;
1895 WaitForEventsPrivate (NULL, event_sp, control_only);
1896 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1897 {
1898 switch (event_sp->GetType())
1899 {
1900 case eBroadcastInternalStateControlStop:
1901 exit_now = true;
1902 continue; // Go to next loop iteration so we exit without
1903 break; // doing any internal state managment below
1904
1905 case eBroadcastInternalStateControlPause:
1906 control_only = true;
1907 break;
1908
1909 case eBroadcastInternalStateControlResume:
1910 control_only = false;
1911 break;
1912 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001913
1914 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1915 if (log)
1916 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
1917
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001918 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001919 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920 }
1921
1922
1923 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1924
1925 if (internal_state != eStateInvalid)
1926 {
1927 HandlePrivateEvent (event_sp);
1928 }
1929
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001930 if (internal_state == eStateInvalid ||
1931 internal_state == eStateExited ||
1932 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001933 {
1934 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1935 if (log)
1936 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
1937
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001939 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 }
1941
Caroline Tice20ad3c42010-10-29 21:48:37 +00001942 // Verify log is still enabled before attempting to write to it...
1943 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001944 if (log)
1945 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1946
Greg Claytonbe77e3b2010-08-19 21:50:06 +00001947 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948 return NULL;
1949}
1950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951//------------------------------------------------------------------
1952// Process Event Data
1953//------------------------------------------------------------------
1954
1955Process::ProcessEventData::ProcessEventData () :
1956 EventData (),
1957 m_process_sp (),
1958 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00001959 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001960 m_update_state (false),
1961 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962{
1963}
1964
1965Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1966 EventData (),
1967 m_process_sp (process_sp),
1968 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00001969 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001970 m_update_state (false),
1971 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972{
1973}
1974
1975Process::ProcessEventData::~ProcessEventData()
1976{
1977}
1978
1979const ConstString &
1980Process::ProcessEventData::GetFlavorString ()
1981{
1982 static ConstString g_flavor ("Process::ProcessEventData");
1983 return g_flavor;
1984}
1985
1986const ConstString &
1987Process::ProcessEventData::GetFlavor () const
1988{
1989 return ProcessEventData::GetFlavorString ();
1990}
1991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001992void
1993Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1994{
1995 // This function gets called twice for each event, once when the event gets pulled
1996 // off of the private process event queue, and once when it gets pulled off of
1997 // the public event queue. m_update_state is used to distinguish these
1998 // two cases; it is false when we're just pulling it off for private handling,
1999 // and we don't want to do the breakpoint command handling then.
2000
2001 if (!m_update_state)
2002 return;
2003
2004 m_process_sp->SetPublicState (m_state);
2005
2006 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2007 if (m_state == eStateStopped && ! m_restarted)
2008 {
2009 int num_threads = m_process_sp->GetThreadList().GetSize();
2010 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002011
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 for (idx = 0; idx < num_threads; ++idx)
2013 {
2014 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2015
Jim Inghamb15bfc72010-10-20 00:39:53 +00002016 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2017 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002018 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002019 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002020 }
2021 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002022
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002023 // The stop action might restart the target. If it does, then we want to mark that in the
2024 // event so that whoever is receiving it will know to wait for the running event and reflect
2025 // that state appropriately.
2026
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027 if (m_process_sp->GetPrivateState() == eStateRunning)
2028 SetRestarted(true);
2029 }
2030}
2031
2032void
2033Process::ProcessEventData::Dump (Stream *s) const
2034{
2035 if (m_process_sp)
2036 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2037
2038 s->Printf("state = %s", StateAsCString(GetState()));;
2039}
2040
2041const Process::ProcessEventData *
2042Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2043{
2044 if (event_ptr)
2045 {
2046 const EventData *event_data = event_ptr->GetData();
2047 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2048 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2049 }
2050 return NULL;
2051}
2052
2053ProcessSP
2054Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2055{
2056 ProcessSP process_sp;
2057 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2058 if (data)
2059 process_sp = data->GetProcessSP();
2060 return process_sp;
2061}
2062
2063StateType
2064Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2065{
2066 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2067 if (data == NULL)
2068 return eStateInvalid;
2069 else
2070 return data->GetState();
2071}
2072
2073bool
2074Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2075{
2076 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2077 if (data == NULL)
2078 return false;
2079 else
2080 return data->GetRestarted();
2081}
2082
2083void
2084Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2085{
2086 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2087 if (data != NULL)
2088 data->SetRestarted(new_value);
2089}
2090
2091bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002092Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2093{
2094 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2095 if (data == NULL)
2096 return false;
2097 else
2098 return data->GetInterrupted ();
2099}
2100
2101void
2102Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2103{
2104 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2105 if (data != NULL)
2106 data->SetInterrupted(new_value);
2107}
2108
2109bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2111{
2112 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2113 if (data)
2114 {
2115 data->SetUpdateStateOnRemoval();
2116 return true;
2117 }
2118 return false;
2119}
2120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121Target *
2122Process::CalculateTarget ()
2123{
2124 return &m_target;
2125}
2126
2127Process *
2128Process::CalculateProcess ()
2129{
2130 return this;
2131}
2132
2133Thread *
2134Process::CalculateThread ()
2135{
2136 return NULL;
2137}
2138
2139StackFrame *
2140Process::CalculateStackFrame ()
2141{
2142 return NULL;
2143}
2144
2145void
Greg Clayton0603aa92010-10-04 01:05:56 +00002146Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147{
2148 exe_ctx.target = &m_target;
2149 exe_ctx.process = this;
2150 exe_ctx.thread = NULL;
2151 exe_ctx.frame = NULL;
2152}
2153
2154lldb::ProcessSP
2155Process::GetSP ()
2156{
2157 return GetTarget().GetProcessSP();
2158}
2159
Sean Callanan2235f322010-08-11 03:57:18 +00002160ClangPersistentVariables &
2161Process::GetPersistentVariables()
2162{
2163 return m_persistent_vars;
2164}
2165
Jim Ingham5aee1622010-08-09 23:31:02 +00002166uint32_t
2167Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2168{
2169 return 0;
2170}
2171
2172ArchSpec
2173Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2174{
2175 return Host::GetArchSpecForExistingProcess (pid);
2176}
2177
2178ArchSpec
2179Process::GetArchSpecForExistingProcess (const char *process_name)
2180{
2181 return Host::GetArchSpecForExistingProcess (process_name);
2182}
2183
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002184void
2185Process::AppendSTDOUT (const char * s, size_t len)
2186{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002187 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002188 m_stdout_data.append (s, len);
2189
Greg Claytona9ff3062010-12-05 19:16:56 +00002190 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002191}
2192
2193void
2194Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2195{
2196 Process *process = (Process *) baton;
2197 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2198}
2199
2200size_t
2201Process::ProcessInputReaderCallback (void *baton,
2202 InputReader &reader,
2203 lldb::InputReaderAction notification,
2204 const char *bytes,
2205 size_t bytes_len)
2206{
2207 Process *process = (Process *) baton;
2208
2209 switch (notification)
2210 {
2211 case eInputReaderActivate:
2212 break;
2213
2214 case eInputReaderDeactivate:
2215 break;
2216
2217 case eInputReaderReactivate:
2218 break;
2219
2220 case eInputReaderGotToken:
2221 {
2222 Error error;
2223 process->PutSTDIN (bytes, bytes_len, error);
2224 }
2225 break;
2226
Caroline Ticeefed6132010-11-19 20:47:54 +00002227 case eInputReaderInterrupt:
2228 process->Halt ();
2229 break;
2230
2231 case eInputReaderEndOfFile:
2232 process->AppendSTDOUT ("^D", 2);
2233 break;
2234
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002235 case eInputReaderDone:
2236 break;
2237
2238 }
2239
2240 return bytes_len;
2241}
2242
2243void
2244Process::ResetProcessInputReader ()
2245{
2246 m_process_input_reader.reset();
2247}
2248
2249void
2250Process::SetUpProcessInputReader (int file_descriptor)
2251{
2252 // First set up the Read Thread for reading/handling process I/O
2253
2254 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2255
2256 if (conn_ap.get())
2257 {
2258 m_stdio_communication.SetConnection (conn_ap.release());
2259 if (m_stdio_communication.IsConnected())
2260 {
2261 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2262 m_stdio_communication.StartReadThread();
2263
2264 // Now read thread is set up, set up input reader.
2265
2266 if (!m_process_input_reader.get())
2267 {
2268 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2269 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2270 this,
2271 eInputReaderGranularityByte,
2272 NULL,
2273 NULL,
2274 false));
2275
2276 if (err.Fail())
2277 m_process_input_reader.reset();
2278 }
2279 }
2280 }
2281}
2282
2283void
2284Process::PushProcessInputReader ()
2285{
2286 if (m_process_input_reader && !m_process_input_reader->IsActive())
2287 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2288}
2289
2290void
2291Process::PopProcessInputReader ()
2292{
2293 if (m_process_input_reader && m_process_input_reader->IsActive())
2294 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2295}
2296
Greg Clayton99d0faf2010-11-18 23:32:35 +00002297
2298void
2299Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002300{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002301 UserSettingsControllerSP &usc = GetSettingsController();
2302 usc.reset (new SettingsController);
2303 UserSettingsController::InitializeSettingsController (usc,
2304 SettingsController::global_settings_table,
2305 SettingsController::instance_settings_table);
2306}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002307
Greg Clayton99d0faf2010-11-18 23:32:35 +00002308void
2309Process::Terminate ()
2310{
2311 UserSettingsControllerSP &usc = GetSettingsController();
2312 UserSettingsController::FinalizeSettingsController (usc);
2313 usc.reset();
2314}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002315
Greg Clayton99d0faf2010-11-18 23:32:35 +00002316UserSettingsControllerSP &
2317Process::GetSettingsController ()
2318{
2319 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002320 return g_settings_controller;
2321}
2322
Caroline Tice1559a462010-09-27 00:30:10 +00002323void
2324Process::UpdateInstanceName ()
2325{
2326 ModuleSP module_sp = GetTarget().GetExecutableModule();
2327 if (module_sp)
2328 {
2329 StreamString sstr;
2330 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2331
Greg Claytondbe54502010-11-19 03:46:01 +00002332 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002333 sstr.GetData());
2334 }
2335}
2336
Jim Inghamf48169b2010-11-30 02:22:11 +00002337Process::ExecutionResults
2338Process::RunThreadPlan (ExecutionContext &exe_ctx,
2339 lldb::ThreadPlanSP &thread_plan_sp,
2340 bool stop_others,
2341 bool try_all_threads,
2342 bool discard_on_error,
2343 uint32_t single_thread_timeout_usec,
2344 Stream &errors)
2345{
2346 ExecutionResults return_value = eExecutionSetupError;
2347
2348 // Save this value for restoration of the execution context after we run
2349 uint32_t tid = exe_ctx.thread->GetIndexID();
2350
2351 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2352 // so we should arrange to reset them as well.
2353
2354 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2355 lldb::StackFrameSP selected_frame_sp;
2356
2357 uint32_t selected_tid;
2358 if (selected_thread_sp != NULL)
2359 {
2360 selected_tid = selected_thread_sp->GetIndexID();
2361 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2362 }
2363 else
2364 {
2365 selected_tid = LLDB_INVALID_THREAD_ID;
2366 }
2367
2368 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2369
2370 Listener listener("ClangFunction temporary listener");
2371 exe_ctx.process->HijackProcessEvents(&listener);
2372
2373 Error resume_error = exe_ctx.process->Resume ();
2374 if (!resume_error.Success())
2375 {
2376 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2377 exe_ctx.process->RestoreProcessEvents();
2378 return Process::eExecutionSetupError;
2379 }
2380
2381 // We need to call the function synchronously, so spin waiting for it to return.
2382 // If we get interrupted while executing, we're going to lose our context, and
2383 // won't be able to gather the result at this point.
2384 // We set the timeout AFTER the resume, since the resume takes some time and we
2385 // don't want to charge that to the timeout.
2386
2387 TimeValue* timeout_ptr = NULL;
2388 TimeValue real_timeout;
2389
2390 if (single_thread_timeout_usec != 0)
2391 {
2392 real_timeout = TimeValue::Now();
2393 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2394 timeout_ptr = &real_timeout;
2395 }
2396
2397 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2398 while (1)
2399 {
2400 lldb::EventSP event_sp;
2401 lldb::StateType stop_state = lldb::eStateInvalid;
2402 // Now wait for the process to stop again:
2403 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2404
2405 if (!got_event)
2406 {
2407 // Right now this is the only way to tell we've timed out...
2408 // We should interrupt the process here...
2409 // Not really sure what to do if Halt fails here...
2410 if (log)
2411 if (try_all_threads)
2412 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2413 single_thread_timeout_usec);
2414 else
2415 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2416 single_thread_timeout_usec);
2417
2418 if (exe_ctx.process->Halt().Success())
2419 {
2420 timeout_ptr = NULL;
2421 if (log)
2422 log->Printf ("Halt succeeded.");
2423
2424 // Between the time that we got the timeout and the time we halted, but target
2425 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2426 // timeout to
2427 got_event = listener.WaitForEvent(NULL, event_sp);
2428
2429 if (got_event)
2430 {
2431 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2432 if (log)
2433 {
2434 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2435 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2436 log->Printf (" Event was the Halt interruption event.");
2437 }
2438
2439 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2440 {
2441 if (log)
2442 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
2443 return_value = Process::eExecutionCompleted;
2444 break;
2445 }
2446
2447 if (try_all_threads
2448 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2449 {
2450
2451 thread_plan_sp->SetStopOthers (false);
2452 if (log)
2453 log->Printf ("About to resume.");
2454
2455 exe_ctx.process->Resume();
2456 continue;
2457 }
2458 else
2459 {
2460 exe_ctx.process->RestoreProcessEvents ();
2461 return Process::eExecutionInterrupted;
2462 }
2463 }
2464 }
2465 }
2466
2467 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2468 if (log)
2469 log->Printf("Got event: %s.", StateAsCString(stop_state));
2470
2471 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2472 continue;
2473
2474 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2475 {
2476 return_value = Process::eExecutionCompleted;
2477 break;
2478 }
2479 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2480 {
2481 return_value = Process::eExecutionDiscarded;
2482 break;
2483 }
2484 else
2485 {
2486 if (log)
2487 {
2488 StreamString s;
2489 event_sp->Dump (&s);
2490 StreamString ts;
2491
2492 const char *event_explanation;
2493
2494 do
2495 {
2496 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2497
2498 if (!event_data)
2499 {
2500 event_explanation = "<no event data>";
2501 break;
2502 }
2503
2504 Process *process = event_data->GetProcessSP().get();
2505
2506 if (!process)
2507 {
2508 event_explanation = "<no process>";
2509 break;
2510 }
2511
2512 ThreadList &thread_list = process->GetThreadList();
2513
2514 uint32_t num_threads = thread_list.GetSize();
2515 uint32_t thread_index;
2516
2517 ts.Printf("<%u threads> ", num_threads);
2518
2519 for (thread_index = 0;
2520 thread_index < num_threads;
2521 ++thread_index)
2522 {
2523 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2524
2525 if (!thread)
2526 {
2527 ts.Printf("<?> ");
2528 continue;
2529 }
2530
2531 ts.Printf("<");
2532 RegisterContext *register_context = thread->GetRegisterContext();
2533
2534 if (register_context)
2535 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2536 else
2537 ts.Printf("[ip unknown] ");
2538
2539 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2540 if (stop_info_sp)
2541 {
2542 const char *stop_desc = stop_info_sp->GetDescription();
2543 if (stop_desc)
2544 ts.PutCString (stop_desc);
2545 }
2546 ts.Printf(">");
2547 }
2548
2549 event_explanation = ts.GetData();
2550 } while (0);
2551
2552 if (log)
2553 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2554 }
2555
2556 if (discard_on_error && thread_plan_sp)
2557 {
2558 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2559 }
2560 return_value = Process::eExecutionInterrupted;
2561 break;
2562 }
2563 }
2564
2565 if (exe_ctx.process)
2566 exe_ctx.process->RestoreProcessEvents ();
2567
2568 // Thread we ran the function in may have gone away because we ran the target
2569 // Check that it's still there.
2570 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2571 if (exe_ctx.thread)
2572 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2573
2574 // Also restore the current process'es selected frame & thread, since this function calling may
2575 // be done behind the user's back.
2576
2577 if (selected_tid != LLDB_INVALID_THREAD_ID)
2578 {
2579 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2580 {
2581 // We were able to restore the selected thread, now restore the frame:
2582 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2583 }
2584 }
2585
2586 return return_value;
2587}
2588
2589const char *
2590Process::ExecutionResultAsCString (ExecutionResults result)
2591{
2592 const char *result_name;
2593
2594 switch (result)
2595 {
2596 case Process::eExecutionCompleted:
2597 result_name = "eExecutionCompleted";
2598 break;
2599 case Process::eExecutionDiscarded:
2600 result_name = "eExecutionDiscarded";
2601 break;
2602 case Process::eExecutionInterrupted:
2603 result_name = "eExecutionInterrupted";
2604 break;
2605 case Process::eExecutionSetupError:
2606 result_name = "eExecutionSetupError";
2607 break;
2608 case Process::eExecutionTimedOut:
2609 result_name = "eExecutionTimedOut";
2610 break;
2611 }
2612 return result_name;
2613}
2614
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002615//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002616// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002617//--------------------------------------------------------------
2618
Greg Clayton1b654882010-09-19 02:33:57 +00002619Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002620 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002621{
Greg Clayton85851dd2010-12-04 00:10:17 +00002622 m_default_settings.reset (new ProcessInstanceSettings (*this,
2623 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002624 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002625}
2626
Greg Clayton1b654882010-09-19 02:33:57 +00002627Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002628{
2629}
2630
2631lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002632Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002633{
Greg Claytondbe54502010-11-19 03:46:01 +00002634 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2635 false,
2636 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002637 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2638 return new_settings_sp;
2639}
2640
2641//--------------------------------------------------------------
2642// class ProcessInstanceSettings
2643//--------------------------------------------------------------
2644
Greg Clayton85851dd2010-12-04 00:10:17 +00002645ProcessInstanceSettings::ProcessInstanceSettings
2646(
2647 UserSettingsController &owner,
2648 bool live_instance,
2649 const char *name
2650) :
2651 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002652 m_run_args (),
2653 m_env_vars (),
2654 m_input_path (),
2655 m_output_path (),
2656 m_error_path (),
2657 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00002658 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00002659 m_disable_stdio (false),
2660 m_inherit_host_env (true),
2661 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002662{
Caroline Ticef20e8232010-09-09 18:26:37 +00002663 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2664 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2665 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00002666 // This is true for CreateInstanceName() too.
2667
2668 if (GetInstanceName () == InstanceSettings::InvalidName())
2669 {
2670 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2671 m_owner.RegisterInstanceSettings (this);
2672 }
Caroline Ticef20e8232010-09-09 18:26:37 +00002673
2674 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002675 {
2676 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2677 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00002678 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002679 }
2680}
2681
2682ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00002683 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002684 m_run_args (rhs.m_run_args),
2685 m_env_vars (rhs.m_env_vars),
2686 m_input_path (rhs.m_input_path),
2687 m_output_path (rhs.m_output_path),
2688 m_error_path (rhs.m_error_path),
2689 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00002690 m_disable_aslr (rhs.m_disable_aslr),
2691 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002692{
2693 if (m_instance_name != InstanceSettings::GetDefaultName())
2694 {
2695 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2696 CopyInstanceSettings (pending_settings,false);
2697 m_owner.RemovePendingSettings (m_instance_name);
2698 }
2699}
2700
2701ProcessInstanceSettings::~ProcessInstanceSettings ()
2702{
2703}
2704
2705ProcessInstanceSettings&
2706ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2707{
2708 if (this != &rhs)
2709 {
2710 m_run_args = rhs.m_run_args;
2711 m_env_vars = rhs.m_env_vars;
2712 m_input_path = rhs.m_input_path;
2713 m_output_path = rhs.m_output_path;
2714 m_error_path = rhs.m_error_path;
2715 m_plugin = rhs.m_plugin;
2716 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00002717 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00002718 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002719 }
2720
2721 return *this;
2722}
2723
2724
2725void
2726ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2727 const char *index_value,
2728 const char *value,
2729 const ConstString &instance_name,
2730 const SettingEntry &entry,
2731 lldb::VarSetOperationType op,
2732 Error &err,
2733 bool pending)
2734{
2735 if (var_name == RunArgsVarName())
2736 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2737 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00002738 {
2739 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002740 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00002741 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002742 else if (var_name == InputPathVarName())
2743 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2744 else if (var_name == OutputPathVarName())
2745 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2746 else if (var_name == ErrorPathVarName())
2747 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2748 else if (var_name == PluginVarName())
2749 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00002750 else if (var_name == InheritHostEnvVarName())
2751 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002752 else if (var_name == DisableASLRVarName())
2753 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00002754 else if (var_name == DisableSTDIOVarName ())
2755 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002756}
2757
2758void
2759ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2760 bool pending)
2761{
2762 if (new_settings.get() == NULL)
2763 return;
2764
2765 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2766
2767 m_run_args = new_process_settings->m_run_args;
2768 m_env_vars = new_process_settings->m_env_vars;
2769 m_input_path = new_process_settings->m_input_path;
2770 m_output_path = new_process_settings->m_output_path;
2771 m_error_path = new_process_settings->m_error_path;
2772 m_plugin = new_process_settings->m_plugin;
2773 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00002774 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002775}
2776
Caroline Tice12cecd72010-09-20 21:37:42 +00002777bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002778ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2779 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00002780 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00002781 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002782{
2783 if (var_name == RunArgsVarName())
2784 {
2785 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00002786 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002787 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2788 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00002789 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002790 }
2791 else if (var_name == EnvVarsVarName())
2792 {
Greg Clayton85851dd2010-12-04 00:10:17 +00002793 GetHostEnvironmentIfNeeded ();
2794
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002795 if (m_env_vars.size() > 0)
2796 {
2797 std::map<std::string, std::string>::iterator pos;
2798 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2799 {
2800 StreamString value_str;
2801 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2802 value.AppendString (value_str.GetData());
2803 }
2804 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002805 }
2806 else if (var_name == InputPathVarName())
2807 {
2808 value.AppendString (m_input_path.c_str());
2809 }
2810 else if (var_name == OutputPathVarName())
2811 {
2812 value.AppendString (m_output_path.c_str());
2813 }
2814 else if (var_name == ErrorPathVarName())
2815 {
2816 value.AppendString (m_error_path.c_str());
2817 }
2818 else if (var_name == PluginVarName())
2819 {
2820 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2821 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00002822 else if (var_name == InheritHostEnvVarName())
2823 {
2824 if (m_inherit_host_env)
2825 value.AppendString ("true");
2826 else
2827 value.AppendString ("false");
2828 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002829 else if (var_name == DisableASLRVarName())
2830 {
2831 if (m_disable_aslr)
2832 value.AppendString ("true");
2833 else
2834 value.AppendString ("false");
2835 }
Caroline Ticef8da8632010-12-03 18:46:09 +00002836 else if (var_name == DisableSTDIOVarName())
2837 {
2838 if (m_disable_stdio)
2839 value.AppendString ("true");
2840 else
2841 value.AppendString ("false");
2842 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002843 else
Caroline Tice12cecd72010-09-20 21:37:42 +00002844 {
2845 if (err)
2846 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2847 return false;
2848 }
2849 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002850}
2851
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002852const ConstString
2853ProcessInstanceSettings::CreateInstanceName ()
2854{
2855 static int instance_count = 1;
2856 StreamString sstr;
2857
2858 sstr.Printf ("process_%d", instance_count);
2859 ++instance_count;
2860
2861 const ConstString ret_val (sstr.GetData());
2862 return ret_val;
2863}
2864
2865const ConstString &
2866ProcessInstanceSettings::RunArgsVarName ()
2867{
2868 static ConstString run_args_var_name ("run-args");
2869
2870 return run_args_var_name;
2871}
2872
2873const ConstString &
2874ProcessInstanceSettings::EnvVarsVarName ()
2875{
2876 static ConstString env_vars_var_name ("env-vars");
2877
2878 return env_vars_var_name;
2879}
2880
2881const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00002882ProcessInstanceSettings::InheritHostEnvVarName ()
2883{
2884 static ConstString g_name ("inherit-env");
2885
2886 return g_name;
2887}
2888
2889const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002890ProcessInstanceSettings::InputPathVarName ()
2891{
2892 static ConstString input_path_var_name ("input-path");
2893
2894 return input_path_var_name;
2895}
2896
2897const ConstString &
2898ProcessInstanceSettings::OutputPathVarName ()
2899{
Caroline Tice49e27372010-09-07 18:35:40 +00002900 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002901
2902 return output_path_var_name;
2903}
2904
2905const ConstString &
2906ProcessInstanceSettings::ErrorPathVarName ()
2907{
Caroline Tice49e27372010-09-07 18:35:40 +00002908 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002909
2910 return error_path_var_name;
2911}
2912
2913const ConstString &
2914ProcessInstanceSettings::PluginVarName ()
2915{
2916 static ConstString plugin_var_name ("plugin");
2917
2918 return plugin_var_name;
2919}
2920
2921
2922const ConstString &
2923ProcessInstanceSettings::DisableASLRVarName ()
2924{
2925 static ConstString disable_aslr_var_name ("disable-aslr");
2926
2927 return disable_aslr_var_name;
2928}
2929
Caroline Ticef8da8632010-12-03 18:46:09 +00002930const ConstString &
2931ProcessInstanceSettings::DisableSTDIOVarName ()
2932{
2933 static ConstString disable_stdio_var_name ("disable-stdio");
2934
2935 return disable_stdio_var_name;
2936}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002937
2938//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002939// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002940//--------------------------------------------------
2941
2942SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00002943Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002944{
2945 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2946 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2947};
2948
2949
2950lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00002951Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002952{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00002953 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2954 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2955 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002956};
2957
2958SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00002959Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002960{
Greg Clayton85851dd2010-12-04 00:10:17 +00002961 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2962 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2963 { "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." },
2964 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
2965 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2966 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2967 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2968 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
2969 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
2970 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2971 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002972};
2973
2974
Jim Ingham5aee1622010-08-09 23:31:02 +00002975