blob: 9538299c2a7bef201fb3ebce2425461d353c8348 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham22777012010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
Greg Clayton58be07b2011-01-07 06:08:19 +000040
41//----------------------------------------------------------------------
42// MemoryCache constructor
43//----------------------------------------------------------------------
44Process::MemoryCache::MemoryCache() :
45 m_cache_line_byte_size (512),
46 m_cache_mutex (Mutex::eMutexTypeRecursive),
47 m_cache ()
48{
49}
50
51//----------------------------------------------------------------------
52// Destructor
53//----------------------------------------------------------------------
54Process::MemoryCache::~MemoryCache()
55{
56}
57
58void
59Process::MemoryCache::Clear()
60{
61 Mutex::Locker locker (m_cache_mutex);
62 m_cache.clear();
63}
64
65void
66Process::MemoryCache::Flush (addr_t addr, size_t size)
67{
68 if (size == 0)
69 return;
70
71 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
72 const addr_t end_addr = (addr + size - 1);
73 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
74 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
75
76 Mutex::Locker locker (m_cache_mutex);
77 if (m_cache.empty())
78 return;
79
80 assert ((flush_start_addr % cache_line_byte_size) == 0);
81
82 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
83 {
84 collection::iterator pos = m_cache.find (curr_addr);
85 if (pos != m_cache.end())
86 m_cache.erase(pos);
87 }
88}
89
90size_t
91Process::MemoryCache::Read
92(
93 Process *process,
94 addr_t addr,
95 void *dst,
96 size_t dst_len,
97 Error &error
98)
99{
100 size_t bytes_left = dst_len;
101 if (dst && bytes_left > 0)
102 {
103 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
104 uint8_t *dst_buf = (uint8_t *)dst;
105 addr_t curr_addr = addr - (addr % cache_line_byte_size);
106 addr_t cache_offset = addr - curr_addr;
107 Mutex::Locker locker (m_cache_mutex);
108
109 while (bytes_left > 0)
110 {
111 collection::const_iterator pos = m_cache.find (curr_addr);
112 collection::const_iterator end = m_cache.end ();
113
114 if (pos != end)
115 {
116 size_t curr_read_size = cache_line_byte_size - cache_offset;
117 if (curr_read_size > bytes_left)
118 curr_read_size = bytes_left;
119
120 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
121
122 bytes_left -= curr_read_size;
123 curr_addr += curr_read_size + cache_offset;
124 cache_offset = 0;
125
126 if (bytes_left > 0)
127 {
128 // Get sequential cache page hits
129 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
130 {
131 assert ((curr_addr % cache_line_byte_size) == 0);
132
133 if (pos->first != curr_addr)
134 break;
135
136 curr_read_size = pos->second->GetByteSize();
137 if (curr_read_size > bytes_left)
138 curr_read_size = bytes_left;
139
140 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
141
142 bytes_left -= curr_read_size;
143 curr_addr += curr_read_size;
144
145 // We have a cache page that succeeded to read some bytes
146 // but not an entire page. If this happens, we must cap
147 // off how much data we are able to read...
148 if (pos->second->GetByteSize() != cache_line_byte_size)
149 return dst_len - bytes_left;
150 }
151 }
152 }
153
154 // We need to read from the process
155
156 if (bytes_left > 0)
157 {
158 assert ((curr_addr % cache_line_byte_size) == 0);
159 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
160 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
161 data_buffer_heap_ap->GetBytes(),
162 data_buffer_heap_ap->GetByteSize(),
163 error);
164 if (process_bytes_read == 0)
165 return dst_len - bytes_left;
166
167 if (process_bytes_read != cache_line_byte_size)
168 data_buffer_heap_ap->SetByteSize (process_bytes_read);
169 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
170 // We have read data and put it into the cache, continue through the
171 // loop again to get the data out of the cache...
172 }
173 }
174 }
175
176 return dst_len - bytes_left;
177}
178
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000179Process*
180Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
181{
182 ProcessCreateInstance create_callback = NULL;
183 if (plugin_name)
184 {
185 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
186 if (create_callback)
187 {
188 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
189 if (debugger_ap->CanDebug(target))
190 return debugger_ap.release();
191 }
192 }
193 else
194 {
Greg Claytonc982c762010-07-09 20:39:50 +0000195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000196 {
Greg Claytonc982c762010-07-09 20:39:50 +0000197 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
198 if (debugger_ap->CanDebug(target))
199 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200 }
201 }
202 return NULL;
203}
204
205
206//----------------------------------------------------------------------
207// Process constructor
208//----------------------------------------------------------------------
209Process::Process(Target &target, Listener &listener) :
210 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000211 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000212 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214 m_public_state (eStateUnloaded),
215 m_private_state (eStateUnloaded),
216 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
217 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
218 m_private_state_listener ("lldb.process.internal_state_listener"),
219 m_private_state_control_wait(),
220 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
221 m_stop_id (0),
222 m_thread_index_id (0),
223 m_exit_status (-1),
224 m_exit_string (),
225 m_thread_list (this),
226 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000227 m_image_tokens (),
228 m_listener (listener),
229 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000230 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000231 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000232 m_target_triple (),
233 m_byte_order (eByteOrderHost),
234 m_addr_byte_size (0),
235 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000236 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000237 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000239 m_stdout_data (),
240 m_memory_cache ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000241{
Caroline Tice1559a462010-09-27 00:30:10 +0000242 UpdateInstanceName();
243
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 if (log)
246 log->Printf ("%p Process::Process()", this);
247
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000248 SetEventName (eBroadcastBitStateChanged, "state-changed");
249 SetEventName (eBroadcastBitInterrupt, "interrupt");
250 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
251 SetEventName (eBroadcastBitSTDERR, "stderr-available");
252
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253 listener.StartListeningForEvents (this,
254 eBroadcastBitStateChanged |
255 eBroadcastBitInterrupt |
256 eBroadcastBitSTDOUT |
257 eBroadcastBitSTDERR);
258
259 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
260 eBroadcastBitStateChanged);
261
262 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
263 eBroadcastInternalStateControlStop |
264 eBroadcastInternalStateControlPause |
265 eBroadcastInternalStateControlResume);
266}
267
268//----------------------------------------------------------------------
269// Destructor
270//----------------------------------------------------------------------
271Process::~Process()
272{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274 if (log)
275 log->Printf ("%p Process::~Process()", this);
276 StopPrivateStateThread();
277}
278
279void
280Process::Finalize()
281{
282 // Do any cleanup needed prior to being destructed... Subclasses
283 // that override this method should call this superclass method as well.
284}
285
286void
287Process::RegisterNotificationCallbacks (const Notifications& callbacks)
288{
289 m_notifications.push_back(callbacks);
290 if (callbacks.initialize != NULL)
291 callbacks.initialize (callbacks.baton, this);
292}
293
294bool
295Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
296{
297 std::vector<Notifications>::iterator pos, end = m_notifications.end();
298 for (pos = m_notifications.begin(); pos != end; ++pos)
299 {
300 if (pos->baton == callbacks.baton &&
301 pos->initialize == callbacks.initialize &&
302 pos->process_state_changed == callbacks.process_state_changed)
303 {
304 m_notifications.erase(pos);
305 return true;
306 }
307 }
308 return false;
309}
310
311void
312Process::SynchronouslyNotifyStateChanged (StateType state)
313{
314 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
315 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
316 {
317 if (notification_pos->process_state_changed)
318 notification_pos->process_state_changed (notification_pos->baton, this, state);
319 }
320}
321
322// FIXME: We need to do some work on events before the general Listener sees them.
323// For instance if we are continuing from a breakpoint, we need to ensure that we do
324// the little "insert real insn, step & stop" trick. But we can't do that when the
325// event is delivered by the broadcaster - since that is done on the thread that is
326// waiting for new events, so if we needed more than one event for our handling, we would
327// stall. So instead we do it when we fetch the event off of the queue.
328//
329
330StateType
331Process::GetNextEvent (EventSP &event_sp)
332{
333 StateType state = eStateInvalid;
334
335 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
336 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
337
338 return state;
339}
340
341
342StateType
343Process::WaitForProcessToStop (const TimeValue *timeout)
344{
345 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
346 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
347}
348
349
350StateType
351Process::WaitForState
352(
353 const TimeValue *timeout,
354 const StateType *match_states, const uint32_t num_match_states
355)
356{
357 EventSP event_sp;
358 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000359 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 while (state != eStateInvalid)
361 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000362 // If we are exited or detached, we won't ever get back to any
363 // other valid state...
364 if (state == eStateDetached || state == eStateExited)
365 return state;
366
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367 state = WaitForStateChangedEvents (timeout, event_sp);
368
369 for (i=0; i<num_match_states; ++i)
370 {
371 if (match_states[i] == state)
372 return state;
373 }
374 }
375 return state;
376}
377
Jim Ingham30f9b212010-10-11 23:53:14 +0000378bool
379Process::HijackProcessEvents (Listener *listener)
380{
381 if (listener != NULL)
382 {
383 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
384 }
385 else
386 return false;
387}
388
389void
390Process::RestoreProcessEvents ()
391{
392 RestoreBroadcaster();
393}
394
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395StateType
396Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
397{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399
400 if (log)
401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
402
403 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000404 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
405 this,
406 eBroadcastBitStateChanged,
407 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
409
410 if (log)
411 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
412 __FUNCTION__,
413 timeout,
414 StateAsCString(state));
415 return state;
416}
417
418Event *
419Process::PeekAtStateChangedEvents ()
420{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000421 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422
423 if (log)
424 log->Printf ("Process::%s...", __FUNCTION__);
425
426 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000427 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
428 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429 if (log)
430 {
431 if (event_ptr)
432 {
433 log->Printf ("Process::%s (event_ptr) => %s",
434 __FUNCTION__,
435 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
436 }
437 else
438 {
439 log->Printf ("Process::%s no events found",
440 __FUNCTION__);
441 }
442 }
443 return event_ptr;
444}
445
446StateType
447Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
448{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000449 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450
451 if (log)
452 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
453
454 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000455 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
456 &m_private_state_broadcaster,
457 eBroadcastBitStateChanged,
458 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
460
461 // This is a bit of a hack, but when we wait here we could very well return
462 // to the command-line, and that could disable the log, which would render the
463 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000465 {
466 if (state == eStateInvalid)
467 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
468 else
469 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
470 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000471 return state;
472}
473
474bool
475Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
476{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000477 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000478
479 if (log)
480 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
481
482 if (control_only)
483 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
484 else
485 return m_private_state_listener.WaitForEvent(timeout, event_sp);
486}
487
488bool
489Process::IsRunning () const
490{
491 return StateIsRunningState (m_public_state.GetValue());
492}
493
494int
495Process::GetExitStatus ()
496{
497 if (m_public_state.GetValue() == eStateExited)
498 return m_exit_status;
499 return -1;
500}
501
Greg Clayton85851dd2010-12-04 00:10:17 +0000502
503void
504Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
505{
506 if (m_inherit_host_env && !m_got_host_env)
507 {
508 m_got_host_env = true;
509 StringList host_env;
510 const size_t host_env_count = Host::GetEnvironment (host_env);
511 for (size_t idx=0; idx<host_env_count; idx++)
512 {
513 const char *env_entry = host_env.GetStringAtIndex (idx);
514 if (env_entry)
515 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000516 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000517 if (equal_pos)
518 {
519 std::string key (env_entry, equal_pos - env_entry);
520 std::string value (equal_pos + 1);
521 if (m_env_vars.find (key) == m_env_vars.end())
522 m_env_vars[key] = value;
523 }
524 }
525 }
526 }
527}
528
529
530size_t
531Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
532{
533 GetHostEnvironmentIfNeeded ();
534
535 dictionary::const_iterator pos, end = m_env_vars.end();
536 for (pos = m_env_vars.begin(); pos != end; ++pos)
537 {
538 std::string env_var_equal_value (pos->first);
539 env_var_equal_value.append(1, '=');
540 env_var_equal_value.append (pos->second);
541 env.AppendArgument (env_var_equal_value.c_str());
542 }
543 return env.GetArgumentCount();
544}
545
546
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547const char *
548Process::GetExitDescription ()
549{
550 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
551 return m_exit_string.c_str();
552 return NULL;
553}
554
Greg Clayton6779606a2011-01-22 23:43:18 +0000555bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000556Process::SetExitStatus (int status, const char *cstr)
557{
Greg Clayton414f5d32011-01-25 02:58:48 +0000558 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
559 if (log)
560 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
561 status, status,
562 cstr ? "\"" : "",
563 cstr ? cstr : "NULL",
564 cstr ? "\"" : "");
565
Greg Clayton6779606a2011-01-22 23:43:18 +0000566 // We were already in the exited state
567 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000568 {
Greg Clayton385d6032011-01-26 23:47:29 +0000569 if (log)
570 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000571 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000572 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000573
574 m_exit_status = status;
575 if (cstr)
576 m_exit_string = cstr;
577 else
578 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000579
Greg Clayton6779606a2011-01-22 23:43:18 +0000580 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000581
Greg Clayton6779606a2011-01-22 23:43:18 +0000582 SetPrivateState (eStateExited);
583 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584}
585
586// This static callback can be used to watch for local child processes on
587// the current host. The the child process exits, the process will be
588// found in the global target list (we want to be completely sure that the
589// lldb_private::Process doesn't go away before we can deliver the signal.
590bool
591Process::SetProcessExitStatus
592(
593 void *callback_baton,
594 lldb::pid_t pid,
595 int signo, // Zero for no signal
596 int exit_status // Exit value of process if signal is zero
597)
598{
599 if (signo == 0 || exit_status)
600 {
Greg Clayton66111032010-06-23 01:19:29 +0000601 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 if (target_sp)
603 {
604 ProcessSP process_sp (target_sp->GetProcessSP());
605 if (process_sp)
606 {
607 const char *signal_cstr = NULL;
608 if (signo)
609 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
610
611 process_sp->SetExitStatus (exit_status, signal_cstr);
612 }
613 }
614 return true;
615 }
616 return false;
617}
618
619
620uint32_t
621Process::GetNextThreadIndexID ()
622{
623 return ++m_thread_index_id;
624}
625
626StateType
627Process::GetState()
628{
629 // If any other threads access this we will need a mutex for it
630 return m_public_state.GetValue ();
631}
632
633void
634Process::SetPublicState (StateType new_state)
635{
Greg Clayton414f5d32011-01-25 02:58:48 +0000636 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 if (log)
638 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
639 m_public_state.SetValue (new_state);
640}
641
642StateType
643Process::GetPrivateState ()
644{
645 return m_private_state.GetValue();
646}
647
648void
649Process::SetPrivateState (StateType new_state)
650{
Greg Clayton414f5d32011-01-25 02:58:48 +0000651 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 bool state_changed = false;
653
654 if (log)
655 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
656
657 Mutex::Locker locker(m_private_state.GetMutex());
658
659 const StateType old_state = m_private_state.GetValueNoLock ();
660 state_changed = old_state != new_state;
661 if (state_changed)
662 {
663 m_private_state.SetValueNoLock (new_state);
664 if (StateIsStoppedState(new_state))
665 {
666 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000667 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 if (log)
669 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
670 }
671 // Use our target to get a shared pointer to ourselves...
672 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
673 }
674 else
675 {
676 if (log)
677 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
678 }
679}
680
681
682uint32_t
683Process::GetStopID() const
684{
685 return m_stop_id;
686}
687
688addr_t
689Process::GetImageInfoAddress()
690{
691 return LLDB_INVALID_ADDRESS;
692}
693
Greg Clayton8f343b02010-11-04 01:54:29 +0000694//----------------------------------------------------------------------
695// LoadImage
696//
697// This function provides a default implementation that works for most
698// unix variants. Any Process subclasses that need to do shared library
699// loading differently should override LoadImage and UnloadImage and
700// do what is needed.
701//----------------------------------------------------------------------
702uint32_t
703Process::LoadImage (const FileSpec &image_spec, Error &error)
704{
705 DynamicLoader *loader = GetDynamicLoader();
706 if (loader)
707 {
708 error = loader->CanLoadImage();
709 if (error.Fail())
710 return LLDB_INVALID_IMAGE_TOKEN;
711 }
712
713 if (error.Success())
714 {
715 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
716 if (thread_sp == NULL)
717 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
718
719 if (thread_sp)
720 {
721 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
722
723 if (frame_sp)
724 {
725 ExecutionContext exe_ctx;
726 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000727 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000728 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000729 StreamString expr;
730 char path[PATH_MAX];
731 image_spec.GetPath(path, sizeof(path));
732 expr.Printf("dlopen (\"%s\", 2)", path);
733 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000734 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000735 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000736 if (result_valobj_sp->GetError().Success())
737 {
738 Scalar scalar;
739 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
740 {
741 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
742 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
743 {
744 uint32_t image_token = m_image_tokens.size();
745 m_image_tokens.push_back (image_ptr);
746 return image_token;
747 }
748 }
749 }
750 }
751 }
752 }
753 return LLDB_INVALID_IMAGE_TOKEN;
754}
755
756//----------------------------------------------------------------------
757// UnloadImage
758//
759// This function provides a default implementation that works for most
760// unix variants. Any Process subclasses that need to do shared library
761// loading differently should override LoadImage and UnloadImage and
762// do what is needed.
763//----------------------------------------------------------------------
764Error
765Process::UnloadImage (uint32_t image_token)
766{
767 Error error;
768 if (image_token < m_image_tokens.size())
769 {
770 const addr_t image_addr = m_image_tokens[image_token];
771 if (image_addr == LLDB_INVALID_ADDRESS)
772 {
773 error.SetErrorString("image already unloaded");
774 }
775 else
776 {
777 DynamicLoader *loader = GetDynamicLoader();
778 if (loader)
779 error = loader->CanLoadImage();
780
781 if (error.Success())
782 {
783 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
784 if (thread_sp == NULL)
785 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
786
787 if (thread_sp)
788 {
789 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
790
791 if (frame_sp)
792 {
793 ExecutionContext exe_ctx;
794 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000795 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000796 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000797 StreamString expr;
798 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
799 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000800 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000801 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000802 if (result_valobj_sp->GetError().Success())
803 {
804 Scalar scalar;
805 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
806 {
807 if (scalar.UInt(1))
808 {
809 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
810 }
811 else
812 {
813 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
814 }
815 }
816 }
817 else
818 {
819 error = result_valobj_sp->GetError();
820 }
821 }
822 }
823 }
824 }
825 }
826 else
827 {
828 error.SetErrorString("invalid image token");
829 }
830 return error;
831}
832
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000833DynamicLoader *
834Process::GetDynamicLoader()
835{
836 return NULL;
837}
838
839const ABI *
840Process::GetABI()
841{
842 ConstString& triple = m_target_triple;
843
844 if (triple.IsEmpty())
845 return NULL;
846
847 if (m_abi_sp.get() == NULL)
848 {
849 m_abi_sp.reset(ABI::FindPlugin(triple));
850 }
851
852 return m_abi_sp.get();
853}
854
Jim Ingham22777012010-09-23 02:01:19 +0000855LanguageRuntime *
856Process::GetLanguageRuntime(lldb::LanguageType language)
857{
858 LanguageRuntimeCollection::iterator pos;
859 pos = m_language_runtimes.find (language);
860 if (pos == m_language_runtimes.end())
861 {
862 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
863
864 m_language_runtimes[language]
865 = runtime;
866 return runtime.get();
867 }
868 else
869 return (*pos).second.get();
870}
871
872CPPLanguageRuntime *
873Process::GetCPPLanguageRuntime ()
874{
875 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
876 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
877 return static_cast<CPPLanguageRuntime *> (runtime);
878 return NULL;
879}
880
881ObjCLanguageRuntime *
882Process::GetObjCLanguageRuntime ()
883{
884 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
885 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
886 return static_cast<ObjCLanguageRuntime *> (runtime);
887 return NULL;
888}
889
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000890BreakpointSiteList &
891Process::GetBreakpointSiteList()
892{
893 return m_breakpoint_site_list;
894}
895
896const BreakpointSiteList &
897Process::GetBreakpointSiteList() const
898{
899 return m_breakpoint_site_list;
900}
901
902
903void
904Process::DisableAllBreakpointSites ()
905{
906 m_breakpoint_site_list.SetEnabledForAll (false);
907}
908
909Error
910Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
911{
912 Error error (DisableBreakpointSiteByID (break_id));
913
914 if (error.Success())
915 m_breakpoint_site_list.Remove(break_id);
916
917 return error;
918}
919
920Error
921Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
922{
923 Error error;
924 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
925 if (bp_site_sp)
926 {
927 if (bp_site_sp->IsEnabled())
928 error = DisableBreakpoint (bp_site_sp.get());
929 }
930 else
931 {
932 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
933 }
934
935 return error;
936}
937
938Error
939Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
940{
941 Error error;
942 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
943 if (bp_site_sp)
944 {
945 if (!bp_site_sp->IsEnabled())
946 error = EnableBreakpoint (bp_site_sp.get());
947 }
948 else
949 {
950 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
951 }
952 return error;
953}
954
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000955lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
957{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000958 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959 if (load_addr != LLDB_INVALID_ADDRESS)
960 {
961 BreakpointSiteSP bp_site_sp;
962
963 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
964 // create a new breakpoint site and add it.
965
966 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
967
968 if (bp_site_sp)
969 {
970 bp_site_sp->AddOwner (owner);
971 owner->SetBreakpointSite (bp_site_sp);
972 return bp_site_sp->GetID();
973 }
974 else
975 {
976 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
977 if (bp_site_sp)
978 {
979 if (EnableBreakpoint (bp_site_sp.get()).Success())
980 {
981 owner->SetBreakpointSite (bp_site_sp);
982 return m_breakpoint_site_list.Add (bp_site_sp);
983 }
984 }
985 }
986 }
987 // We failed to enable the breakpoint
988 return LLDB_INVALID_BREAK_ID;
989
990}
991
992void
993Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
994{
995 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
996 if (num_owners == 0)
997 {
998 DisableBreakpoint(bp_site_sp.get());
999 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1000 }
1001}
1002
1003
1004size_t
1005Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1006{
1007 size_t bytes_removed = 0;
1008 addr_t intersect_addr;
1009 size_t intersect_size;
1010 size_t opcode_offset;
1011 size_t idx;
1012 BreakpointSiteSP bp;
1013
1014 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1015 {
1016 if (bp->GetType() == BreakpointSite::eSoftware)
1017 {
1018 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1019 {
1020 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1021 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1022 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1023 size_t buf_offset = intersect_addr - bp_addr;
1024 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1025 }
1026 }
1027 }
1028 return bytes_removed;
1029}
1030
1031
1032Error
1033Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1034{
1035 Error error;
1036 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001037 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038 const addr_t bp_addr = bp_site->GetLoadAddress();
1039 if (log)
1040 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1041 if (bp_site->IsEnabled())
1042 {
1043 if (log)
1044 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1045 return error;
1046 }
1047
1048 if (bp_addr == LLDB_INVALID_ADDRESS)
1049 {
1050 error.SetErrorString("BreakpointSite contains an invalid load address.");
1051 return error;
1052 }
1053 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1054 // trap for the breakpoint site
1055 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1056
1057 if (bp_opcode_size == 0)
1058 {
1059 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1060 }
1061 else
1062 {
1063 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1064
1065 if (bp_opcode_bytes == NULL)
1066 {
1067 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1068 return error;
1069 }
1070
1071 // Save the original opcode by reading it
1072 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1073 {
1074 // Write a software breakpoint in place of the original opcode
1075 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1076 {
1077 uint8_t verify_bp_opcode_bytes[64];
1078 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1079 {
1080 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1081 {
1082 bp_site->SetEnabled(true);
1083 bp_site->SetType (BreakpointSite::eSoftware);
1084 if (log)
1085 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1086 bp_site->GetID(),
1087 (uint64_t)bp_addr);
1088 }
1089 else
1090 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1091 }
1092 else
1093 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1094 }
1095 else
1096 error.SetErrorString("Unable to write breakpoint trap to memory.");
1097 }
1098 else
1099 error.SetErrorString("Unable to read memory at breakpoint address.");
1100 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001101 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1103 bp_site->GetID(),
1104 (uint64_t)bp_addr,
1105 error.AsCString());
1106 return error;
1107}
1108
1109Error
1110Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1111{
1112 Error error;
1113 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001114 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 addr_t bp_addr = bp_site->GetLoadAddress();
1116 lldb::user_id_t breakID = bp_site->GetID();
1117 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001118 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119
1120 if (bp_site->IsHardware())
1121 {
1122 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1123 }
1124 else if (bp_site->IsEnabled())
1125 {
1126 const size_t break_op_size = bp_site->GetByteSize();
1127 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1128 if (break_op_size > 0)
1129 {
1130 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001131 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001132 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133 bool break_op_found = false;
1134
1135 // Read the breakpoint opcode
1136 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1137 {
1138 bool verify = false;
1139 // Make sure we have the a breakpoint opcode exists at this address
1140 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1141 {
1142 break_op_found = true;
1143 // We found a valid breakpoint opcode at this address, now restore
1144 // the saved opcode.
1145 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1146 {
1147 verify = true;
1148 }
1149 else
1150 error.SetErrorString("Memory write failed when restoring original opcode.");
1151 }
1152 else
1153 {
1154 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1155 // Set verify to true and so we can check if the original opcode has already been restored
1156 verify = true;
1157 }
1158
1159 if (verify)
1160 {
Greg Claytonc982c762010-07-09 20:39:50 +00001161 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001162 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 // Verify that our original opcode made it back to the inferior
1164 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1165 {
1166 // compare the memory we just read with the original opcode
1167 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1168 {
1169 // SUCCESS
1170 bp_site->SetEnabled(false);
1171 if (log)
1172 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1173 return error;
1174 }
1175 else
1176 {
1177 if (break_op_found)
1178 error.SetErrorString("Failed to restore original opcode.");
1179 }
1180 }
1181 else
1182 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1183 }
1184 }
1185 else
1186 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1187 }
1188 }
1189 else
1190 {
1191 if (log)
1192 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1193 return error;
1194 }
1195
1196 if (log)
1197 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1198 bp_site->GetID(),
1199 (uint64_t)bp_addr,
1200 error.AsCString());
1201 return error;
1202
1203}
1204
Greg Clayton58be07b2011-01-07 06:08:19 +00001205// Comment out line below to disable memory caching
1206#define ENABLE_MEMORY_CACHING
1207// Uncomment to verify memory caching works after making changes to caching code
1208//#define VERIFY_MEMORY_READS
1209
1210#if defined (ENABLE_MEMORY_CACHING)
1211
1212#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213
1214size_t
1215Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1216{
Greg Clayton58be07b2011-01-07 06:08:19 +00001217 // Memory caching is enabled, with debug verification
1218 if (buf && size)
1219 {
1220 // Uncomment the line below to make sure memory caching is working.
1221 // I ran this through the test suite and got no assertions, so I am
1222 // pretty confident this is working well. If any changes are made to
1223 // memory caching, uncomment the line below and test your changes!
1224
1225 // Verify all memory reads by using the cache first, then redundantly
1226 // reading the same memory from the inferior and comparing to make sure
1227 // everything is exactly the same.
1228 std::string verify_buf (size, '\0');
1229 assert (verify_buf.size() == size);
1230 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1231 Error verify_error;
1232 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1233 assert (cache_bytes_read == verify_bytes_read);
1234 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1235 assert (verify_error.Success() == error.Success());
1236 return cache_bytes_read;
1237 }
1238 return 0;
1239}
1240
1241#else // #if defined (VERIFY_MEMORY_READS)
1242
1243size_t
1244Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1245{
1246 // Memory caching enabled, no verification
1247 return m_memory_cache.Read (this, addr, buf, size, error);
1248}
1249
1250#endif // #else for #if defined (VERIFY_MEMORY_READS)
1251
1252#else // #if defined (ENABLE_MEMORY_CACHING)
1253
1254size_t
1255Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1256{
1257 // Memory caching is disabled
1258 return ReadMemoryFromInferior (addr, buf, size, error);
1259}
1260
1261#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1262
1263
1264size_t
1265Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1266{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267 if (buf == NULL || size == 0)
1268 return 0;
1269
1270 size_t bytes_read = 0;
1271 uint8_t *bytes = (uint8_t *)buf;
1272
1273 while (bytes_read < size)
1274 {
1275 const size_t curr_size = size - bytes_read;
1276 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1277 bytes + bytes_read,
1278 curr_size,
1279 error);
1280 bytes_read += curr_bytes_read;
1281 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1282 break;
1283 }
1284
1285 // Replace any software breakpoint opcodes that fall into this range back
1286 // into "buf" before we return
1287 if (bytes_read > 0)
1288 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1289 return bytes_read;
1290}
1291
Greg Clayton58a4c462010-12-16 20:01:20 +00001292uint64_t
1293Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1294{
1295 if (integer_byte_size > sizeof(uint64_t))
1296 {
1297 error.SetErrorString ("unsupported integer size");
1298 }
1299 else
1300 {
1301 uint8_t tmp[sizeof(uint64_t)];
1302 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1303 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1304 {
1305 uint32_t offset = 0;
1306 return data.GetMaxU64 (&offset, integer_byte_size);
1307 }
1308 }
1309 // Any plug-in that doesn't return success a memory read with the number
1310 // of bytes that were requested should be setting the error
1311 assert (error.Fail());
1312 return 0;
1313}
1314
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315size_t
1316Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1317{
1318 size_t bytes_written = 0;
1319 const uint8_t *bytes = (const uint8_t *)buf;
1320
1321 while (bytes_written < size)
1322 {
1323 const size_t curr_size = size - bytes_written;
1324 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1325 bytes + bytes_written,
1326 curr_size,
1327 error);
1328 bytes_written += curr_bytes_written;
1329 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1330 break;
1331 }
1332 return bytes_written;
1333}
1334
1335size_t
1336Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1337{
Greg Clayton58be07b2011-01-07 06:08:19 +00001338#if defined (ENABLE_MEMORY_CACHING)
1339 m_memory_cache.Flush (addr, size);
1340#endif
1341
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 if (buf == NULL || size == 0)
1343 return 0;
1344 // We need to write any data that would go where any current software traps
1345 // (enabled software breakpoints) any software traps (breakpoints) that we
1346 // may have placed in our tasks memory.
1347
1348 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1349 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1350
1351 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1352 return DoWriteMemory(addr, buf, size, error);
1353
1354 BreakpointSiteList::collection::const_iterator pos;
1355 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001356 addr_t intersect_addr = 0;
1357 size_t intersect_size = 0;
1358 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359 const uint8_t *ubuf = (const uint8_t *)buf;
1360
1361 for (pos = iter; pos != end; ++pos)
1362 {
1363 BreakpointSiteSP bp;
1364 bp = pos->second;
1365
1366 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1367 assert(addr <= intersect_addr && intersect_addr < addr + size);
1368 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1369 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1370
1371 // Check for bytes before this breakpoint
1372 const addr_t curr_addr = addr + bytes_written;
1373 if (intersect_addr > curr_addr)
1374 {
1375 // There are some bytes before this breakpoint that we need to
1376 // just write to memory
1377 size_t curr_size = intersect_addr - curr_addr;
1378 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1379 ubuf + bytes_written,
1380 curr_size,
1381 error);
1382 bytes_written += curr_bytes_written;
1383 if (curr_bytes_written != curr_size)
1384 {
1385 // We weren't able to write all of the requested bytes, we
1386 // are done looping and will return the number of bytes that
1387 // we have written so far.
1388 break;
1389 }
1390 }
1391
1392 // Now write any bytes that would cover up any software breakpoints
1393 // directly into the breakpoint opcode buffer
1394 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1395 bytes_written += intersect_size;
1396 }
1397
1398 // Write any remaining bytes after the last breakpoint if we have any left
1399 if (bytes_written < size)
1400 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1401 ubuf + bytes_written,
1402 size - bytes_written,
1403 error);
1404
1405 return bytes_written;
1406}
1407
1408addr_t
1409Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1410{
1411 // Fixme: we should track the blocks we've allocated, and clean them up...
1412 // We could even do our own allocator here if that ends up being more efficient.
Greg Claytonb2daec92011-01-23 19:58:49 +00001413 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1414 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1415 if (log)
Greg Clayton2ad66702011-01-24 06:30:45 +00001416 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001417 size,
1418 permissions & ePermissionsReadable ? 'r' : '-',
1419 permissions & ePermissionsWritable ? 'w' : '-',
1420 permissions & ePermissionsExecutable ? 'x' : '-',
1421 (uint64_t)allocated_addr,
1422 m_stop_id);
1423 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424}
1425
1426Error
1427Process::DeallocateMemory (addr_t ptr)
1428{
Greg Claytonb2daec92011-01-23 19:58:49 +00001429 Error error(DoDeallocateMemory (ptr));
1430
1431 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1432 if (log)
1433 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1434 ptr,
1435 error.AsCString("SUCCESS"),
1436 m_stop_id);
1437 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001438}
1439
1440
1441Error
1442Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1443{
1444 Error error;
1445 error.SetErrorString("watchpoints are not supported");
1446 return error;
1447}
1448
1449Error
1450Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1451{
1452 Error error;
1453 error.SetErrorString("watchpoints are not supported");
1454 return error;
1455}
1456
1457StateType
1458Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1459{
1460 StateType state;
1461 // Now wait for the process to launch and return control to us, and then
1462 // call DidLaunch:
1463 while (1)
1464 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001465 event_sp.reset();
1466 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1467
1468 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00001470
1471 // If state is invalid, then we timed out
1472 if (state == eStateInvalid)
1473 break;
1474
1475 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476 HandlePrivateEvent (event_sp);
1477 }
1478 return state;
1479}
1480
1481Error
1482Process::Launch
1483(
1484 char const *argv[],
1485 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001486 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 const char *stdin_path,
1488 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001489 const char *stderr_path,
1490 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001491)
1492{
1493 Error error;
1494 m_target_triple.Clear();
1495 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001496 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497
1498 Module *exe_module = m_target.GetExecutableModule().get();
1499 if (exe_module)
1500 {
1501 char exec_file_path[PATH_MAX];
1502 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1503 if (exe_module->GetFileSpec().Exists())
1504 {
1505 error = WillLaunch (exe_module);
1506 if (error.Success())
1507 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001508 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509 // The args coming in should not contain the application name, the
1510 // lldb_private::Process class will add this in case the executable
1511 // gets resolved to a different file than was given on the command
1512 // line (like when an applicaiton bundle is specified and will
1513 // resolve to the contained exectuable file, or the file given was
1514 // a symlink or other file system link that resolves to a different
1515 // file).
1516
1517 // Get the resolved exectuable path
1518
1519 // Make a new argument vector
1520 std::vector<const char *> exec_path_plus_argv;
1521 // Append the resolved executable path
1522 exec_path_plus_argv.push_back (exec_file_path);
1523
1524 // Push all args if there are any
1525 if (argv)
1526 {
1527 for (int i = 0; argv[i]; ++i)
1528 exec_path_plus_argv.push_back(argv[i]);
1529 }
1530
1531 // Push a NULL to terminate the args.
1532 exec_path_plus_argv.push_back(NULL);
1533
1534 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001535 error = DoLaunch (exe_module,
1536 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1537 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001538 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001539 stdin_path,
1540 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001541 stderr_path,
1542 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001543
1544 if (error.Fail())
1545 {
1546 if (GetID() != LLDB_INVALID_PROCESS_ID)
1547 {
1548 SetID (LLDB_INVALID_PROCESS_ID);
1549 const char *error_string = error.AsCString();
1550 if (error_string == NULL)
1551 error_string = "launch failed";
1552 SetExitStatus (-1, error_string);
1553 }
1554 }
1555 else
1556 {
1557 EventSP event_sp;
1558 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1559
1560 if (state == eStateStopped || state == eStateCrashed)
1561 {
1562 DidLaunch ();
1563
1564 // This delays passing the stopped event to listeners till DidLaunch gets
1565 // a chance to complete...
1566 HandlePrivateEvent (event_sp);
1567 StartPrivateStateThread ();
1568 }
1569 else if (state == eStateExited)
1570 {
1571 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1572 // not likely to work, and return an invalid pid.
1573 HandlePrivateEvent (event_sp);
1574 }
1575 }
1576 }
1577 }
1578 else
1579 {
1580 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1581 }
1582 }
1583 return error;
1584}
1585
1586Error
1587Process::CompleteAttach ()
1588{
1589 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001590
1591 if (GetID() == LLDB_INVALID_PROCESS_ID)
1592 {
1593 error.SetErrorString("no process");
1594 }
1595
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001596 EventSP event_sp;
1597 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1598 if (state == eStateStopped || state == eStateCrashed)
1599 {
1600 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001601 // Figure out which one is the executable, and set that in our target:
1602 ModuleList &modules = GetTarget().GetImages();
1603
1604 size_t num_modules = modules.GetSize();
1605 for (int i = 0; i < num_modules; i++)
1606 {
1607 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1608 if (module_sp->IsExecutable())
1609 {
1610 ModuleSP exec_module = GetTarget().GetExecutableModule();
1611 if (!exec_module || exec_module != module_sp)
1612 {
1613
1614 GetTarget().SetExecutableModule (module_sp, false);
1615 }
1616 break;
1617 }
1618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001619
1620 // This delays passing the stopped event to listeners till DidLaunch gets
1621 // a chance to complete...
1622 HandlePrivateEvent(event_sp);
1623 StartPrivateStateThread();
1624 }
1625 else
1626 {
1627 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1628 // not likely to work, and return an invalid pid.
1629 if (state == eStateExited)
1630 HandlePrivateEvent (event_sp);
1631 error.SetErrorStringWithFormat("invalid state after attach: %s",
1632 lldb_private::StateAsCString(state));
1633 }
1634 return error;
1635}
1636
1637Error
1638Process::Attach (lldb::pid_t attach_pid)
1639{
1640
1641 m_target_triple.Clear();
1642 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001643 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001644
Jim Ingham5aee1622010-08-09 23:31:02 +00001645 // Find the process and its architecture. Make sure it matches the architecture
1646 // of the current Target, and if not adjust it.
1647
1648 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1649 if (attach_spec != GetTarget().GetArchitecture())
1650 {
1651 // Set the architecture on the target.
1652 GetTarget().SetArchitecture(attach_spec);
1653 }
1654
Greg Claytonc982c762010-07-09 20:39:50 +00001655 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001656 if (error.Success())
1657 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001658 SetPublicState (eStateAttaching);
1659
Greg Claytonc982c762010-07-09 20:39:50 +00001660 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 if (error.Success())
1662 {
1663 error = CompleteAttach();
1664 }
1665 else
1666 {
1667 if (GetID() != LLDB_INVALID_PROCESS_ID)
1668 {
1669 SetID (LLDB_INVALID_PROCESS_ID);
1670 const char *error_string = error.AsCString();
1671 if (error_string == NULL)
1672 error_string = "attach failed";
1673
1674 SetExitStatus(-1, error_string);
1675 }
1676 }
1677 }
1678 return error;
1679}
1680
1681Error
1682Process::Attach (const char *process_name, bool wait_for_launch)
1683{
1684 m_target_triple.Clear();
1685 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001686 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001687
1688 // Find the process and its architecture. Make sure it matches the architecture
1689 // of the current Target, and if not adjust it.
1690
Jim Ingham2ecb7422010-08-17 21:54:19 +00001691 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001692 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001693 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001694 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001695 {
1696 // Set the architecture on the target.
1697 GetTarget().SetArchitecture(attach_spec);
1698 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001699 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001700
Greg Claytonc982c762010-07-09 20:39:50 +00001701 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001702 if (error.Success())
1703 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001704 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001705 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706 if (error.Fail())
1707 {
1708 if (GetID() != LLDB_INVALID_PROCESS_ID)
1709 {
1710 SetID (LLDB_INVALID_PROCESS_ID);
1711 const char *error_string = error.AsCString();
1712 if (error_string == NULL)
1713 error_string = "attach failed";
1714
1715 SetExitStatus(-1, error_string);
1716 }
1717 }
1718 else
1719 {
1720 error = CompleteAttach();
1721 }
1722 }
1723 return error;
1724}
1725
1726Error
1727Process::Resume ()
1728{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001729 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001730 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00001731 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1732 m_stop_id,
1733 StateAsCString(m_public_state.GetValue()),
1734 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001735
1736 Error error (WillResume());
1737 // Tell the process it is about to resume before the thread list
1738 if (error.Success())
1739 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001740 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741 // can let all of our threads know that they are about to be
1742 // resumed. Threads will each be called with
1743 // Thread::WillResume(StateType) where StateType contains the state
1744 // that they are supposed to have when the process is resumed
1745 // (suspended/running/stepping). Threads should also check
1746 // their resume signal in lldb::Thread::GetResumeSignal()
1747 // to see if they are suppoed to start back up with a signal.
1748 if (m_thread_list.WillResume())
1749 {
1750 error = DoResume();
1751 if (error.Success())
1752 {
1753 DidResume();
1754 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00001755 if (log)
1756 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001757 }
1758 }
1759 else
1760 {
Jim Ingham444586b2011-01-24 06:34:17 +00001761 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762 }
1763 }
Jim Ingham444586b2011-01-24 06:34:17 +00001764 else if (log)
1765 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001766 return error;
1767}
1768
1769Error
1770Process::Halt ()
1771{
1772 Error error (WillHalt());
1773
1774 if (error.Success())
1775 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001776
1777 bool caused_stop = false;
1778 EventSP event_sp;
1779
1780 // Pause our private state thread so we can ensure no one else eats
1781 // the stop event out from under us.
1782 PausePrivateStateThread();
1783
1784 // Ask the process subclass to actually halt our process
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001785 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001786 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001787 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001788 // If "caused_stop" is true, then DoHalt stopped the process. If
1789 // "caused_stop" is false, the process was already stopped.
1790 // If the DoHalt caused the process to stop, then we want to catch
1791 // this event and set the interrupted bool to true before we pass
1792 // this along so clients know that the process was interrupted by
1793 // a halt command.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001794 if (caused_stop)
1795 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001796 // Wait for 2 seconds for the process to stop.
1797 TimeValue timeout_time;
1798 timeout_time = TimeValue::Now();
Greg Clayton6779606a2011-01-22 23:43:18 +00001799 timeout_time.OffsetWithSeconds(1);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001800 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1801
1802 if (state == eStateInvalid)
1803 {
1804 // We timeout out and didn't get a stop event...
1805 error.SetErrorString ("Halt timed out.");
1806 }
1807 else
1808 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001809 if (StateIsStoppedState (state))
1810 {
1811 // We caused the process to interrupt itself, so mark this
1812 // as such in the stop event so clients can tell an interrupted
1813 // process from a natural stop
1814 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1815 }
1816 else
1817 {
1818 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1819 if (log)
1820 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1821 error.SetErrorString ("Did not get stopped event after halt.");
1822 }
1823 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001824 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001825 DidHalt();
1826
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001827 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001828 // Resume our private state thread before we post the event (if any)
1829 ResumePrivateStateThread();
1830
1831 // Post any event we might have consumed. If all goes well, we will have
1832 // stopped the process, intercepted the event and set the interrupted
Jim Inghamf48169b2010-11-30 02:22:11 +00001833 // bool in the event. Post it to the private event queue and that will end up
1834 // correctly setting the state.
Greg Clayton3af9ea52010-11-18 05:57:03 +00001835 if (event_sp)
Caroline Ticeefed6132010-11-19 20:47:54 +00001836 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001837
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838 }
1839 return error;
1840}
1841
1842Error
1843Process::Detach ()
1844{
1845 Error error (WillDetach());
1846
1847 if (error.Success())
1848 {
1849 DisableAllBreakpointSites();
1850 error = DoDetach();
1851 if (error.Success())
1852 {
1853 DidDetach();
1854 StopPrivateStateThread();
1855 }
1856 }
1857 return error;
1858}
1859
1860Error
1861Process::Destroy ()
1862{
1863 Error error (WillDestroy());
1864 if (error.Success())
1865 {
1866 DisableAllBreakpointSites();
1867 error = DoDestroy();
1868 if (error.Success())
1869 {
1870 DidDestroy();
1871 StopPrivateStateThread();
1872 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001873 m_stdio_communication.StopReadThread();
1874 m_stdio_communication.Disconnect();
1875 if (m_process_input_reader && m_process_input_reader->IsActive())
1876 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1877 if (m_process_input_reader)
1878 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001879 }
1880 return error;
1881}
1882
1883Error
1884Process::Signal (int signal)
1885{
1886 Error error (WillSignal());
1887 if (error.Success())
1888 {
1889 error = DoSignal(signal);
1890 if (error.Success())
1891 DidSignal();
1892 }
1893 return error;
1894}
1895
1896UnixSignals &
1897Process::GetUnixSignals ()
1898{
1899 return m_unix_signals;
1900}
1901
1902Target &
1903Process::GetTarget ()
1904{
1905 return m_target;
1906}
1907
1908const Target &
1909Process::GetTarget () const
1910{
1911 return m_target;
1912}
1913
1914uint32_t
1915Process::GetAddressByteSize()
1916{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001917 if (m_addr_byte_size == 0)
1918 return m_target.GetArchitecture().GetAddressByteSize();
1919 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920}
1921
1922bool
1923Process::ShouldBroadcastEvent (Event *event_ptr)
1924{
1925 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1926 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001927 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928
1929 switch (state)
1930 {
1931 case eStateAttaching:
1932 case eStateLaunching:
1933 case eStateDetached:
1934 case eStateExited:
1935 case eStateUnloaded:
1936 // These events indicate changes in the state of the debugging session, always report them.
1937 return_value = true;
1938 break;
1939 case eStateInvalid:
1940 // We stopped for no apparent reason, don't report it.
1941 return_value = false;
1942 break;
1943 case eStateRunning:
1944 case eStateStepping:
1945 // If we've started the target running, we handle the cases where we
1946 // are already running and where there is a transition from stopped to
1947 // running differently.
1948 // running -> running: Automatically suppress extra running events
1949 // stopped -> running: Report except when there is one or more no votes
1950 // and no yes votes.
1951 SynchronouslyNotifyStateChanged (state);
1952 switch (m_public_state.GetValue())
1953 {
1954 case eStateRunning:
1955 case eStateStepping:
1956 // We always suppress multiple runnings with no PUBLIC stop in between.
1957 return_value = false;
1958 break;
1959 default:
1960 // TODO: make this work correctly. For now always report
1961 // run if we aren't running so we don't miss any runnning
1962 // events. If I run the lldb/test/thread/a.out file and
1963 // break at main.cpp:58, run and hit the breakpoints on
1964 // multiple threads, then somehow during the stepping over
1965 // of all breakpoints no run gets reported.
1966 return_value = true;
1967
1968 // This is a transition from stop to run.
1969 switch (m_thread_list.ShouldReportRun (event_ptr))
1970 {
1971 case eVoteYes:
1972 case eVoteNoOpinion:
1973 return_value = true;
1974 break;
1975 case eVoteNo:
1976 return_value = false;
1977 break;
1978 }
1979 break;
1980 }
1981 break;
1982 case eStateStopped:
1983 case eStateCrashed:
1984 case eStateSuspended:
1985 {
1986 // We've stopped. First see if we're going to restart the target.
1987 // If we are going to stop, then we always broadcast the event.
1988 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00001989 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001990 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001991 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001992 if (log)
1993 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001994 return true;
1995 }
1996 else
1997 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001998 RefreshStateAfterStop ();
1999
2000 if (m_thread_list.ShouldStop (event_ptr) == false)
2001 {
2002 switch (m_thread_list.ShouldReportStop (event_ptr))
2003 {
2004 case eVoteYes:
2005 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002006 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002008 case eVoteNo:
2009 return_value = false;
2010 break;
2011 }
2012
2013 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002014 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002015 Resume ();
2016 }
2017 else
2018 {
2019 return_value = true;
2020 SynchronouslyNotifyStateChanged (state);
2021 }
2022 }
2023 }
2024 }
2025
2026 if (log)
2027 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2028 return return_value;
2029}
2030
2031//------------------------------------------------------------------
2032// Thread Queries
2033//------------------------------------------------------------------
2034
2035ThreadList &
2036Process::GetThreadList ()
2037{
2038 return m_thread_list;
2039}
2040
2041const ThreadList &
2042Process::GetThreadList () const
2043{
2044 return m_thread_list;
2045}
2046
2047
2048bool
2049Process::StartPrivateStateThread ()
2050{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002051 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002052
2053 if (log)
2054 log->Printf ("Process::%s ( )", __FUNCTION__);
2055
2056 // Create a thread that watches our internal state and controls which
2057 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002058 char thread_name[1024];
2059 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2060 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2062}
2063
2064void
2065Process::PausePrivateStateThread ()
2066{
2067 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2068}
2069
2070void
2071Process::ResumePrivateStateThread ()
2072{
2073 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2074}
2075
2076void
2077Process::StopPrivateStateThread ()
2078{
2079 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2080}
2081
2082void
2083Process::ControlPrivateStateThread (uint32_t signal)
2084{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002085 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002086
2087 assert (signal == eBroadcastInternalStateControlStop ||
2088 signal == eBroadcastInternalStateControlPause ||
2089 signal == eBroadcastInternalStateControlResume);
2090
2091 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002092 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002094 // Signal the private state thread. First we should copy this is case the
2095 // thread starts exiting since the private state thread will NULL this out
2096 // when it exits
2097 const lldb::thread_t private_state_thread = m_private_state_thread;
2098 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002099 {
2100 TimeValue timeout_time;
2101 bool timed_out;
2102
2103 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2104
2105 timeout_time = TimeValue::Now();
2106 timeout_time.OffsetWithSeconds(2);
2107 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2108 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2109
2110 if (signal == eBroadcastInternalStateControlStop)
2111 {
2112 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002113 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002114
2115 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002116 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002117 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118 }
2119 }
2120}
2121
2122void
2123Process::HandlePrivateEvent (EventSP &event_sp)
2124{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002125 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00002126 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 // See if we should broadcast this state to external clients?
2128 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129
2130 if (should_broadcast)
2131 {
2132 if (log)
2133 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002134 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2135 __FUNCTION__,
2136 GetID(),
2137 StateAsCString(new_state),
2138 StateAsCString (GetState ()),
2139 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002140 }
Greg Clayton414f5d32011-01-25 02:58:48 +00002141 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002142 PushProcessInputReader ();
2143 else
2144 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2146 BroadcastEvent (event_sp);
2147 }
2148 else
2149 {
2150 if (log)
2151 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002152 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2153 __FUNCTION__,
2154 GetID(),
2155 StateAsCString(new_state),
2156 StateAsCString (GetState ()),
2157 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158 }
2159 }
2160}
2161
2162void *
2163Process::PrivateStateThread (void *arg)
2164{
2165 Process *proc = static_cast<Process*> (arg);
2166 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 return result;
2168}
2169
2170void *
2171Process::RunPrivateStateThread ()
2172{
2173 bool control_only = false;
2174 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2175
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002176 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177 if (log)
2178 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2179
2180 bool exit_now = false;
2181 while (!exit_now)
2182 {
2183 EventSP event_sp;
2184 WaitForEventsPrivate (NULL, event_sp, control_only);
2185 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2186 {
2187 switch (event_sp->GetType())
2188 {
2189 case eBroadcastInternalStateControlStop:
2190 exit_now = true;
2191 continue; // Go to next loop iteration so we exit without
2192 break; // doing any internal state managment below
2193
2194 case eBroadcastInternalStateControlPause:
2195 control_only = true;
2196 break;
2197
2198 case eBroadcastInternalStateControlResume:
2199 control_only = false;
2200 break;
2201 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002202
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002203 if (log)
2204 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2205
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002207 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002208 }
2209
2210
2211 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2212
2213 if (internal_state != eStateInvalid)
2214 {
2215 HandlePrivateEvent (event_sp);
2216 }
2217
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002218 if (internal_state == eStateInvalid ||
2219 internal_state == eStateExited ||
2220 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002221 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002222 if (log)
2223 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2224
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002226 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227 }
2228
Caroline Tice20ad3c42010-10-29 21:48:37 +00002229 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 if (log)
2231 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2232
Greg Clayton6ed95942011-01-22 07:12:45 +00002233 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2234 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235 return NULL;
2236}
2237
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238//------------------------------------------------------------------
2239// Process Event Data
2240//------------------------------------------------------------------
2241
2242Process::ProcessEventData::ProcessEventData () :
2243 EventData (),
2244 m_process_sp (),
2245 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002246 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002247 m_update_state (false),
2248 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249{
2250}
2251
2252Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2253 EventData (),
2254 m_process_sp (process_sp),
2255 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002256 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002257 m_update_state (false),
2258 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002259{
2260}
2261
2262Process::ProcessEventData::~ProcessEventData()
2263{
2264}
2265
2266const ConstString &
2267Process::ProcessEventData::GetFlavorString ()
2268{
2269 static ConstString g_flavor ("Process::ProcessEventData");
2270 return g_flavor;
2271}
2272
2273const ConstString &
2274Process::ProcessEventData::GetFlavor () const
2275{
2276 return ProcessEventData::GetFlavorString ();
2277}
2278
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279void
2280Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2281{
2282 // This function gets called twice for each event, once when the event gets pulled
2283 // off of the private process event queue, and once when it gets pulled off of
2284 // the public event queue. m_update_state is used to distinguish these
2285 // two cases; it is false when we're just pulling it off for private handling,
2286 // and we don't want to do the breakpoint command handling then.
2287
2288 if (!m_update_state)
2289 return;
2290
2291 m_process_sp->SetPublicState (m_state);
2292
2293 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2294 if (m_state == eStateStopped && ! m_restarted)
2295 {
2296 int num_threads = m_process_sp->GetThreadList().GetSize();
2297 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002298
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 for (idx = 0; idx < num_threads; ++idx)
2300 {
2301 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2302
Jim Inghamb15bfc72010-10-20 00:39:53 +00002303 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2304 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002306 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 }
2308 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002309
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002310 // The stop action might restart the target. If it does, then we want to mark that in the
2311 // event so that whoever is receiving it will know to wait for the running event and reflect
2312 // that state appropriately.
2313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 if (m_process_sp->GetPrivateState() == eStateRunning)
2315 SetRestarted(true);
2316 }
2317}
2318
2319void
2320Process::ProcessEventData::Dump (Stream *s) const
2321{
2322 if (m_process_sp)
2323 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2324
2325 s->Printf("state = %s", StateAsCString(GetState()));;
2326}
2327
2328const Process::ProcessEventData *
2329Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2330{
2331 if (event_ptr)
2332 {
2333 const EventData *event_data = event_ptr->GetData();
2334 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2335 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2336 }
2337 return NULL;
2338}
2339
2340ProcessSP
2341Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2342{
2343 ProcessSP process_sp;
2344 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2345 if (data)
2346 process_sp = data->GetProcessSP();
2347 return process_sp;
2348}
2349
2350StateType
2351Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2352{
2353 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2354 if (data == NULL)
2355 return eStateInvalid;
2356 else
2357 return data->GetState();
2358}
2359
2360bool
2361Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2362{
2363 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2364 if (data == NULL)
2365 return false;
2366 else
2367 return data->GetRestarted();
2368}
2369
2370void
2371Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2372{
2373 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2374 if (data != NULL)
2375 data->SetRestarted(new_value);
2376}
2377
2378bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002379Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2380{
2381 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2382 if (data == NULL)
2383 return false;
2384 else
2385 return data->GetInterrupted ();
2386}
2387
2388void
2389Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2390{
2391 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2392 if (data != NULL)
2393 data->SetInterrupted(new_value);
2394}
2395
2396bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2398{
2399 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2400 if (data)
2401 {
2402 data->SetUpdateStateOnRemoval();
2403 return true;
2404 }
2405 return false;
2406}
2407
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408Target *
2409Process::CalculateTarget ()
2410{
2411 return &m_target;
2412}
2413
2414Process *
2415Process::CalculateProcess ()
2416{
2417 return this;
2418}
2419
2420Thread *
2421Process::CalculateThread ()
2422{
2423 return NULL;
2424}
2425
2426StackFrame *
2427Process::CalculateStackFrame ()
2428{
2429 return NULL;
2430}
2431
2432void
Greg Clayton0603aa92010-10-04 01:05:56 +00002433Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434{
2435 exe_ctx.target = &m_target;
2436 exe_ctx.process = this;
2437 exe_ctx.thread = NULL;
2438 exe_ctx.frame = NULL;
2439}
2440
2441lldb::ProcessSP
2442Process::GetSP ()
2443{
2444 return GetTarget().GetProcessSP();
2445}
2446
Jim Ingham5aee1622010-08-09 23:31:02 +00002447uint32_t
2448Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2449{
2450 return 0;
2451}
2452
2453ArchSpec
2454Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2455{
2456 return Host::GetArchSpecForExistingProcess (pid);
2457}
2458
2459ArchSpec
2460Process::GetArchSpecForExistingProcess (const char *process_name)
2461{
2462 return Host::GetArchSpecForExistingProcess (process_name);
2463}
2464
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002465void
2466Process::AppendSTDOUT (const char * s, size_t len)
2467{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002468 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002469 m_stdout_data.append (s, len);
2470
Greg Claytona9ff3062010-12-05 19:16:56 +00002471 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002472}
2473
2474void
2475Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2476{
2477 Process *process = (Process *) baton;
2478 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2479}
2480
2481size_t
2482Process::ProcessInputReaderCallback (void *baton,
2483 InputReader &reader,
2484 lldb::InputReaderAction notification,
2485 const char *bytes,
2486 size_t bytes_len)
2487{
2488 Process *process = (Process *) baton;
2489
2490 switch (notification)
2491 {
2492 case eInputReaderActivate:
2493 break;
2494
2495 case eInputReaderDeactivate:
2496 break;
2497
2498 case eInputReaderReactivate:
2499 break;
2500
2501 case eInputReaderGotToken:
2502 {
2503 Error error;
2504 process->PutSTDIN (bytes, bytes_len, error);
2505 }
2506 break;
2507
Caroline Ticeefed6132010-11-19 20:47:54 +00002508 case eInputReaderInterrupt:
2509 process->Halt ();
2510 break;
2511
2512 case eInputReaderEndOfFile:
2513 process->AppendSTDOUT ("^D", 2);
2514 break;
2515
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002516 case eInputReaderDone:
2517 break;
2518
2519 }
2520
2521 return bytes_len;
2522}
2523
2524void
2525Process::ResetProcessInputReader ()
2526{
2527 m_process_input_reader.reset();
2528}
2529
2530void
2531Process::SetUpProcessInputReader (int file_descriptor)
2532{
2533 // First set up the Read Thread for reading/handling process I/O
2534
2535 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2536
2537 if (conn_ap.get())
2538 {
2539 m_stdio_communication.SetConnection (conn_ap.release());
2540 if (m_stdio_communication.IsConnected())
2541 {
2542 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2543 m_stdio_communication.StartReadThread();
2544
2545 // Now read thread is set up, set up input reader.
2546
2547 if (!m_process_input_reader.get())
2548 {
2549 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2550 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2551 this,
2552 eInputReaderGranularityByte,
2553 NULL,
2554 NULL,
2555 false));
2556
2557 if (err.Fail())
2558 m_process_input_reader.reset();
2559 }
2560 }
2561 }
2562}
2563
2564void
2565Process::PushProcessInputReader ()
2566{
2567 if (m_process_input_reader && !m_process_input_reader->IsActive())
2568 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2569}
2570
2571void
2572Process::PopProcessInputReader ()
2573{
2574 if (m_process_input_reader && m_process_input_reader->IsActive())
2575 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2576}
2577
Greg Clayton99d0faf2010-11-18 23:32:35 +00002578
2579void
2580Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002581{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002582 UserSettingsControllerSP &usc = GetSettingsController();
2583 usc.reset (new SettingsController);
2584 UserSettingsController::InitializeSettingsController (usc,
2585 SettingsController::global_settings_table,
2586 SettingsController::instance_settings_table);
2587}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002588
Greg Clayton99d0faf2010-11-18 23:32:35 +00002589void
2590Process::Terminate ()
2591{
2592 UserSettingsControllerSP &usc = GetSettingsController();
2593 UserSettingsController::FinalizeSettingsController (usc);
2594 usc.reset();
2595}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002596
Greg Clayton99d0faf2010-11-18 23:32:35 +00002597UserSettingsControllerSP &
2598Process::GetSettingsController ()
2599{
2600 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002601 return g_settings_controller;
2602}
2603
Caroline Tice1559a462010-09-27 00:30:10 +00002604void
2605Process::UpdateInstanceName ()
2606{
2607 ModuleSP module_sp = GetTarget().GetExecutableModule();
2608 if (module_sp)
2609 {
2610 StreamString sstr;
2611 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2612
Greg Claytondbe54502010-11-19 03:46:01 +00002613 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002614 sstr.GetData());
2615 }
2616}
2617
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002618ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002619Process::RunThreadPlan (ExecutionContext &exe_ctx,
2620 lldb::ThreadPlanSP &thread_plan_sp,
2621 bool stop_others,
2622 bool try_all_threads,
2623 bool discard_on_error,
2624 uint32_t single_thread_timeout_usec,
2625 Stream &errors)
2626{
2627 ExecutionResults return_value = eExecutionSetupError;
2628
Jim Ingham77787032011-01-20 02:03:18 +00002629 if (thread_plan_sp.get() == NULL)
2630 {
2631 errors.Printf("RunThreadPlan called with empty thread plan.");
2632 return lldb::eExecutionSetupError;
2633 }
2634
Jim Ingham444586b2011-01-24 06:34:17 +00002635 if (m_private_state.GetValue() != eStateStopped)
2636 {
2637 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
2638 // REMOVE BEAR TRAP...
2639 // abort();
2640 }
2641
Jim Inghamf48169b2010-11-30 02:22:11 +00002642 // Save this value for restoration of the execution context after we run
2643 uint32_t tid = exe_ctx.thread->GetIndexID();
2644
2645 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2646 // so we should arrange to reset them as well.
2647
2648 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2649 lldb::StackFrameSP selected_frame_sp;
2650
2651 uint32_t selected_tid;
2652 if (selected_thread_sp != NULL)
2653 {
2654 selected_tid = selected_thread_sp->GetIndexID();
2655 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2656 }
2657 else
2658 {
2659 selected_tid = LLDB_INVALID_THREAD_ID;
2660 }
2661
2662 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2663
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002664 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf48169b2010-11-30 02:22:11 +00002665 exe_ctx.process->HijackProcessEvents(&listener);
Jim Ingham444586b2011-01-24 06:34:17 +00002666
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002667 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00002668 if (log)
2669 {
2670 StreamString s;
2671 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton414f5d32011-01-25 02:58:48 +00002672 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".", exe_ctx.thread->GetIndexID(), exe_ctx.thread->GetID(), s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00002673 }
2674
Jim Inghamf48169b2010-11-30 02:22:11 +00002675 Error resume_error = exe_ctx.process->Resume ();
2676 if (!resume_error.Success())
2677 {
2678 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2679 exe_ctx.process->RestoreProcessEvents();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002680 return lldb::eExecutionSetupError;
Jim Inghamf48169b2010-11-30 02:22:11 +00002681 }
2682
2683 // We need to call the function synchronously, so spin waiting for it to return.
2684 // If we get interrupted while executing, we're going to lose our context, and
2685 // won't be able to gather the result at this point.
2686 // We set the timeout AFTER the resume, since the resume takes some time and we
2687 // don't want to charge that to the timeout.
2688
2689 TimeValue* timeout_ptr = NULL;
2690 TimeValue real_timeout;
2691
2692 if (single_thread_timeout_usec != 0)
2693 {
2694 real_timeout = TimeValue::Now();
2695 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2696 timeout_ptr = &real_timeout;
2697 }
2698
Jim Inghamf48169b2010-11-30 02:22:11 +00002699 while (1)
2700 {
2701 lldb::EventSP event_sp;
2702 lldb::StateType stop_state = lldb::eStateInvalid;
2703 // Now wait for the process to stop again:
2704 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2705
2706 if (!got_event)
2707 {
2708 // Right now this is the only way to tell we've timed out...
2709 // We should interrupt the process here...
2710 // Not really sure what to do if Halt fails here...
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002711 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002712 if (try_all_threads)
Greg Clayton414f5d32011-01-25 02:58:48 +00002713 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, trying with all threads enabled.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002714 single_thread_timeout_usec);
2715 else
Greg Clayton414f5d32011-01-25 02:58:48 +00002716 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002717 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002718 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002719
Jim Inghame22e88b2011-01-22 01:30:53 +00002720 Error halt_error = exe_ctx.process->Halt();
2721
2722 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002723 {
2724 timeout_ptr = NULL;
2725 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002726 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002727
2728 // Between the time that we got the timeout and the time we halted, but target
2729 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2730 // timeout to
2731 got_event = listener.WaitForEvent(NULL, event_sp);
2732
2733 if (got_event)
2734 {
2735 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2736 if (log)
2737 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002738 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf48169b2010-11-30 02:22:11 +00002739 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2740 log->Printf (" Event was the Halt interruption event.");
2741 }
2742
2743 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2744 {
2745 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002746 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002747 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002748 break;
2749 }
2750
2751 if (try_all_threads
2752 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2753 {
2754
2755 thread_plan_sp->SetStopOthers (false);
2756 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002757 log->Printf ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002758
2759 exe_ctx.process->Resume();
2760 continue;
2761 }
2762 else
2763 {
2764 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002765 return lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002766 }
2767 }
2768 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002769 else
2770 {
2771
2772 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002773 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
Jim Inghame22e88b2011-01-22 01:30:53 +00002774 halt_error.AsCString());
Jim Ingham444586b2011-01-24 06:34:17 +00002775// abort();
Jim Inghame22e88b2011-01-22 01:30:53 +00002776
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002777 if (single_thread_timeout_usec != 0)
2778 {
2779 real_timeout = TimeValue::Now();
2780 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2781 timeout_ptr = &real_timeout;
2782 }
2783 continue;
Jim Inghame22e88b2011-01-22 01:30:53 +00002784 }
2785
Jim Inghamf48169b2010-11-30 02:22:11 +00002786 }
2787
2788 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2789 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002790 log->Printf("Process::RunThreadPlan(): got event: %s.", StateAsCString(stop_state));
Jim Inghamf48169b2010-11-30 02:22:11 +00002791
2792 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2793 continue;
2794
2795 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2796 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002797 if (log)
2798 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002799 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002800 break;
2801 }
2802 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2803 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002804 if (log)
2805 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002806 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00002807 break;
2808 }
2809 else
2810 {
2811 if (log)
2812 {
2813 StreamString s;
Jim Inghame22e88b2011-01-22 01:30:53 +00002814 if (event_sp)
2815 event_sp->Dump (&s);
2816 else
2817 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002818 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghame22e88b2011-01-22 01:30:53 +00002819 }
2820
Jim Inghamf48169b2010-11-30 02:22:11 +00002821 StreamString ts;
2822
2823 const char *event_explanation;
2824
2825 do
2826 {
2827 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2828
2829 if (!event_data)
2830 {
2831 event_explanation = "<no event data>";
2832 break;
2833 }
2834
2835 Process *process = event_data->GetProcessSP().get();
2836
2837 if (!process)
2838 {
2839 event_explanation = "<no process>";
2840 break;
2841 }
2842
2843 ThreadList &thread_list = process->GetThreadList();
2844
2845 uint32_t num_threads = thread_list.GetSize();
2846 uint32_t thread_index;
2847
2848 ts.Printf("<%u threads> ", num_threads);
2849
2850 for (thread_index = 0;
2851 thread_index < num_threads;
2852 ++thread_index)
2853 {
2854 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2855
2856 if (!thread)
2857 {
2858 ts.Printf("<?> ");
2859 continue;
2860 }
2861
Jim Inghame22e88b2011-01-22 01:30:53 +00002862 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton5ccbd292011-01-06 22:15:06 +00002863 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Inghamf48169b2010-11-30 02:22:11 +00002864
2865 if (register_context)
2866 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2867 else
2868 ts.Printf("[ip unknown] ");
2869
2870 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2871 if (stop_info_sp)
2872 {
2873 const char *stop_desc = stop_info_sp->GetDescription();
2874 if (stop_desc)
2875 ts.PutCString (stop_desc);
2876 }
2877 ts.Printf(">");
2878 }
2879
2880 event_explanation = ts.GetData();
2881 } while (0);
2882
Jim Inghame22e88b2011-01-22 01:30:53 +00002883 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2884 if (!GetThreadList().ShouldStop(event_sp.get()))
2885 {
2886 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002887 log->Printf("Process::RunThreadPlan(): execution interrupted, but nobody wanted to stop, so we continued: %s %s",
Jim Inghame22e88b2011-01-22 01:30:53 +00002888 s.GetData(), event_explanation);
2889 if (single_thread_timeout_usec != 0)
2890 {
2891 real_timeout = TimeValue::Now();
2892 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2893 timeout_ptr = &real_timeout;
2894 }
2895
2896 continue;
2897 }
2898 else
2899 {
2900 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002901 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Jim Inghame22e88b2011-01-22 01:30:53 +00002902 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002903 }
2904
2905 if (discard_on_error && thread_plan_sp)
2906 {
2907 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2908 }
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002909 return_value = lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002910 break;
2911 }
2912 }
2913
2914 if (exe_ctx.process)
2915 exe_ctx.process->RestoreProcessEvents ();
2916
2917 // Thread we ran the function in may have gone away because we ran the target
2918 // Check that it's still there.
2919 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2920 if (exe_ctx.thread)
2921 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2922
2923 // Also restore the current process'es selected frame & thread, since this function calling may
2924 // be done behind the user's back.
2925
2926 if (selected_tid != LLDB_INVALID_THREAD_ID)
2927 {
2928 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2929 {
2930 // We were able to restore the selected thread, now restore the frame:
2931 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2932 }
2933 }
2934
2935 return return_value;
2936}
2937
2938const char *
2939Process::ExecutionResultAsCString (ExecutionResults result)
2940{
2941 const char *result_name;
2942
2943 switch (result)
2944 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002945 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002946 result_name = "eExecutionCompleted";
2947 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002948 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00002949 result_name = "eExecutionDiscarded";
2950 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002951 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002952 result_name = "eExecutionInterrupted";
2953 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002954 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00002955 result_name = "eExecutionSetupError";
2956 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002957 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00002958 result_name = "eExecutionTimedOut";
2959 break;
2960 }
2961 return result_name;
2962}
2963
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002964//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002965// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002966//--------------------------------------------------------------
2967
Greg Clayton1b654882010-09-19 02:33:57 +00002968Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002969 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002970{
Greg Clayton85851dd2010-12-04 00:10:17 +00002971 m_default_settings.reset (new ProcessInstanceSettings (*this,
2972 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002973 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002974}
2975
Greg Clayton1b654882010-09-19 02:33:57 +00002976Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002977{
2978}
2979
2980lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002981Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002982{
Greg Claytondbe54502010-11-19 03:46:01 +00002983 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2984 false,
2985 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002986 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2987 return new_settings_sp;
2988}
2989
2990//--------------------------------------------------------------
2991// class ProcessInstanceSettings
2992//--------------------------------------------------------------
2993
Greg Clayton85851dd2010-12-04 00:10:17 +00002994ProcessInstanceSettings::ProcessInstanceSettings
2995(
2996 UserSettingsController &owner,
2997 bool live_instance,
2998 const char *name
2999) :
3000 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003001 m_run_args (),
3002 m_env_vars (),
3003 m_input_path (),
3004 m_output_path (),
3005 m_error_path (),
3006 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00003007 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00003008 m_disable_stdio (false),
3009 m_inherit_host_env (true),
3010 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003011{
Caroline Ticef20e8232010-09-09 18:26:37 +00003012 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3013 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3014 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00003015 // This is true for CreateInstanceName() too.
3016
3017 if (GetInstanceName () == InstanceSettings::InvalidName())
3018 {
3019 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3020 m_owner.RegisterInstanceSettings (this);
3021 }
Caroline Ticef20e8232010-09-09 18:26:37 +00003022
3023 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003024 {
3025 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3026 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00003027 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003028 }
3029}
3030
3031ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00003032 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003033 m_run_args (rhs.m_run_args),
3034 m_env_vars (rhs.m_env_vars),
3035 m_input_path (rhs.m_input_path),
3036 m_output_path (rhs.m_output_path),
3037 m_error_path (rhs.m_error_path),
3038 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00003039 m_disable_aslr (rhs.m_disable_aslr),
3040 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003041{
3042 if (m_instance_name != InstanceSettings::GetDefaultName())
3043 {
3044 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3045 CopyInstanceSettings (pending_settings,false);
3046 m_owner.RemovePendingSettings (m_instance_name);
3047 }
3048}
3049
3050ProcessInstanceSettings::~ProcessInstanceSettings ()
3051{
3052}
3053
3054ProcessInstanceSettings&
3055ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3056{
3057 if (this != &rhs)
3058 {
3059 m_run_args = rhs.m_run_args;
3060 m_env_vars = rhs.m_env_vars;
3061 m_input_path = rhs.m_input_path;
3062 m_output_path = rhs.m_output_path;
3063 m_error_path = rhs.m_error_path;
3064 m_plugin = rhs.m_plugin;
3065 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003066 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00003067 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003068 }
3069
3070 return *this;
3071}
3072
3073
3074void
3075ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3076 const char *index_value,
3077 const char *value,
3078 const ConstString &instance_name,
3079 const SettingEntry &entry,
3080 lldb::VarSetOperationType op,
3081 Error &err,
3082 bool pending)
3083{
3084 if (var_name == RunArgsVarName())
3085 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3086 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003087 {
3088 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003089 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003090 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003091 else if (var_name == InputPathVarName())
3092 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3093 else if (var_name == OutputPathVarName())
3094 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3095 else if (var_name == ErrorPathVarName())
3096 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3097 else if (var_name == PluginVarName())
3098 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003099 else if (var_name == InheritHostEnvVarName())
3100 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003101 else if (var_name == DisableASLRVarName())
3102 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003103 else if (var_name == DisableSTDIOVarName ())
3104 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003105}
3106
3107void
3108ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3109 bool pending)
3110{
3111 if (new_settings.get() == NULL)
3112 return;
3113
3114 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3115
3116 m_run_args = new_process_settings->m_run_args;
3117 m_env_vars = new_process_settings->m_env_vars;
3118 m_input_path = new_process_settings->m_input_path;
3119 m_output_path = new_process_settings->m_output_path;
3120 m_error_path = new_process_settings->m_error_path;
3121 m_plugin = new_process_settings->m_plugin;
3122 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003123 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003124}
3125
Caroline Tice12cecd72010-09-20 21:37:42 +00003126bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003127ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3128 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003129 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003130 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003131{
3132 if (var_name == RunArgsVarName())
3133 {
3134 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003135 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003136 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3137 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003138 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003139 }
3140 else if (var_name == EnvVarsVarName())
3141 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003142 GetHostEnvironmentIfNeeded ();
3143
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003144 if (m_env_vars.size() > 0)
3145 {
3146 std::map<std::string, std::string>::iterator pos;
3147 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3148 {
3149 StreamString value_str;
3150 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3151 value.AppendString (value_str.GetData());
3152 }
3153 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003154 }
3155 else if (var_name == InputPathVarName())
3156 {
3157 value.AppendString (m_input_path.c_str());
3158 }
3159 else if (var_name == OutputPathVarName())
3160 {
3161 value.AppendString (m_output_path.c_str());
3162 }
3163 else if (var_name == ErrorPathVarName())
3164 {
3165 value.AppendString (m_error_path.c_str());
3166 }
3167 else if (var_name == PluginVarName())
3168 {
3169 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3170 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003171 else if (var_name == InheritHostEnvVarName())
3172 {
3173 if (m_inherit_host_env)
3174 value.AppendString ("true");
3175 else
3176 value.AppendString ("false");
3177 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003178 else if (var_name == DisableASLRVarName())
3179 {
3180 if (m_disable_aslr)
3181 value.AppendString ("true");
3182 else
3183 value.AppendString ("false");
3184 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003185 else if (var_name == DisableSTDIOVarName())
3186 {
3187 if (m_disable_stdio)
3188 value.AppendString ("true");
3189 else
3190 value.AppendString ("false");
3191 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003192 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003193 {
3194 if (err)
3195 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3196 return false;
3197 }
3198 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003199}
3200
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003201const ConstString
3202ProcessInstanceSettings::CreateInstanceName ()
3203{
3204 static int instance_count = 1;
3205 StreamString sstr;
3206
3207 sstr.Printf ("process_%d", instance_count);
3208 ++instance_count;
3209
3210 const ConstString ret_val (sstr.GetData());
3211 return ret_val;
3212}
3213
3214const ConstString &
3215ProcessInstanceSettings::RunArgsVarName ()
3216{
3217 static ConstString run_args_var_name ("run-args");
3218
3219 return run_args_var_name;
3220}
3221
3222const ConstString &
3223ProcessInstanceSettings::EnvVarsVarName ()
3224{
3225 static ConstString env_vars_var_name ("env-vars");
3226
3227 return env_vars_var_name;
3228}
3229
3230const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003231ProcessInstanceSettings::InheritHostEnvVarName ()
3232{
3233 static ConstString g_name ("inherit-env");
3234
3235 return g_name;
3236}
3237
3238const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003239ProcessInstanceSettings::InputPathVarName ()
3240{
3241 static ConstString input_path_var_name ("input-path");
3242
3243 return input_path_var_name;
3244}
3245
3246const ConstString &
3247ProcessInstanceSettings::OutputPathVarName ()
3248{
Caroline Tice49e27372010-09-07 18:35:40 +00003249 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003250
3251 return output_path_var_name;
3252}
3253
3254const ConstString &
3255ProcessInstanceSettings::ErrorPathVarName ()
3256{
Caroline Tice49e27372010-09-07 18:35:40 +00003257 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003258
3259 return error_path_var_name;
3260}
3261
3262const ConstString &
3263ProcessInstanceSettings::PluginVarName ()
3264{
3265 static ConstString plugin_var_name ("plugin");
3266
3267 return plugin_var_name;
3268}
3269
3270
3271const ConstString &
3272ProcessInstanceSettings::DisableASLRVarName ()
3273{
3274 static ConstString disable_aslr_var_name ("disable-aslr");
3275
3276 return disable_aslr_var_name;
3277}
3278
Caroline Ticef8da8632010-12-03 18:46:09 +00003279const ConstString &
3280ProcessInstanceSettings::DisableSTDIOVarName ()
3281{
3282 static ConstString disable_stdio_var_name ("disable-stdio");
3283
3284 return disable_stdio_var_name;
3285}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003286
3287//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003288// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003289//--------------------------------------------------
3290
3291SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003292Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003293{
3294 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3295 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3296};
3297
3298
3299lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003300Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003301{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003302 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3303 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3304 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003305};
3306
3307SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003308Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003309{
Greg Clayton85851dd2010-12-04 00:10:17 +00003310 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3311 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3312 { "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." },
3313 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00003314 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3315 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3316 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3317 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00003318 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3319 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3320 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003321};
3322
3323
Jim Ingham5aee1622010-08-09 23:31:02 +00003324