blob: 5b87c528e3112f7ec3379229a72be86c4c39b81e [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
40Process*
41Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
42{
43 ProcessCreateInstance create_callback = NULL;
44 if (plugin_name)
45 {
46 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
47 if (create_callback)
48 {
49 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
50 if (debugger_ap->CanDebug(target))
51 return debugger_ap.release();
52 }
53 }
54 else
55 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000056 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +000057 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000058 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
59 if (debugger_ap->CanDebug(target))
60 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +000061 }
62 }
63 return NULL;
64}
65
66
67//----------------------------------------------------------------------
68// Process constructor
69//----------------------------------------------------------------------
70Process::Process(Target &target, Listener &listener) :
71 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +000072 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +000073 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +000074 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +000075 m_public_state (eStateUnloaded),
76 m_private_state (eStateUnloaded),
77 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
78 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
79 m_private_state_listener ("lldb.process.internal_state_listener"),
80 m_private_state_control_wait(),
81 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
82 m_stop_id (0),
83 m_thread_index_id (0),
84 m_exit_status (-1),
85 m_exit_string (),
86 m_thread_list (this),
87 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +000088 m_image_tokens (),
89 m_listener (listener),
90 m_breakpoint_site_list (),
91 m_persistent_vars (),
92 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +000093 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +000094 m_target_triple (),
95 m_byte_order (eByteOrderHost),
96 m_addr_byte_size (0),
97 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +000098 m_process_input_reader (),
Caroline Tice9ac497b2010-12-02 18:31:56 +000099 m_stdio_communication ("lldb.process.stdio", true),
Greg Clayton20d338f2010-11-18 05:57:03 +0000100 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Caroline Tice861efb32010-11-16 05:07:41 +0000101 m_stdout_data ()
Chris Lattner24943d22010-06-08 16:52:24 +0000102{
Caroline Tice1ebef442010-09-27 00:30:10 +0000103 UpdateInstanceName();
104
Greg Claytone005f2c2010-11-06 01:53:30 +0000105 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000106 if (log)
107 log->Printf ("%p Process::Process()", this);
108
Greg Clayton49ce6822010-10-31 03:01:06 +0000109 SetEventName (eBroadcastBitStateChanged, "state-changed");
110 SetEventName (eBroadcastBitInterrupt, "interrupt");
111 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
112 SetEventName (eBroadcastBitSTDERR, "stderr-available");
113
Chris Lattner24943d22010-06-08 16:52:24 +0000114 listener.StartListeningForEvents (this,
115 eBroadcastBitStateChanged |
116 eBroadcastBitInterrupt |
117 eBroadcastBitSTDOUT |
118 eBroadcastBitSTDERR);
119
120 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
121 eBroadcastBitStateChanged);
122
123 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
124 eBroadcastInternalStateControlStop |
125 eBroadcastInternalStateControlPause |
126 eBroadcastInternalStateControlResume);
127}
128
129//----------------------------------------------------------------------
130// Destructor
131//----------------------------------------------------------------------
132Process::~Process()
133{
Greg Claytone005f2c2010-11-06 01:53:30 +0000134 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000135 if (log)
136 log->Printf ("%p Process::~Process()", this);
137 StopPrivateStateThread();
138}
139
140void
141Process::Finalize()
142{
143 // Do any cleanup needed prior to being destructed... Subclasses
144 // that override this method should call this superclass method as well.
145}
146
147void
148Process::RegisterNotificationCallbacks (const Notifications& callbacks)
149{
150 m_notifications.push_back(callbacks);
151 if (callbacks.initialize != NULL)
152 callbacks.initialize (callbacks.baton, this);
153}
154
155bool
156Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
157{
158 std::vector<Notifications>::iterator pos, end = m_notifications.end();
159 for (pos = m_notifications.begin(); pos != end; ++pos)
160 {
161 if (pos->baton == callbacks.baton &&
162 pos->initialize == callbacks.initialize &&
163 pos->process_state_changed == callbacks.process_state_changed)
164 {
165 m_notifications.erase(pos);
166 return true;
167 }
168 }
169 return false;
170}
171
172void
173Process::SynchronouslyNotifyStateChanged (StateType state)
174{
175 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
176 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
177 {
178 if (notification_pos->process_state_changed)
179 notification_pos->process_state_changed (notification_pos->baton, this, state);
180 }
181}
182
183// FIXME: We need to do some work on events before the general Listener sees them.
184// For instance if we are continuing from a breakpoint, we need to ensure that we do
185// the little "insert real insn, step & stop" trick. But we can't do that when the
186// event is delivered by the broadcaster - since that is done on the thread that is
187// waiting for new events, so if we needed more than one event for our handling, we would
188// stall. So instead we do it when we fetch the event off of the queue.
189//
190
191StateType
192Process::GetNextEvent (EventSP &event_sp)
193{
194 StateType state = eStateInvalid;
195
196 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
197 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
198
199 return state;
200}
201
202
203StateType
204Process::WaitForProcessToStop (const TimeValue *timeout)
205{
206 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
207 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
208}
209
210
211StateType
212Process::WaitForState
213(
214 const TimeValue *timeout,
215 const StateType *match_states, const uint32_t num_match_states
216)
217{
218 EventSP event_sp;
219 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000220 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000221 while (state != eStateInvalid)
222 {
Greg Claytond8c62532010-10-07 04:19:01 +0000223 // If we are exited or detached, we won't ever get back to any
224 // other valid state...
225 if (state == eStateDetached || state == eStateExited)
226 return state;
227
Chris Lattner24943d22010-06-08 16:52:24 +0000228 state = WaitForStateChangedEvents (timeout, event_sp);
229
230 for (i=0; i<num_match_states; ++i)
231 {
232 if (match_states[i] == state)
233 return state;
234 }
235 }
236 return state;
237}
238
Jim Ingham63e24d72010-10-11 23:53:14 +0000239bool
240Process::HijackProcessEvents (Listener *listener)
241{
242 if (listener != NULL)
243 {
244 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
245 }
246 else
247 return false;
248}
249
250void
251Process::RestoreProcessEvents ()
252{
253 RestoreBroadcaster();
254}
255
Chris Lattner24943d22010-06-08 16:52:24 +0000256StateType
257Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
258{
Greg Claytone005f2c2010-11-06 01:53:30 +0000259 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000260
261 if (log)
262 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
263
264 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000265 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
266 this,
267 eBroadcastBitStateChanged,
268 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000269 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
270
Caroline Tice926060e2010-10-29 21:48:37 +0000271 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000272 if (log)
273 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
274 __FUNCTION__,
275 timeout,
276 StateAsCString(state));
277 return state;
278}
279
280Event *
281Process::PeekAtStateChangedEvents ()
282{
Greg Claytone005f2c2010-11-06 01:53:30 +0000283 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000284
285 if (log)
286 log->Printf ("Process::%s...", __FUNCTION__);
287
288 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000289 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
290 eBroadcastBitStateChanged);
Caroline Tice926060e2010-10-29 21:48:37 +0000291 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +0000292 if (log)
293 {
294 if (event_ptr)
295 {
296 log->Printf ("Process::%s (event_ptr) => %s",
297 __FUNCTION__,
298 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
299 }
300 else
301 {
302 log->Printf ("Process::%s no events found",
303 __FUNCTION__);
304 }
305 }
306 return event_ptr;
307}
308
309StateType
310Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
311{
Greg Claytone005f2c2010-11-06 01:53:30 +0000312 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000313
314 if (log)
315 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
316
317 StateType state = eStateInvalid;
318 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
319 &m_private_state_broadcaster,
320 eBroadcastBitStateChanged,
321 event_sp))
322 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
323
324 // This is a bit of a hack, but when we wait here we could very well return
325 // to the command-line, and that could disable the log, which would render the
326 // log we got above invalid.
327 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
328 if (log)
329 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
330 return state;
331}
332
333bool
334Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
335{
Greg Claytone005f2c2010-11-06 01:53:30 +0000336 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000337
338 if (log)
339 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
340
341 if (control_only)
342 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
343 else
344 return m_private_state_listener.WaitForEvent(timeout, event_sp);
345}
346
347bool
348Process::IsRunning () const
349{
350 return StateIsRunningState (m_public_state.GetValue());
351}
352
353int
354Process::GetExitStatus ()
355{
356 if (m_public_state.GetValue() == eStateExited)
357 return m_exit_status;
358 return -1;
359}
360
Greg Clayton638351a2010-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 Lattner24943d22010-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{
417 m_exit_status = status;
418 if (cstr)
419 m_exit_string = cstr;
420 else
421 m_exit_string.clear();
422
423 SetPrivateState (eStateExited);
424}
425
426// This static callback can be used to watch for local child processes on
427// the current host. The the child process exits, the process will be
428// found in the global target list (we want to be completely sure that the
429// lldb_private::Process doesn't go away before we can deliver the signal.
430bool
431Process::SetProcessExitStatus
432(
433 void *callback_baton,
434 lldb::pid_t pid,
435 int signo, // Zero for no signal
436 int exit_status // Exit value of process if signal is zero
437)
438{
439 if (signo == 0 || exit_status)
440 {
Greg Clayton63094e02010-06-23 01:19:29 +0000441 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000442 if (target_sp)
443 {
444 ProcessSP process_sp (target_sp->GetProcessSP());
445 if (process_sp)
446 {
447 const char *signal_cstr = NULL;
448 if (signo)
449 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
450
451 process_sp->SetExitStatus (exit_status, signal_cstr);
452 }
453 }
454 return true;
455 }
456 return false;
457}
458
459
460uint32_t
461Process::GetNextThreadIndexID ()
462{
463 return ++m_thread_index_id;
464}
465
466StateType
467Process::GetState()
468{
469 // If any other threads access this we will need a mutex for it
470 return m_public_state.GetValue ();
471}
472
473void
474Process::SetPublicState (StateType new_state)
475{
Greg Claytone005f2c2010-11-06 01:53:30 +0000476 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000477 if (log)
478 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
479 m_public_state.SetValue (new_state);
480}
481
482StateType
483Process::GetPrivateState ()
484{
485 return m_private_state.GetValue();
486}
487
488void
489Process::SetPrivateState (StateType new_state)
490{
Greg Claytone005f2c2010-11-06 01:53:30 +0000491 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000492 bool state_changed = false;
493
494 if (log)
495 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
496
497 Mutex::Locker locker(m_private_state.GetMutex());
498
499 const StateType old_state = m_private_state.GetValueNoLock ();
500 state_changed = old_state != new_state;
501 if (state_changed)
502 {
503 m_private_state.SetValueNoLock (new_state);
504 if (StateIsStoppedState(new_state))
505 {
506 m_stop_id++;
507 if (log)
508 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
509 }
510 // Use our target to get a shared pointer to ourselves...
511 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
512 }
513 else
514 {
515 if (log)
516 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
517 }
518}
519
520
521uint32_t
522Process::GetStopID() const
523{
524 return m_stop_id;
525}
526
527addr_t
528Process::GetImageInfoAddress()
529{
530 return LLDB_INVALID_ADDRESS;
531}
532
Greg Clayton0baa3942010-11-04 01:54:29 +0000533//----------------------------------------------------------------------
534// LoadImage
535//
536// This function provides a default implementation that works for most
537// unix variants. Any Process subclasses that need to do shared library
538// loading differently should override LoadImage and UnloadImage and
539// do what is needed.
540//----------------------------------------------------------------------
541uint32_t
542Process::LoadImage (const FileSpec &image_spec, Error &error)
543{
544 DynamicLoader *loader = GetDynamicLoader();
545 if (loader)
546 {
547 error = loader->CanLoadImage();
548 if (error.Fail())
549 return LLDB_INVALID_IMAGE_TOKEN;
550 }
551
552 if (error.Success())
553 {
554 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
555 if (thread_sp == NULL)
556 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
557
558 if (thread_sp)
559 {
560 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
561
562 if (frame_sp)
563 {
564 ExecutionContext exe_ctx;
565 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000566 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000567 StreamString expr;
568 char path[PATH_MAX];
569 image_spec.GetPath(path, sizeof(path));
570 expr.Printf("dlopen (\"%s\", 2)", path);
571 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000572 lldb::ValueObjectSP result_valobj_sp;
573 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000574 if (result_valobj_sp->GetError().Success())
575 {
576 Scalar scalar;
577 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
578 {
579 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
580 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
581 {
582 uint32_t image_token = m_image_tokens.size();
583 m_image_tokens.push_back (image_ptr);
584 return image_token;
585 }
586 }
587 }
588 }
589 }
590 }
591 return LLDB_INVALID_IMAGE_TOKEN;
592}
593
594//----------------------------------------------------------------------
595// UnloadImage
596//
597// This function provides a default implementation that works for most
598// unix variants. Any Process subclasses that need to do shared library
599// loading differently should override LoadImage and UnloadImage and
600// do what is needed.
601//----------------------------------------------------------------------
602Error
603Process::UnloadImage (uint32_t image_token)
604{
605 Error error;
606 if (image_token < m_image_tokens.size())
607 {
608 const addr_t image_addr = m_image_tokens[image_token];
609 if (image_addr == LLDB_INVALID_ADDRESS)
610 {
611 error.SetErrorString("image already unloaded");
612 }
613 else
614 {
615 DynamicLoader *loader = GetDynamicLoader();
616 if (loader)
617 error = loader->CanLoadImage();
618
619 if (error.Success())
620 {
621 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
622 if (thread_sp == NULL)
623 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
624
625 if (thread_sp)
626 {
627 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
628
629 if (frame_sp)
630 {
631 ExecutionContext exe_ctx;
632 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000633 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000634 StreamString expr;
635 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
636 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000637 lldb::ValueObjectSP result_valobj_sp;
638 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000639 if (result_valobj_sp->GetError().Success())
640 {
641 Scalar scalar;
642 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
643 {
644 if (scalar.UInt(1))
645 {
646 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
647 }
648 else
649 {
650 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
651 }
652 }
653 }
654 else
655 {
656 error = result_valobj_sp->GetError();
657 }
658 }
659 }
660 }
661 }
662 }
663 else
664 {
665 error.SetErrorString("invalid image token");
666 }
667 return error;
668}
669
Chris Lattner24943d22010-06-08 16:52:24 +0000670DynamicLoader *
671Process::GetDynamicLoader()
672{
673 return NULL;
674}
675
676const ABI *
677Process::GetABI()
678{
679 ConstString& triple = m_target_triple;
680
681 if (triple.IsEmpty())
682 return NULL;
683
684 if (m_abi_sp.get() == NULL)
685 {
686 m_abi_sp.reset(ABI::FindPlugin(triple));
687 }
688
689 return m_abi_sp.get();
690}
691
Jim Ingham642036f2010-09-23 02:01:19 +0000692LanguageRuntime *
693Process::GetLanguageRuntime(lldb::LanguageType language)
694{
695 LanguageRuntimeCollection::iterator pos;
696 pos = m_language_runtimes.find (language);
697 if (pos == m_language_runtimes.end())
698 {
699 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
700
701 m_language_runtimes[language]
702 = runtime;
703 return runtime.get();
704 }
705 else
706 return (*pos).second.get();
707}
708
709CPPLanguageRuntime *
710Process::GetCPPLanguageRuntime ()
711{
712 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
713 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
714 return static_cast<CPPLanguageRuntime *> (runtime);
715 return NULL;
716}
717
718ObjCLanguageRuntime *
719Process::GetObjCLanguageRuntime ()
720{
721 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
722 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
723 return static_cast<ObjCLanguageRuntime *> (runtime);
724 return NULL;
725}
726
Chris Lattner24943d22010-06-08 16:52:24 +0000727BreakpointSiteList &
728Process::GetBreakpointSiteList()
729{
730 return m_breakpoint_site_list;
731}
732
733const BreakpointSiteList &
734Process::GetBreakpointSiteList() const
735{
736 return m_breakpoint_site_list;
737}
738
739
740void
741Process::DisableAllBreakpointSites ()
742{
743 m_breakpoint_site_list.SetEnabledForAll (false);
744}
745
746Error
747Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
748{
749 Error error (DisableBreakpointSiteByID (break_id));
750
751 if (error.Success())
752 m_breakpoint_site_list.Remove(break_id);
753
754 return error;
755}
756
757Error
758Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
759{
760 Error error;
761 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
762 if (bp_site_sp)
763 {
764 if (bp_site_sp->IsEnabled())
765 error = DisableBreakpoint (bp_site_sp.get());
766 }
767 else
768 {
769 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
770 }
771
772 return error;
773}
774
775Error
776Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
777{
778 Error error;
779 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
780 if (bp_site_sp)
781 {
782 if (!bp_site_sp->IsEnabled())
783 error = EnableBreakpoint (bp_site_sp.get());
784 }
785 else
786 {
787 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
788 }
789 return error;
790}
791
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000792lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000793Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
794{
Greg Claytoneea26402010-09-14 23:36:40 +0000795 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000796 if (load_addr != LLDB_INVALID_ADDRESS)
797 {
798 BreakpointSiteSP bp_site_sp;
799
800 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
801 // create a new breakpoint site and add it.
802
803 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
804
805 if (bp_site_sp)
806 {
807 bp_site_sp->AddOwner (owner);
808 owner->SetBreakpointSite (bp_site_sp);
809 return bp_site_sp->GetID();
810 }
811 else
812 {
813 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
814 if (bp_site_sp)
815 {
816 if (EnableBreakpoint (bp_site_sp.get()).Success())
817 {
818 owner->SetBreakpointSite (bp_site_sp);
819 return m_breakpoint_site_list.Add (bp_site_sp);
820 }
821 }
822 }
823 }
824 // We failed to enable the breakpoint
825 return LLDB_INVALID_BREAK_ID;
826
827}
828
829void
830Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
831{
832 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
833 if (num_owners == 0)
834 {
835 DisableBreakpoint(bp_site_sp.get());
836 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
837 }
838}
839
840
841size_t
842Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
843{
844 size_t bytes_removed = 0;
845 addr_t intersect_addr;
846 size_t intersect_size;
847 size_t opcode_offset;
848 size_t idx;
849 BreakpointSiteSP bp;
850
851 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
852 {
853 if (bp->GetType() == BreakpointSite::eSoftware)
854 {
855 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
856 {
857 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
858 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
859 assert(opcode_offset + intersect_size <= bp->GetByteSize());
860 size_t buf_offset = intersect_addr - bp_addr;
861 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
862 }
863 }
864 }
865 return bytes_removed;
866}
867
868
869Error
870Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
871{
872 Error error;
873 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000874 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000875 const addr_t bp_addr = bp_site->GetLoadAddress();
876 if (log)
877 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
878 if (bp_site->IsEnabled())
879 {
880 if (log)
881 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
882 return error;
883 }
884
885 if (bp_addr == LLDB_INVALID_ADDRESS)
886 {
887 error.SetErrorString("BreakpointSite contains an invalid load address.");
888 return error;
889 }
890 // Ask the lldb::Process subclass to fill in the correct software breakpoint
891 // trap for the breakpoint site
892 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
893
894 if (bp_opcode_size == 0)
895 {
896 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
897 }
898 else
899 {
900 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
901
902 if (bp_opcode_bytes == NULL)
903 {
904 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
905 return error;
906 }
907
908 // Save the original opcode by reading it
909 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
910 {
911 // Write a software breakpoint in place of the original opcode
912 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
913 {
914 uint8_t verify_bp_opcode_bytes[64];
915 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
916 {
917 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
918 {
919 bp_site->SetEnabled(true);
920 bp_site->SetType (BreakpointSite::eSoftware);
921 if (log)
922 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
923 bp_site->GetID(),
924 (uint64_t)bp_addr);
925 }
926 else
927 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
928 }
929 else
930 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
931 }
932 else
933 error.SetErrorString("Unable to write breakpoint trap to memory.");
934 }
935 else
936 error.SetErrorString("Unable to read memory at breakpoint address.");
937 }
938 if (log)
939 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
940 bp_site->GetID(),
941 (uint64_t)bp_addr,
942 error.AsCString());
943 return error;
944}
945
946Error
947Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
948{
949 Error error;
950 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +0000951 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +0000952 addr_t bp_addr = bp_site->GetLoadAddress();
953 lldb::user_id_t breakID = bp_site->GetID();
954 if (log)
955 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
956
957 if (bp_site->IsHardware())
958 {
959 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
960 }
961 else if (bp_site->IsEnabled())
962 {
963 const size_t break_op_size = bp_site->GetByteSize();
964 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
965 if (break_op_size > 0)
966 {
967 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +0000968 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000969 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +0000970 bool break_op_found = false;
971
972 // Read the breakpoint opcode
973 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
974 {
975 bool verify = false;
976 // Make sure we have the a breakpoint opcode exists at this address
977 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
978 {
979 break_op_found = true;
980 // We found a valid breakpoint opcode at this address, now restore
981 // the saved opcode.
982 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
983 {
984 verify = true;
985 }
986 else
987 error.SetErrorString("Memory write failed when restoring original opcode.");
988 }
989 else
990 {
991 error.SetErrorString("Original breakpoint trap is no longer in memory.");
992 // Set verify to true and so we can check if the original opcode has already been restored
993 verify = true;
994 }
995
996 if (verify)
997 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000998 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +0000999 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001000 // Verify that our original opcode made it back to the inferior
1001 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1002 {
1003 // compare the memory we just read with the original opcode
1004 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1005 {
1006 // SUCCESS
1007 bp_site->SetEnabled(false);
1008 if (log)
1009 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1010 return error;
1011 }
1012 else
1013 {
1014 if (break_op_found)
1015 error.SetErrorString("Failed to restore original opcode.");
1016 }
1017 }
1018 else
1019 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1020 }
1021 }
1022 else
1023 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1024 }
1025 }
1026 else
1027 {
1028 if (log)
1029 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1030 return error;
1031 }
1032
1033 if (log)
1034 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1035 bp_site->GetID(),
1036 (uint64_t)bp_addr,
1037 error.AsCString());
1038 return error;
1039
1040}
1041
1042
1043size_t
1044Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1045{
1046 if (buf == NULL || size == 0)
1047 return 0;
1048
1049 size_t bytes_read = 0;
1050 uint8_t *bytes = (uint8_t *)buf;
1051
1052 while (bytes_read < size)
1053 {
1054 const size_t curr_size = size - bytes_read;
1055 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1056 bytes + bytes_read,
1057 curr_size,
1058 error);
1059 bytes_read += curr_bytes_read;
1060 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1061 break;
1062 }
1063
1064 // Replace any software breakpoint opcodes that fall into this range back
1065 // into "buf" before we return
1066 if (bytes_read > 0)
1067 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1068 return bytes_read;
1069}
1070
1071size_t
1072Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1073{
1074 size_t bytes_written = 0;
1075 const uint8_t *bytes = (const uint8_t *)buf;
1076
1077 while (bytes_written < size)
1078 {
1079 const size_t curr_size = size - bytes_written;
1080 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1081 bytes + bytes_written,
1082 curr_size,
1083 error);
1084 bytes_written += curr_bytes_written;
1085 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1086 break;
1087 }
1088 return bytes_written;
1089}
1090
1091size_t
1092Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1093{
1094 if (buf == NULL || size == 0)
1095 return 0;
1096 // We need to write any data that would go where any current software traps
1097 // (enabled software breakpoints) any software traps (breakpoints) that we
1098 // may have placed in our tasks memory.
1099
1100 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1101 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1102
1103 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1104 return DoWriteMemory(addr, buf, size, error);
1105
1106 BreakpointSiteList::collection::const_iterator pos;
1107 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001108 addr_t intersect_addr = 0;
1109 size_t intersect_size = 0;
1110 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001111 const uint8_t *ubuf = (const uint8_t *)buf;
1112
1113 for (pos = iter; pos != end; ++pos)
1114 {
1115 BreakpointSiteSP bp;
1116 bp = pos->second;
1117
1118 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1119 assert(addr <= intersect_addr && intersect_addr < addr + size);
1120 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1121 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1122
1123 // Check for bytes before this breakpoint
1124 const addr_t curr_addr = addr + bytes_written;
1125 if (intersect_addr > curr_addr)
1126 {
1127 // There are some bytes before this breakpoint that we need to
1128 // just write to memory
1129 size_t curr_size = intersect_addr - curr_addr;
1130 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1131 ubuf + bytes_written,
1132 curr_size,
1133 error);
1134 bytes_written += curr_bytes_written;
1135 if (curr_bytes_written != curr_size)
1136 {
1137 // We weren't able to write all of the requested bytes, we
1138 // are done looping and will return the number of bytes that
1139 // we have written so far.
1140 break;
1141 }
1142 }
1143
1144 // Now write any bytes that would cover up any software breakpoints
1145 // directly into the breakpoint opcode buffer
1146 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1147 bytes_written += intersect_size;
1148 }
1149
1150 // Write any remaining bytes after the last breakpoint if we have any left
1151 if (bytes_written < size)
1152 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1153 ubuf + bytes_written,
1154 size - bytes_written,
1155 error);
1156
1157 return bytes_written;
1158}
1159
1160addr_t
1161Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1162{
1163 // Fixme: we should track the blocks we've allocated, and clean them up...
1164 // We could even do our own allocator here if that ends up being more efficient.
1165 return DoAllocateMemory (size, permissions, error);
1166}
1167
1168Error
1169Process::DeallocateMemory (addr_t ptr)
1170{
1171 return DoDeallocateMemory (ptr);
1172}
1173
1174
1175Error
1176Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1177{
1178 Error error;
1179 error.SetErrorString("watchpoints are not supported");
1180 return error;
1181}
1182
1183Error
1184Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1185{
1186 Error error;
1187 error.SetErrorString("watchpoints are not supported");
1188 return error;
1189}
1190
1191StateType
1192Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1193{
1194 StateType state;
1195 // Now wait for the process to launch and return control to us, and then
1196 // call DidLaunch:
1197 while (1)
1198 {
1199 // FIXME: Might want to put a timeout in here:
1200 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1201 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1202 break;
1203 else
1204 HandlePrivateEvent (event_sp);
1205 }
1206 return state;
1207}
1208
1209Error
1210Process::Launch
1211(
1212 char const *argv[],
1213 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001214 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001215 const char *stdin_path,
1216 const char *stdout_path,
1217 const char *stderr_path
1218)
1219{
1220 Error error;
1221 m_target_triple.Clear();
1222 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001223 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001224
1225 Module *exe_module = m_target.GetExecutableModule().get();
1226 if (exe_module)
1227 {
1228 char exec_file_path[PATH_MAX];
1229 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1230 if (exe_module->GetFileSpec().Exists())
1231 {
1232 error = WillLaunch (exe_module);
1233 if (error.Success())
1234 {
Greg Claytond8c62532010-10-07 04:19:01 +00001235 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001236 // The args coming in should not contain the application name, the
1237 // lldb_private::Process class will add this in case the executable
1238 // gets resolved to a different file than was given on the command
1239 // line (like when an applicaiton bundle is specified and will
1240 // resolve to the contained exectuable file, or the file given was
1241 // a symlink or other file system link that resolves to a different
1242 // file).
1243
1244 // Get the resolved exectuable path
1245
1246 // Make a new argument vector
1247 std::vector<const char *> exec_path_plus_argv;
1248 // Append the resolved executable path
1249 exec_path_plus_argv.push_back (exec_file_path);
1250
1251 // Push all args if there are any
1252 if (argv)
1253 {
1254 for (int i = 0; argv[i]; ++i)
1255 exec_path_plus_argv.push_back(argv[i]);
1256 }
1257
1258 // Push a NULL to terminate the args.
1259 exec_path_plus_argv.push_back(NULL);
1260
1261 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001262 error = DoLaunch (exe_module,
1263 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1264 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001265 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001266 stdin_path,
1267 stdout_path,
1268 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001269
1270 if (error.Fail())
1271 {
1272 if (GetID() != LLDB_INVALID_PROCESS_ID)
1273 {
1274 SetID (LLDB_INVALID_PROCESS_ID);
1275 const char *error_string = error.AsCString();
1276 if (error_string == NULL)
1277 error_string = "launch failed";
1278 SetExitStatus (-1, error_string);
1279 }
1280 }
1281 else
1282 {
1283 EventSP event_sp;
1284 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1285
1286 if (state == eStateStopped || state == eStateCrashed)
1287 {
1288 DidLaunch ();
1289
1290 // This delays passing the stopped event to listeners till DidLaunch gets
1291 // a chance to complete...
1292 HandlePrivateEvent (event_sp);
1293 StartPrivateStateThread ();
1294 }
1295 else if (state == eStateExited)
1296 {
1297 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1298 // not likely to work, and return an invalid pid.
1299 HandlePrivateEvent (event_sp);
1300 }
1301 }
1302 }
1303 }
1304 else
1305 {
1306 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1307 }
1308 }
1309 return error;
1310}
1311
1312Error
1313Process::CompleteAttach ()
1314{
1315 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001316
1317 if (GetID() == LLDB_INVALID_PROCESS_ID)
1318 {
1319 error.SetErrorString("no process");
1320 }
1321
Chris Lattner24943d22010-06-08 16:52:24 +00001322 EventSP event_sp;
1323 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1324 if (state == eStateStopped || state == eStateCrashed)
1325 {
1326 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001327 // Figure out which one is the executable, and set that in our target:
1328 ModuleList &modules = GetTarget().GetImages();
1329
1330 size_t num_modules = modules.GetSize();
1331 for (int i = 0; i < num_modules; i++)
1332 {
1333 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1334 if (module_sp->IsExecutable())
1335 {
1336 ModuleSP exec_module = GetTarget().GetExecutableModule();
1337 if (!exec_module || exec_module != module_sp)
1338 {
1339
1340 GetTarget().SetExecutableModule (module_sp, false);
1341 }
1342 break;
1343 }
1344 }
Chris Lattner24943d22010-06-08 16:52:24 +00001345
1346 // This delays passing the stopped event to listeners till DidLaunch gets
1347 // a chance to complete...
1348 HandlePrivateEvent(event_sp);
1349 StartPrivateStateThread();
1350 }
1351 else
1352 {
1353 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1354 // not likely to work, and return an invalid pid.
1355 if (state == eStateExited)
1356 HandlePrivateEvent (event_sp);
1357 error.SetErrorStringWithFormat("invalid state after attach: %s",
1358 lldb_private::StateAsCString(state));
1359 }
1360 return error;
1361}
1362
1363Error
1364Process::Attach (lldb::pid_t attach_pid)
1365{
1366
1367 m_target_triple.Clear();
1368 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001369 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001370
Jim Ingham7508e732010-08-09 23:31:02 +00001371 // Find the process and its architecture. Make sure it matches the architecture
1372 // of the current Target, and if not adjust it.
1373
1374 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1375 if (attach_spec != GetTarget().GetArchitecture())
1376 {
1377 // Set the architecture on the target.
1378 GetTarget().SetArchitecture(attach_spec);
1379 }
1380
Greg Clayton54e7afa2010-07-09 20:39:50 +00001381 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001382 if (error.Success())
1383 {
Greg Claytond8c62532010-10-07 04:19:01 +00001384 SetPublicState (eStateAttaching);
1385
Greg Clayton54e7afa2010-07-09 20:39:50 +00001386 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001387 if (error.Success())
1388 {
1389 error = CompleteAttach();
1390 }
1391 else
1392 {
1393 if (GetID() != LLDB_INVALID_PROCESS_ID)
1394 {
1395 SetID (LLDB_INVALID_PROCESS_ID);
1396 const char *error_string = error.AsCString();
1397 if (error_string == NULL)
1398 error_string = "attach failed";
1399
1400 SetExitStatus(-1, error_string);
1401 }
1402 }
1403 }
1404 return error;
1405}
1406
1407Error
1408Process::Attach (const char *process_name, bool wait_for_launch)
1409{
1410 m_target_triple.Clear();
1411 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001412 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001413
1414 // Find the process and its architecture. Make sure it matches the architecture
1415 // of the current Target, and if not adjust it.
1416
Jim Inghamea294182010-08-17 21:54:19 +00001417 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001418 {
Jim Inghamea294182010-08-17 21:54:19 +00001419 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001420 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001421 {
1422 // Set the architecture on the target.
1423 GetTarget().SetArchitecture(attach_spec);
1424 }
Jim Ingham7508e732010-08-09 23:31:02 +00001425 }
Jim Inghamea294182010-08-17 21:54:19 +00001426
Greg Clayton54e7afa2010-07-09 20:39:50 +00001427 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001428 if (error.Success())
1429 {
Greg Claytond8c62532010-10-07 04:19:01 +00001430 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001431 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001432 if (error.Fail())
1433 {
1434 if (GetID() != LLDB_INVALID_PROCESS_ID)
1435 {
1436 SetID (LLDB_INVALID_PROCESS_ID);
1437 const char *error_string = error.AsCString();
1438 if (error_string == NULL)
1439 error_string = "attach failed";
1440
1441 SetExitStatus(-1, error_string);
1442 }
1443 }
1444 else
1445 {
1446 error = CompleteAttach();
1447 }
1448 }
1449 return error;
1450}
1451
1452Error
1453Process::Resume ()
1454{
Greg Claytone005f2c2010-11-06 01:53:30 +00001455 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001456 if (log)
1457 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1458
1459 Error error (WillResume());
1460 // Tell the process it is about to resume before the thread list
1461 if (error.Success())
1462 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001463 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001464 // can let all of our threads know that they are about to be
1465 // resumed. Threads will each be called with
1466 // Thread::WillResume(StateType) where StateType contains the state
1467 // that they are supposed to have when the process is resumed
1468 // (suspended/running/stepping). Threads should also check
1469 // their resume signal in lldb::Thread::GetResumeSignal()
1470 // to see if they are suppoed to start back up with a signal.
1471 if (m_thread_list.WillResume())
1472 {
1473 error = DoResume();
1474 if (error.Success())
1475 {
1476 DidResume();
1477 m_thread_list.DidResume();
1478 }
1479 }
1480 else
1481 {
1482 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1483 }
1484 }
1485 return error;
1486}
1487
1488Error
1489Process::Halt ()
1490{
1491 Error error (WillHalt());
1492
1493 if (error.Success())
1494 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001495
1496 bool caused_stop = false;
1497 EventSP event_sp;
1498
1499 // Pause our private state thread so we can ensure no one else eats
1500 // the stop event out from under us.
1501 PausePrivateStateThread();
1502
1503 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001504 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001505 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001506 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001507 // If "caused_stop" is true, then DoHalt stopped the process. If
1508 // "caused_stop" is false, the process was already stopped.
1509 // If the DoHalt caused the process to stop, then we want to catch
1510 // this event and set the interrupted bool to true before we pass
1511 // this along so clients know that the process was interrupted by
1512 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001513 if (caused_stop)
1514 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001515 // Wait for 2 seconds for the process to stop.
1516 TimeValue timeout_time;
1517 timeout_time = TimeValue::Now();
1518 timeout_time.OffsetWithSeconds(2);
1519 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1520
1521 if (state == eStateInvalid)
1522 {
1523 // We timeout out and didn't get a stop event...
1524 error.SetErrorString ("Halt timed out.");
1525 }
1526 else
1527 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001528 if (StateIsStoppedState (state))
1529 {
1530 // We caused the process to interrupt itself, so mark this
1531 // as such in the stop event so clients can tell an interrupted
1532 // process from a natural stop
1533 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1534 }
1535 else
1536 {
1537 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1538 if (log)
1539 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1540 error.SetErrorString ("Did not get stopped event after halt.");
1541 }
1542 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001543 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001544 DidHalt();
1545
Jim Ingham3ae449a2010-11-17 02:32:00 +00001546 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001547 // Resume our private state thread before we post the event (if any)
1548 ResumePrivateStateThread();
1549
1550 // Post any event we might have consumed. If all goes well, we will have
1551 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001552 // bool in the event. Post it to the private event queue and that will end up
1553 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001554 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001555 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001556
Chris Lattner24943d22010-06-08 16:52:24 +00001557 }
1558 return error;
1559}
1560
1561Error
1562Process::Detach ()
1563{
1564 Error error (WillDetach());
1565
1566 if (error.Success())
1567 {
1568 DisableAllBreakpointSites();
1569 error = DoDetach();
1570 if (error.Success())
1571 {
1572 DidDetach();
1573 StopPrivateStateThread();
1574 }
1575 }
1576 return error;
1577}
1578
1579Error
1580Process::Destroy ()
1581{
1582 Error error (WillDestroy());
1583 if (error.Success())
1584 {
1585 DisableAllBreakpointSites();
1586 error = DoDestroy();
1587 if (error.Success())
1588 {
1589 DidDestroy();
1590 StopPrivateStateThread();
1591 }
Caroline Tice861efb32010-11-16 05:07:41 +00001592 m_stdio_communication.StopReadThread();
1593 m_stdio_communication.Disconnect();
1594 if (m_process_input_reader && m_process_input_reader->IsActive())
1595 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1596 if (m_process_input_reader)
1597 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001598 }
1599 return error;
1600}
1601
1602Error
1603Process::Signal (int signal)
1604{
1605 Error error (WillSignal());
1606 if (error.Success())
1607 {
1608 error = DoSignal(signal);
1609 if (error.Success())
1610 DidSignal();
1611 }
1612 return error;
1613}
1614
1615UnixSignals &
1616Process::GetUnixSignals ()
1617{
1618 return m_unix_signals;
1619}
1620
1621Target &
1622Process::GetTarget ()
1623{
1624 return m_target;
1625}
1626
1627const Target &
1628Process::GetTarget () const
1629{
1630 return m_target;
1631}
1632
1633uint32_t
1634Process::GetAddressByteSize()
1635{
Greg Clayton20d338f2010-11-18 05:57:03 +00001636 if (m_addr_byte_size == 0)
1637 return m_target.GetArchitecture().GetAddressByteSize();
1638 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001639}
1640
1641bool
1642Process::ShouldBroadcastEvent (Event *event_ptr)
1643{
1644 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1645 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001646 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001647
1648 switch (state)
1649 {
1650 case eStateAttaching:
1651 case eStateLaunching:
1652 case eStateDetached:
1653 case eStateExited:
1654 case eStateUnloaded:
1655 // These events indicate changes in the state of the debugging session, always report them.
1656 return_value = true;
1657 break;
1658 case eStateInvalid:
1659 // We stopped for no apparent reason, don't report it.
1660 return_value = false;
1661 break;
1662 case eStateRunning:
1663 case eStateStepping:
1664 // If we've started the target running, we handle the cases where we
1665 // are already running and where there is a transition from stopped to
1666 // running differently.
1667 // running -> running: Automatically suppress extra running events
1668 // stopped -> running: Report except when there is one or more no votes
1669 // and no yes votes.
1670 SynchronouslyNotifyStateChanged (state);
1671 switch (m_public_state.GetValue())
1672 {
1673 case eStateRunning:
1674 case eStateStepping:
1675 // We always suppress multiple runnings with no PUBLIC stop in between.
1676 return_value = false;
1677 break;
1678 default:
1679 // TODO: make this work correctly. For now always report
1680 // run if we aren't running so we don't miss any runnning
1681 // events. If I run the lldb/test/thread/a.out file and
1682 // break at main.cpp:58, run and hit the breakpoints on
1683 // multiple threads, then somehow during the stepping over
1684 // of all breakpoints no run gets reported.
1685 return_value = true;
1686
1687 // This is a transition from stop to run.
1688 switch (m_thread_list.ShouldReportRun (event_ptr))
1689 {
1690 case eVoteYes:
1691 case eVoteNoOpinion:
1692 return_value = true;
1693 break;
1694 case eVoteNo:
1695 return_value = false;
1696 break;
1697 }
1698 break;
1699 }
1700 break;
1701 case eStateStopped:
1702 case eStateCrashed:
1703 case eStateSuspended:
1704 {
1705 // We've stopped. First see if we're going to restart the target.
1706 // If we are going to stop, then we always broadcast the event.
1707 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00001708 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001709 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001710 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001711 if (log)
1712 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001713 return true;
1714 }
1715 else
1716 {
Chris Lattner24943d22010-06-08 16:52:24 +00001717 RefreshStateAfterStop ();
1718
1719 if (m_thread_list.ShouldStop (event_ptr) == false)
1720 {
1721 switch (m_thread_list.ShouldReportStop (event_ptr))
1722 {
1723 case eVoteYes:
1724 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001725 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001726 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001727 case eVoteNo:
1728 return_value = false;
1729 break;
1730 }
1731
1732 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001733 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001734 Resume ();
1735 }
1736 else
1737 {
1738 return_value = true;
1739 SynchronouslyNotifyStateChanged (state);
1740 }
1741 }
1742 }
1743 }
1744
1745 if (log)
1746 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1747 return return_value;
1748}
1749
1750//------------------------------------------------------------------
1751// Thread Queries
1752//------------------------------------------------------------------
1753
1754ThreadList &
1755Process::GetThreadList ()
1756{
1757 return m_thread_list;
1758}
1759
1760const ThreadList &
1761Process::GetThreadList () const
1762{
1763 return m_thread_list;
1764}
1765
1766
1767bool
1768Process::StartPrivateStateThread ()
1769{
Greg Claytone005f2c2010-11-06 01:53:30 +00001770 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001771
1772 if (log)
1773 log->Printf ("Process::%s ( )", __FUNCTION__);
1774
1775 // Create a thread that watches our internal state and controls which
1776 // events make it to clients (into the DCProcess event queue).
1777 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1778 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1779}
1780
1781void
1782Process::PausePrivateStateThread ()
1783{
1784 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1785}
1786
1787void
1788Process::ResumePrivateStateThread ()
1789{
1790 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1791}
1792
1793void
1794Process::StopPrivateStateThread ()
1795{
1796 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1797}
1798
1799void
1800Process::ControlPrivateStateThread (uint32_t signal)
1801{
Greg Claytone005f2c2010-11-06 01:53:30 +00001802 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001803
1804 assert (signal == eBroadcastInternalStateControlStop ||
1805 signal == eBroadcastInternalStateControlPause ||
1806 signal == eBroadcastInternalStateControlResume);
1807
1808 if (log)
1809 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1810
1811 // Signal the private state thread
1812 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1813 {
1814 TimeValue timeout_time;
1815 bool timed_out;
1816
1817 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1818
1819 timeout_time = TimeValue::Now();
1820 timeout_time.OffsetWithSeconds(2);
1821 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1822 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1823
1824 if (signal == eBroadcastInternalStateControlStop)
1825 {
1826 if (timed_out)
1827 Host::ThreadCancel (m_private_state_thread, NULL);
1828
1829 thread_result_t result = NULL;
1830 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00001831 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001832 }
1833 }
1834}
1835
1836void
1837Process::HandlePrivateEvent (EventSP &event_sp)
1838{
Greg Claytone005f2c2010-11-06 01:53:30 +00001839 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001840 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1841 // See if we should broadcast this state to external clients?
1842 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1843 if (log)
1844 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1845
1846 if (should_broadcast)
1847 {
1848 if (log)
1849 {
1850 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1851 }
Caroline Tice861efb32010-11-16 05:07:41 +00001852 if (StateIsRunningState (internal_state))
1853 PushProcessInputReader ();
1854 else
1855 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00001856 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1857 BroadcastEvent (event_sp);
1858 }
1859 else
1860 {
1861 if (log)
1862 {
1863 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1864 }
1865 }
1866}
1867
1868void *
1869Process::PrivateStateThread (void *arg)
1870{
1871 Process *proc = static_cast<Process*> (arg);
1872 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001873 return result;
1874}
1875
1876void *
1877Process::RunPrivateStateThread ()
1878{
1879 bool control_only = false;
1880 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1881
Greg Claytone005f2c2010-11-06 01:53:30 +00001882 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001883 if (log)
1884 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1885
1886 bool exit_now = false;
1887 while (!exit_now)
1888 {
1889 EventSP event_sp;
1890 WaitForEventsPrivate (NULL, event_sp, control_only);
1891 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1892 {
1893 switch (event_sp->GetType())
1894 {
1895 case eBroadcastInternalStateControlStop:
1896 exit_now = true;
1897 continue; // Go to next loop iteration so we exit without
1898 break; // doing any internal state managment below
1899
1900 case eBroadcastInternalStateControlPause:
1901 control_only = true;
1902 break;
1903
1904 case eBroadcastInternalStateControlResume:
1905 control_only = false;
1906 break;
1907 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001908
1909 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1910 if (log)
1911 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
1912
Chris Lattner24943d22010-06-08 16:52:24 +00001913 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00001914 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00001915 }
1916
1917
1918 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1919
1920 if (internal_state != eStateInvalid)
1921 {
1922 HandlePrivateEvent (event_sp);
1923 }
1924
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001925 if (internal_state == eStateInvalid ||
1926 internal_state == eStateExited ||
1927 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00001928 {
1929 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1930 if (log)
1931 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
1932
Chris Lattner24943d22010-06-08 16:52:24 +00001933 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001934 }
Chris Lattner24943d22010-06-08 16:52:24 +00001935 }
1936
Caroline Tice926060e2010-10-29 21:48:37 +00001937 // Verify log is still enabled before attempting to write to it...
1938 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00001939 if (log)
1940 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1941
Greg Clayton8b4c16e2010-08-19 21:50:06 +00001942 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00001943 return NULL;
1944}
1945
Chris Lattner24943d22010-06-08 16:52:24 +00001946//------------------------------------------------------------------
1947// Process Event Data
1948//------------------------------------------------------------------
1949
1950Process::ProcessEventData::ProcessEventData () :
1951 EventData (),
1952 m_process_sp (),
1953 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001954 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00001955 m_update_state (false),
1956 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001957{
1958}
1959
1960Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1961 EventData (),
1962 m_process_sp (process_sp),
1963 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001964 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00001965 m_update_state (false),
1966 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00001967{
1968}
1969
1970Process::ProcessEventData::~ProcessEventData()
1971{
1972}
1973
1974const ConstString &
1975Process::ProcessEventData::GetFlavorString ()
1976{
1977 static ConstString g_flavor ("Process::ProcessEventData");
1978 return g_flavor;
1979}
1980
1981const ConstString &
1982Process::ProcessEventData::GetFlavor () const
1983{
1984 return ProcessEventData::GetFlavorString ();
1985}
1986
Chris Lattner24943d22010-06-08 16:52:24 +00001987void
1988Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1989{
1990 // This function gets called twice for each event, once when the event gets pulled
1991 // off of the private process event queue, and once when it gets pulled off of
1992 // the public event queue. m_update_state is used to distinguish these
1993 // two cases; it is false when we're just pulling it off for private handling,
1994 // and we don't want to do the breakpoint command handling then.
1995
1996 if (!m_update_state)
1997 return;
1998
1999 m_process_sp->SetPublicState (m_state);
2000
2001 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2002 if (m_state == eStateStopped && ! m_restarted)
2003 {
2004 int num_threads = m_process_sp->GetThreadList().GetSize();
2005 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002006
Chris Lattner24943d22010-06-08 16:52:24 +00002007 for (idx = 0; idx < num_threads; ++idx)
2008 {
2009 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2010
Jim Ingham6297a3a2010-10-20 00:39:53 +00002011 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2012 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002013 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002014 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002015 }
2016 }
Greg Clayton643ee732010-08-04 01:40:35 +00002017
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002018 // The stop action might restart the target. If it does, then we want to mark that in the
2019 // event so that whoever is receiving it will know to wait for the running event and reflect
2020 // that state appropriately.
2021
Chris Lattner24943d22010-06-08 16:52:24 +00002022 if (m_process_sp->GetPrivateState() == eStateRunning)
2023 SetRestarted(true);
2024 }
2025}
2026
2027void
2028Process::ProcessEventData::Dump (Stream *s) const
2029{
2030 if (m_process_sp)
2031 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2032
2033 s->Printf("state = %s", StateAsCString(GetState()));;
2034}
2035
2036const Process::ProcessEventData *
2037Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2038{
2039 if (event_ptr)
2040 {
2041 const EventData *event_data = event_ptr->GetData();
2042 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2043 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2044 }
2045 return NULL;
2046}
2047
2048ProcessSP
2049Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2050{
2051 ProcessSP process_sp;
2052 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2053 if (data)
2054 process_sp = data->GetProcessSP();
2055 return process_sp;
2056}
2057
2058StateType
2059Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2060{
2061 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2062 if (data == NULL)
2063 return eStateInvalid;
2064 else
2065 return data->GetState();
2066}
2067
2068bool
2069Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2070{
2071 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2072 if (data == NULL)
2073 return false;
2074 else
2075 return data->GetRestarted();
2076}
2077
2078void
2079Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2080{
2081 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2082 if (data != NULL)
2083 data->SetRestarted(new_value);
2084}
2085
2086bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002087Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2088{
2089 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2090 if (data == NULL)
2091 return false;
2092 else
2093 return data->GetInterrupted ();
2094}
2095
2096void
2097Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2098{
2099 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2100 if (data != NULL)
2101 data->SetInterrupted(new_value);
2102}
2103
2104bool
Chris Lattner24943d22010-06-08 16:52:24 +00002105Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2106{
2107 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2108 if (data)
2109 {
2110 data->SetUpdateStateOnRemoval();
2111 return true;
2112 }
2113 return false;
2114}
2115
Chris Lattner24943d22010-06-08 16:52:24 +00002116Target *
2117Process::CalculateTarget ()
2118{
2119 return &m_target;
2120}
2121
2122Process *
2123Process::CalculateProcess ()
2124{
2125 return this;
2126}
2127
2128Thread *
2129Process::CalculateThread ()
2130{
2131 return NULL;
2132}
2133
2134StackFrame *
2135Process::CalculateStackFrame ()
2136{
2137 return NULL;
2138}
2139
2140void
Greg Claytona830adb2010-10-04 01:05:56 +00002141Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002142{
2143 exe_ctx.target = &m_target;
2144 exe_ctx.process = this;
2145 exe_ctx.thread = NULL;
2146 exe_ctx.frame = NULL;
2147}
2148
2149lldb::ProcessSP
2150Process::GetSP ()
2151{
2152 return GetTarget().GetProcessSP();
2153}
2154
Sean Callanana48fe162010-08-11 03:57:18 +00002155ClangPersistentVariables &
2156Process::GetPersistentVariables()
2157{
2158 return m_persistent_vars;
2159}
2160
Jim Ingham7508e732010-08-09 23:31:02 +00002161uint32_t
2162Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2163{
2164 return 0;
2165}
2166
2167ArchSpec
2168Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2169{
2170 return Host::GetArchSpecForExistingProcess (pid);
2171}
2172
2173ArchSpec
2174Process::GetArchSpecForExistingProcess (const char *process_name)
2175{
2176 return Host::GetArchSpecForExistingProcess (process_name);
2177}
2178
Caroline Tice861efb32010-11-16 05:07:41 +00002179void
2180Process::AppendSTDOUT (const char * s, size_t len)
2181{
Greg Clayton20d338f2010-11-18 05:57:03 +00002182 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002183 m_stdout_data.append (s, len);
2184
2185 BroadcastEventIfUnique (eBroadcastBitSTDOUT);
2186}
2187
2188void
2189Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2190{
2191 Process *process = (Process *) baton;
2192 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2193}
2194
2195size_t
2196Process::ProcessInputReaderCallback (void *baton,
2197 InputReader &reader,
2198 lldb::InputReaderAction notification,
2199 const char *bytes,
2200 size_t bytes_len)
2201{
2202 Process *process = (Process *) baton;
2203
2204 switch (notification)
2205 {
2206 case eInputReaderActivate:
2207 break;
2208
2209 case eInputReaderDeactivate:
2210 break;
2211
2212 case eInputReaderReactivate:
2213 break;
2214
2215 case eInputReaderGotToken:
2216 {
2217 Error error;
2218 process->PutSTDIN (bytes, bytes_len, error);
2219 }
2220 break;
2221
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002222 case eInputReaderInterrupt:
2223 process->Halt ();
2224 break;
2225
2226 case eInputReaderEndOfFile:
2227 process->AppendSTDOUT ("^D", 2);
2228 break;
2229
Caroline Tice861efb32010-11-16 05:07:41 +00002230 case eInputReaderDone:
2231 break;
2232
2233 }
2234
2235 return bytes_len;
2236}
2237
2238void
2239Process::ResetProcessInputReader ()
2240{
2241 m_process_input_reader.reset();
2242}
2243
2244void
2245Process::SetUpProcessInputReader (int file_descriptor)
2246{
2247 // First set up the Read Thread for reading/handling process I/O
2248
2249 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2250
2251 if (conn_ap.get())
2252 {
2253 m_stdio_communication.SetConnection (conn_ap.release());
2254 if (m_stdio_communication.IsConnected())
2255 {
2256 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2257 m_stdio_communication.StartReadThread();
2258
2259 // Now read thread is set up, set up input reader.
2260
2261 if (!m_process_input_reader.get())
2262 {
2263 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2264 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2265 this,
2266 eInputReaderGranularityByte,
2267 NULL,
2268 NULL,
2269 false));
2270
2271 if (err.Fail())
2272 m_process_input_reader.reset();
2273 }
2274 }
2275 }
2276}
2277
2278void
2279Process::PushProcessInputReader ()
2280{
2281 if (m_process_input_reader && !m_process_input_reader->IsActive())
2282 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2283}
2284
2285void
2286Process::PopProcessInputReader ()
2287{
2288 if (m_process_input_reader && m_process_input_reader->IsActive())
2289 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2290}
2291
Greg Clayton990de7b2010-11-18 23:32:35 +00002292
2293void
2294Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002295{
Greg Clayton990de7b2010-11-18 23:32:35 +00002296 UserSettingsControllerSP &usc = GetSettingsController();
2297 usc.reset (new SettingsController);
2298 UserSettingsController::InitializeSettingsController (usc,
2299 SettingsController::global_settings_table,
2300 SettingsController::instance_settings_table);
2301}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002302
Greg Clayton990de7b2010-11-18 23:32:35 +00002303void
2304Process::Terminate ()
2305{
2306 UserSettingsControllerSP &usc = GetSettingsController();
2307 UserSettingsController::FinalizeSettingsController (usc);
2308 usc.reset();
2309}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002310
Greg Clayton990de7b2010-11-18 23:32:35 +00002311UserSettingsControllerSP &
2312Process::GetSettingsController ()
2313{
2314 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002315 return g_settings_controller;
2316}
2317
Caroline Tice1ebef442010-09-27 00:30:10 +00002318void
2319Process::UpdateInstanceName ()
2320{
2321 ModuleSP module_sp = GetTarget().GetExecutableModule();
2322 if (module_sp)
2323 {
2324 StreamString sstr;
2325 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2326
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002327 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002328 sstr.GetData());
2329 }
2330}
2331
Jim Ingham360f53f2010-11-30 02:22:11 +00002332Process::ExecutionResults
2333Process::RunThreadPlan (ExecutionContext &exe_ctx,
2334 lldb::ThreadPlanSP &thread_plan_sp,
2335 bool stop_others,
2336 bool try_all_threads,
2337 bool discard_on_error,
2338 uint32_t single_thread_timeout_usec,
2339 Stream &errors)
2340{
2341 ExecutionResults return_value = eExecutionSetupError;
2342
2343 // Save this value for restoration of the execution context after we run
2344 uint32_t tid = exe_ctx.thread->GetIndexID();
2345
2346 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2347 // so we should arrange to reset them as well.
2348
2349 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2350 lldb::StackFrameSP selected_frame_sp;
2351
2352 uint32_t selected_tid;
2353 if (selected_thread_sp != NULL)
2354 {
2355 selected_tid = selected_thread_sp->GetIndexID();
2356 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2357 }
2358 else
2359 {
2360 selected_tid = LLDB_INVALID_THREAD_ID;
2361 }
2362
2363 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2364
2365 Listener listener("ClangFunction temporary listener");
2366 exe_ctx.process->HijackProcessEvents(&listener);
2367
2368 Error resume_error = exe_ctx.process->Resume ();
2369 if (!resume_error.Success())
2370 {
2371 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2372 exe_ctx.process->RestoreProcessEvents();
2373 return Process::eExecutionSetupError;
2374 }
2375
2376 // We need to call the function synchronously, so spin waiting for it to return.
2377 // If we get interrupted while executing, we're going to lose our context, and
2378 // won't be able to gather the result at this point.
2379 // We set the timeout AFTER the resume, since the resume takes some time and we
2380 // don't want to charge that to the timeout.
2381
2382 TimeValue* timeout_ptr = NULL;
2383 TimeValue real_timeout;
2384
2385 if (single_thread_timeout_usec != 0)
2386 {
2387 real_timeout = TimeValue::Now();
2388 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2389 timeout_ptr = &real_timeout;
2390 }
2391
2392 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2393 while (1)
2394 {
2395 lldb::EventSP event_sp;
2396 lldb::StateType stop_state = lldb::eStateInvalid;
2397 // Now wait for the process to stop again:
2398 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2399
2400 if (!got_event)
2401 {
2402 // Right now this is the only way to tell we've timed out...
2403 // We should interrupt the process here...
2404 // Not really sure what to do if Halt fails here...
2405 if (log)
2406 if (try_all_threads)
2407 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2408 single_thread_timeout_usec);
2409 else
2410 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2411 single_thread_timeout_usec);
2412
2413 if (exe_ctx.process->Halt().Success())
2414 {
2415 timeout_ptr = NULL;
2416 if (log)
2417 log->Printf ("Halt succeeded.");
2418
2419 // Between the time that we got the timeout and the time we halted, but target
2420 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2421 // timeout to
2422 got_event = listener.WaitForEvent(NULL, event_sp);
2423
2424 if (got_event)
2425 {
2426 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2427 if (log)
2428 {
2429 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2430 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2431 log->Printf (" Event was the Halt interruption event.");
2432 }
2433
2434 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2435 {
2436 if (log)
2437 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
2438 return_value = Process::eExecutionCompleted;
2439 break;
2440 }
2441
2442 if (try_all_threads
2443 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2444 {
2445
2446 thread_plan_sp->SetStopOthers (false);
2447 if (log)
2448 log->Printf ("About to resume.");
2449
2450 exe_ctx.process->Resume();
2451 continue;
2452 }
2453 else
2454 {
2455 exe_ctx.process->RestoreProcessEvents ();
2456 return Process::eExecutionInterrupted;
2457 }
2458 }
2459 }
2460 }
2461
2462 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2463 if (log)
2464 log->Printf("Got event: %s.", StateAsCString(stop_state));
2465
2466 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2467 continue;
2468
2469 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2470 {
2471 return_value = Process::eExecutionCompleted;
2472 break;
2473 }
2474 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2475 {
2476 return_value = Process::eExecutionDiscarded;
2477 break;
2478 }
2479 else
2480 {
2481 if (log)
2482 {
2483 StreamString s;
2484 event_sp->Dump (&s);
2485 StreamString ts;
2486
2487 const char *event_explanation;
2488
2489 do
2490 {
2491 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2492
2493 if (!event_data)
2494 {
2495 event_explanation = "<no event data>";
2496 break;
2497 }
2498
2499 Process *process = event_data->GetProcessSP().get();
2500
2501 if (!process)
2502 {
2503 event_explanation = "<no process>";
2504 break;
2505 }
2506
2507 ThreadList &thread_list = process->GetThreadList();
2508
2509 uint32_t num_threads = thread_list.GetSize();
2510 uint32_t thread_index;
2511
2512 ts.Printf("<%u threads> ", num_threads);
2513
2514 for (thread_index = 0;
2515 thread_index < num_threads;
2516 ++thread_index)
2517 {
2518 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2519
2520 if (!thread)
2521 {
2522 ts.Printf("<?> ");
2523 continue;
2524 }
2525
2526 ts.Printf("<");
2527 RegisterContext *register_context = thread->GetRegisterContext();
2528
2529 if (register_context)
2530 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2531 else
2532 ts.Printf("[ip unknown] ");
2533
2534 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2535 if (stop_info_sp)
2536 {
2537 const char *stop_desc = stop_info_sp->GetDescription();
2538 if (stop_desc)
2539 ts.PutCString (stop_desc);
2540 }
2541 ts.Printf(">");
2542 }
2543
2544 event_explanation = ts.GetData();
2545 } while (0);
2546
2547 if (log)
2548 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2549 }
2550
2551 if (discard_on_error && thread_plan_sp)
2552 {
2553 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2554 }
2555 return_value = Process::eExecutionInterrupted;
2556 break;
2557 }
2558 }
2559
2560 if (exe_ctx.process)
2561 exe_ctx.process->RestoreProcessEvents ();
2562
2563 // Thread we ran the function in may have gone away because we ran the target
2564 // Check that it's still there.
2565 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2566 if (exe_ctx.thread)
2567 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2568
2569 // Also restore the current process'es selected frame & thread, since this function calling may
2570 // be done behind the user's back.
2571
2572 if (selected_tid != LLDB_INVALID_THREAD_ID)
2573 {
2574 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2575 {
2576 // We were able to restore the selected thread, now restore the frame:
2577 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2578 }
2579 }
2580
2581 return return_value;
2582}
2583
2584const char *
2585Process::ExecutionResultAsCString (ExecutionResults result)
2586{
2587 const char *result_name;
2588
2589 switch (result)
2590 {
2591 case Process::eExecutionCompleted:
2592 result_name = "eExecutionCompleted";
2593 break;
2594 case Process::eExecutionDiscarded:
2595 result_name = "eExecutionDiscarded";
2596 break;
2597 case Process::eExecutionInterrupted:
2598 result_name = "eExecutionInterrupted";
2599 break;
2600 case Process::eExecutionSetupError:
2601 result_name = "eExecutionSetupError";
2602 break;
2603 case Process::eExecutionTimedOut:
2604 result_name = "eExecutionTimedOut";
2605 break;
2606 }
2607 return result_name;
2608}
2609
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002610//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002611// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002612//--------------------------------------------------------------
2613
Greg Claytond0a5a232010-09-19 02:33:57 +00002614Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002615 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002616{
Greg Clayton638351a2010-12-04 00:10:17 +00002617 m_default_settings.reset (new ProcessInstanceSettings (*this,
2618 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002619 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002620}
2621
Greg Claytond0a5a232010-09-19 02:33:57 +00002622Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002623{
2624}
2625
2626lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002627Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002628{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002629 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2630 false,
2631 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002632 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2633 return new_settings_sp;
2634}
2635
2636//--------------------------------------------------------------
2637// class ProcessInstanceSettings
2638//--------------------------------------------------------------
2639
Greg Clayton638351a2010-12-04 00:10:17 +00002640ProcessInstanceSettings::ProcessInstanceSettings
2641(
2642 UserSettingsController &owner,
2643 bool live_instance,
2644 const char *name
2645) :
2646 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002647 m_run_args (),
2648 m_env_vars (),
2649 m_input_path (),
2650 m_output_path (),
2651 m_error_path (),
2652 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002653 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002654 m_disable_stdio (false),
2655 m_inherit_host_env (true),
2656 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002657{
Caroline Tice396704b2010-09-09 18:26:37 +00002658 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2659 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2660 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00002661 // This is true for CreateInstanceName() too.
2662
2663 if (GetInstanceName () == InstanceSettings::InvalidName())
2664 {
2665 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2666 m_owner.RegisterInstanceSettings (this);
2667 }
Caroline Tice396704b2010-09-09 18:26:37 +00002668
2669 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002670 {
2671 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2672 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002673 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002674 }
2675}
2676
2677ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002678 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002679 m_run_args (rhs.m_run_args),
2680 m_env_vars (rhs.m_env_vars),
2681 m_input_path (rhs.m_input_path),
2682 m_output_path (rhs.m_output_path),
2683 m_error_path (rhs.m_error_path),
2684 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00002685 m_disable_aslr (rhs.m_disable_aslr),
2686 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002687{
2688 if (m_instance_name != InstanceSettings::GetDefaultName())
2689 {
2690 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2691 CopyInstanceSettings (pending_settings,false);
2692 m_owner.RemovePendingSettings (m_instance_name);
2693 }
2694}
2695
2696ProcessInstanceSettings::~ProcessInstanceSettings ()
2697{
2698}
2699
2700ProcessInstanceSettings&
2701ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2702{
2703 if (this != &rhs)
2704 {
2705 m_run_args = rhs.m_run_args;
2706 m_env_vars = rhs.m_env_vars;
2707 m_input_path = rhs.m_input_path;
2708 m_output_path = rhs.m_output_path;
2709 m_error_path = rhs.m_error_path;
2710 m_plugin = rhs.m_plugin;
2711 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002712 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00002713 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002714 }
2715
2716 return *this;
2717}
2718
2719
2720void
2721ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2722 const char *index_value,
2723 const char *value,
2724 const ConstString &instance_name,
2725 const SettingEntry &entry,
2726 lldb::VarSetOperationType op,
2727 Error &err,
2728 bool pending)
2729{
2730 if (var_name == RunArgsVarName())
2731 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2732 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00002733 {
2734 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002735 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002736 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002737 else if (var_name == InputPathVarName())
2738 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2739 else if (var_name == OutputPathVarName())
2740 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2741 else if (var_name == ErrorPathVarName())
2742 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2743 else if (var_name == PluginVarName())
2744 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002745 else if (var_name == InheritHostEnvVarName())
2746 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002747 else if (var_name == DisableASLRVarName())
2748 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00002749 else if (var_name == DisableSTDIOVarName ())
2750 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002751}
2752
2753void
2754ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2755 bool pending)
2756{
2757 if (new_settings.get() == NULL)
2758 return;
2759
2760 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2761
2762 m_run_args = new_process_settings->m_run_args;
2763 m_env_vars = new_process_settings->m_env_vars;
2764 m_input_path = new_process_settings->m_input_path;
2765 m_output_path = new_process_settings->m_output_path;
2766 m_error_path = new_process_settings->m_error_path;
2767 m_plugin = new_process_settings->m_plugin;
2768 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002769 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002770}
2771
Caroline Ticebcb5b452010-09-20 21:37:42 +00002772bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002773ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2774 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00002775 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00002776 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002777{
2778 if (var_name == RunArgsVarName())
2779 {
2780 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00002781 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002782 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2783 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00002784 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002785 }
2786 else if (var_name == EnvVarsVarName())
2787 {
Greg Clayton638351a2010-12-04 00:10:17 +00002788 GetHostEnvironmentIfNeeded ();
2789
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002790 if (m_env_vars.size() > 0)
2791 {
2792 std::map<std::string, std::string>::iterator pos;
2793 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2794 {
2795 StreamString value_str;
2796 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2797 value.AppendString (value_str.GetData());
2798 }
2799 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002800 }
2801 else if (var_name == InputPathVarName())
2802 {
2803 value.AppendString (m_input_path.c_str());
2804 }
2805 else if (var_name == OutputPathVarName())
2806 {
2807 value.AppendString (m_output_path.c_str());
2808 }
2809 else if (var_name == ErrorPathVarName())
2810 {
2811 value.AppendString (m_error_path.c_str());
2812 }
2813 else if (var_name == PluginVarName())
2814 {
2815 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
2816 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00002817 else if (var_name == InheritHostEnvVarName())
2818 {
2819 if (m_inherit_host_env)
2820 value.AppendString ("true");
2821 else
2822 value.AppendString ("false");
2823 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002824 else if (var_name == DisableASLRVarName())
2825 {
2826 if (m_disable_aslr)
2827 value.AppendString ("true");
2828 else
2829 value.AppendString ("false");
2830 }
Caroline Ticebd666012010-12-03 18:46:09 +00002831 else if (var_name == DisableSTDIOVarName())
2832 {
2833 if (m_disable_stdio)
2834 value.AppendString ("true");
2835 else
2836 value.AppendString ("false");
2837 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002838 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00002839 {
2840 if (err)
2841 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2842 return false;
2843 }
2844 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002845}
2846
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002847const ConstString
2848ProcessInstanceSettings::CreateInstanceName ()
2849{
2850 static int instance_count = 1;
2851 StreamString sstr;
2852
2853 sstr.Printf ("process_%d", instance_count);
2854 ++instance_count;
2855
2856 const ConstString ret_val (sstr.GetData());
2857 return ret_val;
2858}
2859
2860const ConstString &
2861ProcessInstanceSettings::RunArgsVarName ()
2862{
2863 static ConstString run_args_var_name ("run-args");
2864
2865 return run_args_var_name;
2866}
2867
2868const ConstString &
2869ProcessInstanceSettings::EnvVarsVarName ()
2870{
2871 static ConstString env_vars_var_name ("env-vars");
2872
2873 return env_vars_var_name;
2874}
2875
2876const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00002877ProcessInstanceSettings::InheritHostEnvVarName ()
2878{
2879 static ConstString g_name ("inherit-env");
2880
2881 return g_name;
2882}
2883
2884const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002885ProcessInstanceSettings::InputPathVarName ()
2886{
2887 static ConstString input_path_var_name ("input-path");
2888
2889 return input_path_var_name;
2890}
2891
2892const ConstString &
2893ProcessInstanceSettings::OutputPathVarName ()
2894{
Caroline Tice87097232010-09-07 18:35:40 +00002895 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002896
2897 return output_path_var_name;
2898}
2899
2900const ConstString &
2901ProcessInstanceSettings::ErrorPathVarName ()
2902{
Caroline Tice87097232010-09-07 18:35:40 +00002903 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002904
2905 return error_path_var_name;
2906}
2907
2908const ConstString &
2909ProcessInstanceSettings::PluginVarName ()
2910{
2911 static ConstString plugin_var_name ("plugin");
2912
2913 return plugin_var_name;
2914}
2915
2916
2917const ConstString &
2918ProcessInstanceSettings::DisableASLRVarName ()
2919{
2920 static ConstString disable_aslr_var_name ("disable-aslr");
2921
2922 return disable_aslr_var_name;
2923}
2924
Caroline Ticebd666012010-12-03 18:46:09 +00002925const ConstString &
2926ProcessInstanceSettings::DisableSTDIOVarName ()
2927{
2928 static ConstString disable_stdio_var_name ("disable-stdio");
2929
2930 return disable_stdio_var_name;
2931}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002932
2933//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002934// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002935//--------------------------------------------------
2936
2937SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002938Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002939{
2940 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
2941 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2942};
2943
2944
2945lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00002946Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002947{
Caroline Ticef2c330d2010-09-09 18:01:59 +00002948 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
2949 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
2950 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002951};
2952
2953SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00002954Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002955{
Greg Clayton638351a2010-12-04 00:10:17 +00002956 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
2957 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
2958 { "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." },
2959 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
2960 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
2961 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
2962 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
2963 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
2964 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
2965 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2966 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002967};
2968
2969
Jim Ingham7508e732010-08-09 23:31:02 +00002970