blob: ecf8ef1ba5703a22efd03f2ff89f149607fa6ed2 [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 {
569 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000570 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000571 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000572
573 m_exit_status = status;
574 if (cstr)
575 m_exit_string = cstr;
576 else
577 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578
Greg Clayton6779606a2011-01-22 23:43:18 +0000579 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000580
Greg Clayton6779606a2011-01-22 23:43:18 +0000581 SetPrivateState (eStateExited);
582 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583}
584
585// This static callback can be used to watch for local child processes on
586// the current host. The the child process exits, the process will be
587// found in the global target list (we want to be completely sure that the
588// lldb_private::Process doesn't go away before we can deliver the signal.
589bool
590Process::SetProcessExitStatus
591(
592 void *callback_baton,
593 lldb::pid_t pid,
594 int signo, // Zero for no signal
595 int exit_status // Exit value of process if signal is zero
596)
597{
598 if (signo == 0 || exit_status)
599 {
Greg Clayton66111032010-06-23 01:19:29 +0000600 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601 if (target_sp)
602 {
603 ProcessSP process_sp (target_sp->GetProcessSP());
604 if (process_sp)
605 {
606 const char *signal_cstr = NULL;
607 if (signo)
608 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
609
610 process_sp->SetExitStatus (exit_status, signal_cstr);
611 }
612 }
613 return true;
614 }
615 return false;
616}
617
618
619uint32_t
620Process::GetNextThreadIndexID ()
621{
622 return ++m_thread_index_id;
623}
624
625StateType
626Process::GetState()
627{
628 // If any other threads access this we will need a mutex for it
629 return m_public_state.GetValue ();
630}
631
632void
633Process::SetPublicState (StateType new_state)
634{
Greg Clayton414f5d32011-01-25 02:58:48 +0000635 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636 if (log)
637 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
638 m_public_state.SetValue (new_state);
639}
640
641StateType
642Process::GetPrivateState ()
643{
644 return m_private_state.GetValue();
645}
646
647void
648Process::SetPrivateState (StateType new_state)
649{
Greg Clayton414f5d32011-01-25 02:58:48 +0000650 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651 bool state_changed = false;
652
653 if (log)
654 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
655
656 Mutex::Locker locker(m_private_state.GetMutex());
657
658 const StateType old_state = m_private_state.GetValueNoLock ();
659 state_changed = old_state != new_state;
660 if (state_changed)
661 {
662 m_private_state.SetValueNoLock (new_state);
663 if (StateIsStoppedState(new_state))
664 {
665 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000666 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667 if (log)
668 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
669 }
670 // Use our target to get a shared pointer to ourselves...
671 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
672 }
673 else
674 {
675 if (log)
676 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
677 }
678}
679
680
681uint32_t
682Process::GetStopID() const
683{
684 return m_stop_id;
685}
686
687addr_t
688Process::GetImageInfoAddress()
689{
690 return LLDB_INVALID_ADDRESS;
691}
692
Greg Clayton8f343b02010-11-04 01:54:29 +0000693//----------------------------------------------------------------------
694// LoadImage
695//
696// This function provides a default implementation that works for most
697// unix variants. Any Process subclasses that need to do shared library
698// loading differently should override LoadImage and UnloadImage and
699// do what is needed.
700//----------------------------------------------------------------------
701uint32_t
702Process::LoadImage (const FileSpec &image_spec, Error &error)
703{
704 DynamicLoader *loader = GetDynamicLoader();
705 if (loader)
706 {
707 error = loader->CanLoadImage();
708 if (error.Fail())
709 return LLDB_INVALID_IMAGE_TOKEN;
710 }
711
712 if (error.Success())
713 {
714 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
715 if (thread_sp == NULL)
716 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
717
718 if (thread_sp)
719 {
720 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
721
722 if (frame_sp)
723 {
724 ExecutionContext exe_ctx;
725 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000726 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000727 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000728 StreamString expr;
729 char path[PATH_MAX];
730 image_spec.GetPath(path, sizeof(path));
731 expr.Printf("dlopen (\"%s\", 2)", path);
732 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000733 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000734 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000735 if (result_valobj_sp->GetError().Success())
736 {
737 Scalar scalar;
738 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
739 {
740 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
741 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
742 {
743 uint32_t image_token = m_image_tokens.size();
744 m_image_tokens.push_back (image_ptr);
745 return image_token;
746 }
747 }
748 }
749 }
750 }
751 }
752 return LLDB_INVALID_IMAGE_TOKEN;
753}
754
755//----------------------------------------------------------------------
756// UnloadImage
757//
758// This function provides a default implementation that works for most
759// unix variants. Any Process subclasses that need to do shared library
760// loading differently should override LoadImage and UnloadImage and
761// do what is needed.
762//----------------------------------------------------------------------
763Error
764Process::UnloadImage (uint32_t image_token)
765{
766 Error error;
767 if (image_token < m_image_tokens.size())
768 {
769 const addr_t image_addr = m_image_tokens[image_token];
770 if (image_addr == LLDB_INVALID_ADDRESS)
771 {
772 error.SetErrorString("image already unloaded");
773 }
774 else
775 {
776 DynamicLoader *loader = GetDynamicLoader();
777 if (loader)
778 error = loader->CanLoadImage();
779
780 if (error.Success())
781 {
782 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
783 if (thread_sp == NULL)
784 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
785
786 if (thread_sp)
787 {
788 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
789
790 if (frame_sp)
791 {
792 ExecutionContext exe_ctx;
793 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000794 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000795 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000796 StreamString expr;
797 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
798 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000799 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000800 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000801 if (result_valobj_sp->GetError().Success())
802 {
803 Scalar scalar;
804 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
805 {
806 if (scalar.UInt(1))
807 {
808 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
809 }
810 else
811 {
812 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
813 }
814 }
815 }
816 else
817 {
818 error = result_valobj_sp->GetError();
819 }
820 }
821 }
822 }
823 }
824 }
825 else
826 {
827 error.SetErrorString("invalid image token");
828 }
829 return error;
830}
831
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832DynamicLoader *
833Process::GetDynamicLoader()
834{
835 return NULL;
836}
837
838const ABI *
839Process::GetABI()
840{
841 ConstString& triple = m_target_triple;
842
843 if (triple.IsEmpty())
844 return NULL;
845
846 if (m_abi_sp.get() == NULL)
847 {
848 m_abi_sp.reset(ABI::FindPlugin(triple));
849 }
850
851 return m_abi_sp.get();
852}
853
Jim Ingham22777012010-09-23 02:01:19 +0000854LanguageRuntime *
855Process::GetLanguageRuntime(lldb::LanguageType language)
856{
857 LanguageRuntimeCollection::iterator pos;
858 pos = m_language_runtimes.find (language);
859 if (pos == m_language_runtimes.end())
860 {
861 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
862
863 m_language_runtimes[language]
864 = runtime;
865 return runtime.get();
866 }
867 else
868 return (*pos).second.get();
869}
870
871CPPLanguageRuntime *
872Process::GetCPPLanguageRuntime ()
873{
874 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
875 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
876 return static_cast<CPPLanguageRuntime *> (runtime);
877 return NULL;
878}
879
880ObjCLanguageRuntime *
881Process::GetObjCLanguageRuntime ()
882{
883 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
884 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
885 return static_cast<ObjCLanguageRuntime *> (runtime);
886 return NULL;
887}
888
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889BreakpointSiteList &
890Process::GetBreakpointSiteList()
891{
892 return m_breakpoint_site_list;
893}
894
895const BreakpointSiteList &
896Process::GetBreakpointSiteList() const
897{
898 return m_breakpoint_site_list;
899}
900
901
902void
903Process::DisableAllBreakpointSites ()
904{
905 m_breakpoint_site_list.SetEnabledForAll (false);
906}
907
908Error
909Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
910{
911 Error error (DisableBreakpointSiteByID (break_id));
912
913 if (error.Success())
914 m_breakpoint_site_list.Remove(break_id);
915
916 return error;
917}
918
919Error
920Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
921{
922 Error error;
923 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
924 if (bp_site_sp)
925 {
926 if (bp_site_sp->IsEnabled())
927 error = DisableBreakpoint (bp_site_sp.get());
928 }
929 else
930 {
931 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
932 }
933
934 return error;
935}
936
937Error
938Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
939{
940 Error error;
941 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
942 if (bp_site_sp)
943 {
944 if (!bp_site_sp->IsEnabled())
945 error = EnableBreakpoint (bp_site_sp.get());
946 }
947 else
948 {
949 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
950 }
951 return error;
952}
953
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000954lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
956{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000957 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 if (load_addr != LLDB_INVALID_ADDRESS)
959 {
960 BreakpointSiteSP bp_site_sp;
961
962 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
963 // create a new breakpoint site and add it.
964
965 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
966
967 if (bp_site_sp)
968 {
969 bp_site_sp->AddOwner (owner);
970 owner->SetBreakpointSite (bp_site_sp);
971 return bp_site_sp->GetID();
972 }
973 else
974 {
975 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
976 if (bp_site_sp)
977 {
978 if (EnableBreakpoint (bp_site_sp.get()).Success())
979 {
980 owner->SetBreakpointSite (bp_site_sp);
981 return m_breakpoint_site_list.Add (bp_site_sp);
982 }
983 }
984 }
985 }
986 // We failed to enable the breakpoint
987 return LLDB_INVALID_BREAK_ID;
988
989}
990
991void
992Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
993{
994 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
995 if (num_owners == 0)
996 {
997 DisableBreakpoint(bp_site_sp.get());
998 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
999 }
1000}
1001
1002
1003size_t
1004Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1005{
1006 size_t bytes_removed = 0;
1007 addr_t intersect_addr;
1008 size_t intersect_size;
1009 size_t opcode_offset;
1010 size_t idx;
1011 BreakpointSiteSP bp;
1012
1013 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1014 {
1015 if (bp->GetType() == BreakpointSite::eSoftware)
1016 {
1017 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1018 {
1019 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1020 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1021 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1022 size_t buf_offset = intersect_addr - bp_addr;
1023 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1024 }
1025 }
1026 }
1027 return bytes_removed;
1028}
1029
1030
1031Error
1032Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1033{
1034 Error error;
1035 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001036 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037 const addr_t bp_addr = bp_site->GetLoadAddress();
1038 if (log)
1039 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1040 if (bp_site->IsEnabled())
1041 {
1042 if (log)
1043 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1044 return error;
1045 }
1046
1047 if (bp_addr == LLDB_INVALID_ADDRESS)
1048 {
1049 error.SetErrorString("BreakpointSite contains an invalid load address.");
1050 return error;
1051 }
1052 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1053 // trap for the breakpoint site
1054 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1055
1056 if (bp_opcode_size == 0)
1057 {
1058 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1059 }
1060 else
1061 {
1062 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1063
1064 if (bp_opcode_bytes == NULL)
1065 {
1066 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1067 return error;
1068 }
1069
1070 // Save the original opcode by reading it
1071 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1072 {
1073 // Write a software breakpoint in place of the original opcode
1074 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1075 {
1076 uint8_t verify_bp_opcode_bytes[64];
1077 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1078 {
1079 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1080 {
1081 bp_site->SetEnabled(true);
1082 bp_site->SetType (BreakpointSite::eSoftware);
1083 if (log)
1084 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1085 bp_site->GetID(),
1086 (uint64_t)bp_addr);
1087 }
1088 else
1089 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1090 }
1091 else
1092 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1093 }
1094 else
1095 error.SetErrorString("Unable to write breakpoint trap to memory.");
1096 }
1097 else
1098 error.SetErrorString("Unable to read memory at breakpoint address.");
1099 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001100 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1102 bp_site->GetID(),
1103 (uint64_t)bp_addr,
1104 error.AsCString());
1105 return error;
1106}
1107
1108Error
1109Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1110{
1111 Error error;
1112 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001113 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114 addr_t bp_addr = bp_site->GetLoadAddress();
1115 lldb::user_id_t breakID = bp_site->GetID();
1116 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001117 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
1119 if (bp_site->IsHardware())
1120 {
1121 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1122 }
1123 else if (bp_site->IsEnabled())
1124 {
1125 const size_t break_op_size = bp_site->GetByteSize();
1126 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1127 if (break_op_size > 0)
1128 {
1129 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001130 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001131 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132 bool break_op_found = false;
1133
1134 // Read the breakpoint opcode
1135 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1136 {
1137 bool verify = false;
1138 // Make sure we have the a breakpoint opcode exists at this address
1139 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1140 {
1141 break_op_found = true;
1142 // We found a valid breakpoint opcode at this address, now restore
1143 // the saved opcode.
1144 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1145 {
1146 verify = true;
1147 }
1148 else
1149 error.SetErrorString("Memory write failed when restoring original opcode.");
1150 }
1151 else
1152 {
1153 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1154 // Set verify to true and so we can check if the original opcode has already been restored
1155 verify = true;
1156 }
1157
1158 if (verify)
1159 {
Greg Claytonc982c762010-07-09 20:39:50 +00001160 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001161 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162 // Verify that our original opcode made it back to the inferior
1163 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1164 {
1165 // compare the memory we just read with the original opcode
1166 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1167 {
1168 // SUCCESS
1169 bp_site->SetEnabled(false);
1170 if (log)
1171 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1172 return error;
1173 }
1174 else
1175 {
1176 if (break_op_found)
1177 error.SetErrorString("Failed to restore original opcode.");
1178 }
1179 }
1180 else
1181 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1182 }
1183 }
1184 else
1185 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1186 }
1187 }
1188 else
1189 {
1190 if (log)
1191 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1192 return error;
1193 }
1194
1195 if (log)
1196 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1197 bp_site->GetID(),
1198 (uint64_t)bp_addr,
1199 error.AsCString());
1200 return error;
1201
1202}
1203
Greg Clayton58be07b2011-01-07 06:08:19 +00001204// Comment out line below to disable memory caching
1205#define ENABLE_MEMORY_CACHING
1206// Uncomment to verify memory caching works after making changes to caching code
1207//#define VERIFY_MEMORY_READS
1208
1209#if defined (ENABLE_MEMORY_CACHING)
1210
1211#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212
1213size_t
1214Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1215{
Greg Clayton58be07b2011-01-07 06:08:19 +00001216 // Memory caching is enabled, with debug verification
1217 if (buf && size)
1218 {
1219 // Uncomment the line below to make sure memory caching is working.
1220 // I ran this through the test suite and got no assertions, so I am
1221 // pretty confident this is working well. If any changes are made to
1222 // memory caching, uncomment the line below and test your changes!
1223
1224 // Verify all memory reads by using the cache first, then redundantly
1225 // reading the same memory from the inferior and comparing to make sure
1226 // everything is exactly the same.
1227 std::string verify_buf (size, '\0');
1228 assert (verify_buf.size() == size);
1229 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1230 Error verify_error;
1231 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1232 assert (cache_bytes_read == verify_bytes_read);
1233 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1234 assert (verify_error.Success() == error.Success());
1235 return cache_bytes_read;
1236 }
1237 return 0;
1238}
1239
1240#else // #if defined (VERIFY_MEMORY_READS)
1241
1242size_t
1243Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1244{
1245 // Memory caching enabled, no verification
1246 return m_memory_cache.Read (this, addr, buf, size, error);
1247}
1248
1249#endif // #else for #if defined (VERIFY_MEMORY_READS)
1250
1251#else // #if defined (ENABLE_MEMORY_CACHING)
1252
1253size_t
1254Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1255{
1256 // Memory caching is disabled
1257 return ReadMemoryFromInferior (addr, buf, size, error);
1258}
1259
1260#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1261
1262
1263size_t
1264Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1265{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266 if (buf == NULL || size == 0)
1267 return 0;
1268
1269 size_t bytes_read = 0;
1270 uint8_t *bytes = (uint8_t *)buf;
1271
1272 while (bytes_read < size)
1273 {
1274 const size_t curr_size = size - bytes_read;
1275 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1276 bytes + bytes_read,
1277 curr_size,
1278 error);
1279 bytes_read += curr_bytes_read;
1280 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1281 break;
1282 }
1283
1284 // Replace any software breakpoint opcodes that fall into this range back
1285 // into "buf" before we return
1286 if (bytes_read > 0)
1287 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1288 return bytes_read;
1289}
1290
Greg Clayton58a4c462010-12-16 20:01:20 +00001291uint64_t
1292Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1293{
1294 if (integer_byte_size > sizeof(uint64_t))
1295 {
1296 error.SetErrorString ("unsupported integer size");
1297 }
1298 else
1299 {
1300 uint8_t tmp[sizeof(uint64_t)];
1301 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1302 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1303 {
1304 uint32_t offset = 0;
1305 return data.GetMaxU64 (&offset, integer_byte_size);
1306 }
1307 }
1308 // Any plug-in that doesn't return success a memory read with the number
1309 // of bytes that were requested should be setting the error
1310 assert (error.Fail());
1311 return 0;
1312}
1313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314size_t
1315Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1316{
1317 size_t bytes_written = 0;
1318 const uint8_t *bytes = (const uint8_t *)buf;
1319
1320 while (bytes_written < size)
1321 {
1322 const size_t curr_size = size - bytes_written;
1323 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1324 bytes + bytes_written,
1325 curr_size,
1326 error);
1327 bytes_written += curr_bytes_written;
1328 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1329 break;
1330 }
1331 return bytes_written;
1332}
1333
1334size_t
1335Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1336{
Greg Clayton58be07b2011-01-07 06:08:19 +00001337#if defined (ENABLE_MEMORY_CACHING)
1338 m_memory_cache.Flush (addr, size);
1339#endif
1340
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341 if (buf == NULL || size == 0)
1342 return 0;
1343 // We need to write any data that would go where any current software traps
1344 // (enabled software breakpoints) any software traps (breakpoints) that we
1345 // may have placed in our tasks memory.
1346
1347 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1348 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1349
1350 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1351 return DoWriteMemory(addr, buf, size, error);
1352
1353 BreakpointSiteList::collection::const_iterator pos;
1354 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001355 addr_t intersect_addr = 0;
1356 size_t intersect_size = 0;
1357 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358 const uint8_t *ubuf = (const uint8_t *)buf;
1359
1360 for (pos = iter; pos != end; ++pos)
1361 {
1362 BreakpointSiteSP bp;
1363 bp = pos->second;
1364
1365 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1366 assert(addr <= intersect_addr && intersect_addr < addr + size);
1367 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1368 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1369
1370 // Check for bytes before this breakpoint
1371 const addr_t curr_addr = addr + bytes_written;
1372 if (intersect_addr > curr_addr)
1373 {
1374 // There are some bytes before this breakpoint that we need to
1375 // just write to memory
1376 size_t curr_size = intersect_addr - curr_addr;
1377 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1378 ubuf + bytes_written,
1379 curr_size,
1380 error);
1381 bytes_written += curr_bytes_written;
1382 if (curr_bytes_written != curr_size)
1383 {
1384 // We weren't able to write all of the requested bytes, we
1385 // are done looping and will return the number of bytes that
1386 // we have written so far.
1387 break;
1388 }
1389 }
1390
1391 // Now write any bytes that would cover up any software breakpoints
1392 // directly into the breakpoint opcode buffer
1393 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1394 bytes_written += intersect_size;
1395 }
1396
1397 // Write any remaining bytes after the last breakpoint if we have any left
1398 if (bytes_written < size)
1399 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1400 ubuf + bytes_written,
1401 size - bytes_written,
1402 error);
1403
1404 return bytes_written;
1405}
1406
1407addr_t
1408Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1409{
1410 // Fixme: we should track the blocks we've allocated, and clean them up...
1411 // We could even do our own allocator here if that ends up being more efficient.
Greg Claytonb2daec92011-01-23 19:58:49 +00001412 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1413 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1414 if (log)
Greg Clayton2ad66702011-01-24 06:30:45 +00001415 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001416 size,
1417 permissions & ePermissionsReadable ? 'r' : '-',
1418 permissions & ePermissionsWritable ? 'w' : '-',
1419 permissions & ePermissionsExecutable ? 'x' : '-',
1420 (uint64_t)allocated_addr,
1421 m_stop_id);
1422 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423}
1424
1425Error
1426Process::DeallocateMemory (addr_t ptr)
1427{
Greg Claytonb2daec92011-01-23 19:58:49 +00001428 Error error(DoDeallocateMemory (ptr));
1429
1430 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1431 if (log)
1432 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1433 ptr,
1434 error.AsCString("SUCCESS"),
1435 m_stop_id);
1436 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437}
1438
1439
1440Error
1441Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1442{
1443 Error error;
1444 error.SetErrorString("watchpoints are not supported");
1445 return error;
1446}
1447
1448Error
1449Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1450{
1451 Error error;
1452 error.SetErrorString("watchpoints are not supported");
1453 return error;
1454}
1455
1456StateType
1457Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1458{
1459 StateType state;
1460 // Now wait for the process to launch and return control to us, and then
1461 // call DidLaunch:
1462 while (1)
1463 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001464 event_sp.reset();
1465 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1466
1467 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00001469
1470 // If state is invalid, then we timed out
1471 if (state == eStateInvalid)
1472 break;
1473
1474 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001475 HandlePrivateEvent (event_sp);
1476 }
1477 return state;
1478}
1479
1480Error
1481Process::Launch
1482(
1483 char const *argv[],
1484 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001485 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486 const char *stdin_path,
1487 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001488 const char *stderr_path,
1489 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490)
1491{
1492 Error error;
1493 m_target_triple.Clear();
1494 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001495 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496
1497 Module *exe_module = m_target.GetExecutableModule().get();
1498 if (exe_module)
1499 {
1500 char exec_file_path[PATH_MAX];
1501 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1502 if (exe_module->GetFileSpec().Exists())
1503 {
1504 error = WillLaunch (exe_module);
1505 if (error.Success())
1506 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001507 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508 // The args coming in should not contain the application name, the
1509 // lldb_private::Process class will add this in case the executable
1510 // gets resolved to a different file than was given on the command
1511 // line (like when an applicaiton bundle is specified and will
1512 // resolve to the contained exectuable file, or the file given was
1513 // a symlink or other file system link that resolves to a different
1514 // file).
1515
1516 // Get the resolved exectuable path
1517
1518 // Make a new argument vector
1519 std::vector<const char *> exec_path_plus_argv;
1520 // Append the resolved executable path
1521 exec_path_plus_argv.push_back (exec_file_path);
1522
1523 // Push all args if there are any
1524 if (argv)
1525 {
1526 for (int i = 0; argv[i]; ++i)
1527 exec_path_plus_argv.push_back(argv[i]);
1528 }
1529
1530 // Push a NULL to terminate the args.
1531 exec_path_plus_argv.push_back(NULL);
1532
1533 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001534 error = DoLaunch (exe_module,
1535 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1536 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001537 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001538 stdin_path,
1539 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001540 stderr_path,
1541 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542
1543 if (error.Fail())
1544 {
1545 if (GetID() != LLDB_INVALID_PROCESS_ID)
1546 {
1547 SetID (LLDB_INVALID_PROCESS_ID);
1548 const char *error_string = error.AsCString();
1549 if (error_string == NULL)
1550 error_string = "launch failed";
1551 SetExitStatus (-1, error_string);
1552 }
1553 }
1554 else
1555 {
1556 EventSP event_sp;
1557 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1558
1559 if (state == eStateStopped || state == eStateCrashed)
1560 {
1561 DidLaunch ();
1562
1563 // This delays passing the stopped event to listeners till DidLaunch gets
1564 // a chance to complete...
1565 HandlePrivateEvent (event_sp);
1566 StartPrivateStateThread ();
1567 }
1568 else if (state == eStateExited)
1569 {
1570 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1571 // not likely to work, and return an invalid pid.
1572 HandlePrivateEvent (event_sp);
1573 }
1574 }
1575 }
1576 }
1577 else
1578 {
1579 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1580 }
1581 }
1582 return error;
1583}
1584
1585Error
1586Process::CompleteAttach ()
1587{
1588 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001589
1590 if (GetID() == LLDB_INVALID_PROCESS_ID)
1591 {
1592 error.SetErrorString("no process");
1593 }
1594
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595 EventSP event_sp;
1596 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1597 if (state == eStateStopped || state == eStateCrashed)
1598 {
1599 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001600 // Figure out which one is the executable, and set that in our target:
1601 ModuleList &modules = GetTarget().GetImages();
1602
1603 size_t num_modules = modules.GetSize();
1604 for (int i = 0; i < num_modules; i++)
1605 {
1606 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1607 if (module_sp->IsExecutable())
1608 {
1609 ModuleSP exec_module = GetTarget().GetExecutableModule();
1610 if (!exec_module || exec_module != module_sp)
1611 {
1612
1613 GetTarget().SetExecutableModule (module_sp, false);
1614 }
1615 break;
1616 }
1617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001618
1619 // This delays passing the stopped event to listeners till DidLaunch gets
1620 // a chance to complete...
1621 HandlePrivateEvent(event_sp);
1622 StartPrivateStateThread();
1623 }
1624 else
1625 {
1626 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1627 // not likely to work, and return an invalid pid.
1628 if (state == eStateExited)
1629 HandlePrivateEvent (event_sp);
1630 error.SetErrorStringWithFormat("invalid state after attach: %s",
1631 lldb_private::StateAsCString(state));
1632 }
1633 return error;
1634}
1635
1636Error
1637Process::Attach (lldb::pid_t attach_pid)
1638{
1639
1640 m_target_triple.Clear();
1641 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001642 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643
Jim Ingham5aee1622010-08-09 23:31:02 +00001644 // Find the process and its architecture. Make sure it matches the architecture
1645 // of the current Target, and if not adjust it.
1646
1647 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1648 if (attach_spec != GetTarget().GetArchitecture())
1649 {
1650 // Set the architecture on the target.
1651 GetTarget().SetArchitecture(attach_spec);
1652 }
1653
Greg Claytonc982c762010-07-09 20:39:50 +00001654 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655 if (error.Success())
1656 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001657 SetPublicState (eStateAttaching);
1658
Greg Claytonc982c762010-07-09 20:39:50 +00001659 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660 if (error.Success())
1661 {
1662 error = CompleteAttach();
1663 }
1664 else
1665 {
1666 if (GetID() != LLDB_INVALID_PROCESS_ID)
1667 {
1668 SetID (LLDB_INVALID_PROCESS_ID);
1669 const char *error_string = error.AsCString();
1670 if (error_string == NULL)
1671 error_string = "attach failed";
1672
1673 SetExitStatus(-1, error_string);
1674 }
1675 }
1676 }
1677 return error;
1678}
1679
1680Error
1681Process::Attach (const char *process_name, bool wait_for_launch)
1682{
1683 m_target_triple.Clear();
1684 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001685 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001686
1687 // Find the process and its architecture. Make sure it matches the architecture
1688 // of the current Target, and if not adjust it.
1689
Jim Ingham2ecb7422010-08-17 21:54:19 +00001690 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001691 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001692 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001693 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001694 {
1695 // Set the architecture on the target.
1696 GetTarget().SetArchitecture(attach_spec);
1697 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001698 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001699
Greg Claytonc982c762010-07-09 20:39:50 +00001700 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001701 if (error.Success())
1702 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001703 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001704 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001705 if (error.Fail())
1706 {
1707 if (GetID() != LLDB_INVALID_PROCESS_ID)
1708 {
1709 SetID (LLDB_INVALID_PROCESS_ID);
1710 const char *error_string = error.AsCString();
1711 if (error_string == NULL)
1712 error_string = "attach failed";
1713
1714 SetExitStatus(-1, error_string);
1715 }
1716 }
1717 else
1718 {
1719 error = CompleteAttach();
1720 }
1721 }
1722 return error;
1723}
1724
1725Error
1726Process::Resume ()
1727{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001728 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00001730 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1731 m_stop_id,
1732 StateAsCString(m_public_state.GetValue()),
1733 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734
1735 Error error (WillResume());
1736 // Tell the process it is about to resume before the thread list
1737 if (error.Success())
1738 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001739 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001740 // can let all of our threads know that they are about to be
1741 // resumed. Threads will each be called with
1742 // Thread::WillResume(StateType) where StateType contains the state
1743 // that they are supposed to have when the process is resumed
1744 // (suspended/running/stepping). Threads should also check
1745 // their resume signal in lldb::Thread::GetResumeSignal()
1746 // to see if they are suppoed to start back up with a signal.
1747 if (m_thread_list.WillResume())
1748 {
1749 error = DoResume();
1750 if (error.Success())
1751 {
1752 DidResume();
1753 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00001754 if (log)
1755 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001756 }
1757 }
1758 else
1759 {
Jim Ingham444586b2011-01-24 06:34:17 +00001760 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001761 }
1762 }
Jim Ingham444586b2011-01-24 06:34:17 +00001763 else if (log)
1764 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001765 return error;
1766}
1767
1768Error
1769Process::Halt ()
1770{
1771 Error error (WillHalt());
1772
1773 if (error.Success())
1774 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001775
1776 bool caused_stop = false;
1777 EventSP event_sp;
1778
1779 // Pause our private state thread so we can ensure no one else eats
1780 // the stop event out from under us.
1781 PausePrivateStateThread();
1782
1783 // Ask the process subclass to actually halt our process
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001784 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001785 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001786 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001787 // If "caused_stop" is true, then DoHalt stopped the process. If
1788 // "caused_stop" is false, the process was already stopped.
1789 // If the DoHalt caused the process to stop, then we want to catch
1790 // this event and set the interrupted bool to true before we pass
1791 // this along so clients know that the process was interrupted by
1792 // a halt command.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001793 if (caused_stop)
1794 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001795 // Wait for 2 seconds for the process to stop.
1796 TimeValue timeout_time;
1797 timeout_time = TimeValue::Now();
Greg Clayton6779606a2011-01-22 23:43:18 +00001798 timeout_time.OffsetWithSeconds(1);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001799 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1800
1801 if (state == eStateInvalid)
1802 {
1803 // We timeout out and didn't get a stop event...
1804 error.SetErrorString ("Halt timed out.");
1805 }
1806 else
1807 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001808 if (StateIsStoppedState (state))
1809 {
1810 // We caused the process to interrupt itself, so mark this
1811 // as such in the stop event so clients can tell an interrupted
1812 // process from a natural stop
1813 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1814 }
1815 else
1816 {
1817 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1818 if (log)
1819 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1820 error.SetErrorString ("Did not get stopped event after halt.");
1821 }
1822 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001823 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001824 DidHalt();
1825
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001826 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001827 // Resume our private state thread before we post the event (if any)
1828 ResumePrivateStateThread();
1829
1830 // Post any event we might have consumed. If all goes well, we will have
1831 // stopped the process, intercepted the event and set the interrupted
Jim Inghamf48169b2010-11-30 02:22:11 +00001832 // bool in the event. Post it to the private event queue and that will end up
1833 // correctly setting the state.
Greg Clayton3af9ea52010-11-18 05:57:03 +00001834 if (event_sp)
Caroline Ticeefed6132010-11-19 20:47:54 +00001835 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001836
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
1838 return error;
1839}
1840
1841Error
1842Process::Detach ()
1843{
1844 Error error (WillDetach());
1845
1846 if (error.Success())
1847 {
1848 DisableAllBreakpointSites();
1849 error = DoDetach();
1850 if (error.Success())
1851 {
1852 DidDetach();
1853 StopPrivateStateThread();
1854 }
1855 }
1856 return error;
1857}
1858
1859Error
1860Process::Destroy ()
1861{
1862 Error error (WillDestroy());
1863 if (error.Success())
1864 {
1865 DisableAllBreakpointSites();
1866 error = DoDestroy();
1867 if (error.Success())
1868 {
1869 DidDestroy();
1870 StopPrivateStateThread();
1871 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001872 m_stdio_communication.StopReadThread();
1873 m_stdio_communication.Disconnect();
1874 if (m_process_input_reader && m_process_input_reader->IsActive())
1875 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1876 if (m_process_input_reader)
1877 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878 }
1879 return error;
1880}
1881
1882Error
1883Process::Signal (int signal)
1884{
1885 Error error (WillSignal());
1886 if (error.Success())
1887 {
1888 error = DoSignal(signal);
1889 if (error.Success())
1890 DidSignal();
1891 }
1892 return error;
1893}
1894
1895UnixSignals &
1896Process::GetUnixSignals ()
1897{
1898 return m_unix_signals;
1899}
1900
1901Target &
1902Process::GetTarget ()
1903{
1904 return m_target;
1905}
1906
1907const Target &
1908Process::GetTarget () const
1909{
1910 return m_target;
1911}
1912
1913uint32_t
1914Process::GetAddressByteSize()
1915{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001916 if (m_addr_byte_size == 0)
1917 return m_target.GetArchitecture().GetAddressByteSize();
1918 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919}
1920
1921bool
1922Process::ShouldBroadcastEvent (Event *event_ptr)
1923{
1924 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1925 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001926 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927
1928 switch (state)
1929 {
1930 case eStateAttaching:
1931 case eStateLaunching:
1932 case eStateDetached:
1933 case eStateExited:
1934 case eStateUnloaded:
1935 // These events indicate changes in the state of the debugging session, always report them.
1936 return_value = true;
1937 break;
1938 case eStateInvalid:
1939 // We stopped for no apparent reason, don't report it.
1940 return_value = false;
1941 break;
1942 case eStateRunning:
1943 case eStateStepping:
1944 // If we've started the target running, we handle the cases where we
1945 // are already running and where there is a transition from stopped to
1946 // running differently.
1947 // running -> running: Automatically suppress extra running events
1948 // stopped -> running: Report except when there is one or more no votes
1949 // and no yes votes.
1950 SynchronouslyNotifyStateChanged (state);
1951 switch (m_public_state.GetValue())
1952 {
1953 case eStateRunning:
1954 case eStateStepping:
1955 // We always suppress multiple runnings with no PUBLIC stop in between.
1956 return_value = false;
1957 break;
1958 default:
1959 // TODO: make this work correctly. For now always report
1960 // run if we aren't running so we don't miss any runnning
1961 // events. If I run the lldb/test/thread/a.out file and
1962 // break at main.cpp:58, run and hit the breakpoints on
1963 // multiple threads, then somehow during the stepping over
1964 // of all breakpoints no run gets reported.
1965 return_value = true;
1966
1967 // This is a transition from stop to run.
1968 switch (m_thread_list.ShouldReportRun (event_ptr))
1969 {
1970 case eVoteYes:
1971 case eVoteNoOpinion:
1972 return_value = true;
1973 break;
1974 case eVoteNo:
1975 return_value = false;
1976 break;
1977 }
1978 break;
1979 }
1980 break;
1981 case eStateStopped:
1982 case eStateCrashed:
1983 case eStateSuspended:
1984 {
1985 // We've stopped. First see if we're going to restart the target.
1986 // If we are going to stop, then we always broadcast the event.
1987 // 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 +00001988 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001989 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001991 if (log)
1992 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001993 return true;
1994 }
1995 else
1996 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997 RefreshStateAfterStop ();
1998
1999 if (m_thread_list.ShouldStop (event_ptr) == false)
2000 {
2001 switch (m_thread_list.ShouldReportStop (event_ptr))
2002 {
2003 case eVoteYes:
2004 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002005 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 case eVoteNo:
2008 return_value = false;
2009 break;
2010 }
2011
2012 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002013 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 Resume ();
2015 }
2016 else
2017 {
2018 return_value = true;
2019 SynchronouslyNotifyStateChanged (state);
2020 }
2021 }
2022 }
2023 }
2024
2025 if (log)
2026 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2027 return return_value;
2028}
2029
2030//------------------------------------------------------------------
2031// Thread Queries
2032//------------------------------------------------------------------
2033
2034ThreadList &
2035Process::GetThreadList ()
2036{
2037 return m_thread_list;
2038}
2039
2040const ThreadList &
2041Process::GetThreadList () const
2042{
2043 return m_thread_list;
2044}
2045
2046
2047bool
2048Process::StartPrivateStateThread ()
2049{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002050 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002051
2052 if (log)
2053 log->Printf ("Process::%s ( )", __FUNCTION__);
2054
2055 // Create a thread that watches our internal state and controls which
2056 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002057 char thread_name[1024];
2058 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2059 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2061}
2062
2063void
2064Process::PausePrivateStateThread ()
2065{
2066 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2067}
2068
2069void
2070Process::ResumePrivateStateThread ()
2071{
2072 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2073}
2074
2075void
2076Process::StopPrivateStateThread ()
2077{
2078 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2079}
2080
2081void
2082Process::ControlPrivateStateThread (uint32_t signal)
2083{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002084 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002085
2086 assert (signal == eBroadcastInternalStateControlStop ||
2087 signal == eBroadcastInternalStateControlPause ||
2088 signal == eBroadcastInternalStateControlResume);
2089
2090 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002091 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002092
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002093 // Signal the private state thread. First we should copy this is case the
2094 // thread starts exiting since the private state thread will NULL this out
2095 // when it exits
2096 const lldb::thread_t private_state_thread = m_private_state_thread;
2097 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 {
2099 TimeValue timeout_time;
2100 bool timed_out;
2101
2102 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2103
2104 timeout_time = TimeValue::Now();
2105 timeout_time.OffsetWithSeconds(2);
2106 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2107 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2108
2109 if (signal == eBroadcastInternalStateControlStop)
2110 {
2111 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002112 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113
2114 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002115 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002116 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 }
2118 }
2119}
2120
2121void
2122Process::HandlePrivateEvent (EventSP &event_sp)
2123{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002124 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00002125 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 // See if we should broadcast this state to external clients?
2127 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128
2129 if (should_broadcast)
2130 {
2131 if (log)
2132 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002133 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2134 __FUNCTION__,
2135 GetID(),
2136 StateAsCString(new_state),
2137 StateAsCString (GetState ()),
2138 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139 }
Greg Clayton414f5d32011-01-25 02:58:48 +00002140 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002141 PushProcessInputReader ();
2142 else
2143 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2145 BroadcastEvent (event_sp);
2146 }
2147 else
2148 {
2149 if (log)
2150 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002151 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2152 __FUNCTION__,
2153 GetID(),
2154 StateAsCString(new_state),
2155 StateAsCString (GetState ()),
2156 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002157 }
2158 }
2159}
2160
2161void *
2162Process::PrivateStateThread (void *arg)
2163{
2164 Process *proc = static_cast<Process*> (arg);
2165 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166 return result;
2167}
2168
2169void *
2170Process::RunPrivateStateThread ()
2171{
2172 bool control_only = false;
2173 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2174
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002175 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176 if (log)
2177 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2178
2179 bool exit_now = false;
2180 while (!exit_now)
2181 {
2182 EventSP event_sp;
2183 WaitForEventsPrivate (NULL, event_sp, control_only);
2184 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2185 {
2186 switch (event_sp->GetType())
2187 {
2188 case eBroadcastInternalStateControlStop:
2189 exit_now = true;
2190 continue; // Go to next loop iteration so we exit without
2191 break; // doing any internal state managment below
2192
2193 case eBroadcastInternalStateControlPause:
2194 control_only = true;
2195 break;
2196
2197 case eBroadcastInternalStateControlResume:
2198 control_only = false;
2199 break;
2200 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002201
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002202 if (log)
2203 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2204
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002206 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207 }
2208
2209
2210 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2211
2212 if (internal_state != eStateInvalid)
2213 {
2214 HandlePrivateEvent (event_sp);
2215 }
2216
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002217 if (internal_state == eStateInvalid ||
2218 internal_state == eStateExited ||
2219 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002220 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002221 if (log)
2222 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2223
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002225 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 }
2227
Caroline Tice20ad3c42010-10-29 21:48:37 +00002228 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002229 if (log)
2230 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2231
Greg Clayton6ed95942011-01-22 07:12:45 +00002232 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2233 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234 return NULL;
2235}
2236
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237//------------------------------------------------------------------
2238// Process Event Data
2239//------------------------------------------------------------------
2240
2241Process::ProcessEventData::ProcessEventData () :
2242 EventData (),
2243 m_process_sp (),
2244 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002245 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002246 m_update_state (false),
2247 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248{
2249}
2250
2251Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2252 EventData (),
2253 m_process_sp (process_sp),
2254 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002255 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002256 m_update_state (false),
2257 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258{
2259}
2260
2261Process::ProcessEventData::~ProcessEventData()
2262{
2263}
2264
2265const ConstString &
2266Process::ProcessEventData::GetFlavorString ()
2267{
2268 static ConstString g_flavor ("Process::ProcessEventData");
2269 return g_flavor;
2270}
2271
2272const ConstString &
2273Process::ProcessEventData::GetFlavor () const
2274{
2275 return ProcessEventData::GetFlavorString ();
2276}
2277
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278void
2279Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2280{
2281 // This function gets called twice for each event, once when the event gets pulled
2282 // off of the private process event queue, and once when it gets pulled off of
2283 // the public event queue. m_update_state is used to distinguish these
2284 // two cases; it is false when we're just pulling it off for private handling,
2285 // and we don't want to do the breakpoint command handling then.
2286
2287 if (!m_update_state)
2288 return;
2289
2290 m_process_sp->SetPublicState (m_state);
2291
2292 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2293 if (m_state == eStateStopped && ! m_restarted)
2294 {
2295 int num_threads = m_process_sp->GetThreadList().GetSize();
2296 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 for (idx = 0; idx < num_threads; ++idx)
2299 {
2300 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2301
Jim Inghamb15bfc72010-10-20 00:39:53 +00002302 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2303 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002305 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306 }
2307 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002308
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002309 // The stop action might restart the target. If it does, then we want to mark that in the
2310 // event so that whoever is receiving it will know to wait for the running event and reflect
2311 // that state appropriately.
2312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 if (m_process_sp->GetPrivateState() == eStateRunning)
2314 SetRestarted(true);
2315 }
2316}
2317
2318void
2319Process::ProcessEventData::Dump (Stream *s) const
2320{
2321 if (m_process_sp)
2322 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2323
2324 s->Printf("state = %s", StateAsCString(GetState()));;
2325}
2326
2327const Process::ProcessEventData *
2328Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2329{
2330 if (event_ptr)
2331 {
2332 const EventData *event_data = event_ptr->GetData();
2333 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2334 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2335 }
2336 return NULL;
2337}
2338
2339ProcessSP
2340Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2341{
2342 ProcessSP process_sp;
2343 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2344 if (data)
2345 process_sp = data->GetProcessSP();
2346 return process_sp;
2347}
2348
2349StateType
2350Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2351{
2352 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2353 if (data == NULL)
2354 return eStateInvalid;
2355 else
2356 return data->GetState();
2357}
2358
2359bool
2360Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2361{
2362 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2363 if (data == NULL)
2364 return false;
2365 else
2366 return data->GetRestarted();
2367}
2368
2369void
2370Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2371{
2372 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2373 if (data != NULL)
2374 data->SetRestarted(new_value);
2375}
2376
2377bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002378Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2379{
2380 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2381 if (data == NULL)
2382 return false;
2383 else
2384 return data->GetInterrupted ();
2385}
2386
2387void
2388Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2389{
2390 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2391 if (data != NULL)
2392 data->SetInterrupted(new_value);
2393}
2394
2395bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002396Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2397{
2398 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2399 if (data)
2400 {
2401 data->SetUpdateStateOnRemoval();
2402 return true;
2403 }
2404 return false;
2405}
2406
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407Target *
2408Process::CalculateTarget ()
2409{
2410 return &m_target;
2411}
2412
2413Process *
2414Process::CalculateProcess ()
2415{
2416 return this;
2417}
2418
2419Thread *
2420Process::CalculateThread ()
2421{
2422 return NULL;
2423}
2424
2425StackFrame *
2426Process::CalculateStackFrame ()
2427{
2428 return NULL;
2429}
2430
2431void
Greg Clayton0603aa92010-10-04 01:05:56 +00002432Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433{
2434 exe_ctx.target = &m_target;
2435 exe_ctx.process = this;
2436 exe_ctx.thread = NULL;
2437 exe_ctx.frame = NULL;
2438}
2439
2440lldb::ProcessSP
2441Process::GetSP ()
2442{
2443 return GetTarget().GetProcessSP();
2444}
2445
Jim Ingham5aee1622010-08-09 23:31:02 +00002446uint32_t
2447Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2448{
2449 return 0;
2450}
2451
2452ArchSpec
2453Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2454{
2455 return Host::GetArchSpecForExistingProcess (pid);
2456}
2457
2458ArchSpec
2459Process::GetArchSpecForExistingProcess (const char *process_name)
2460{
2461 return Host::GetArchSpecForExistingProcess (process_name);
2462}
2463
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002464void
2465Process::AppendSTDOUT (const char * s, size_t len)
2466{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002467 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002468 m_stdout_data.append (s, len);
2469
Greg Claytona9ff3062010-12-05 19:16:56 +00002470 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002471}
2472
2473void
2474Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2475{
2476 Process *process = (Process *) baton;
2477 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2478}
2479
2480size_t
2481Process::ProcessInputReaderCallback (void *baton,
2482 InputReader &reader,
2483 lldb::InputReaderAction notification,
2484 const char *bytes,
2485 size_t bytes_len)
2486{
2487 Process *process = (Process *) baton;
2488
2489 switch (notification)
2490 {
2491 case eInputReaderActivate:
2492 break;
2493
2494 case eInputReaderDeactivate:
2495 break;
2496
2497 case eInputReaderReactivate:
2498 break;
2499
2500 case eInputReaderGotToken:
2501 {
2502 Error error;
2503 process->PutSTDIN (bytes, bytes_len, error);
2504 }
2505 break;
2506
Caroline Ticeefed6132010-11-19 20:47:54 +00002507 case eInputReaderInterrupt:
2508 process->Halt ();
2509 break;
2510
2511 case eInputReaderEndOfFile:
2512 process->AppendSTDOUT ("^D", 2);
2513 break;
2514
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002515 case eInputReaderDone:
2516 break;
2517
2518 }
2519
2520 return bytes_len;
2521}
2522
2523void
2524Process::ResetProcessInputReader ()
2525{
2526 m_process_input_reader.reset();
2527}
2528
2529void
2530Process::SetUpProcessInputReader (int file_descriptor)
2531{
2532 // First set up the Read Thread for reading/handling process I/O
2533
2534 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2535
2536 if (conn_ap.get())
2537 {
2538 m_stdio_communication.SetConnection (conn_ap.release());
2539 if (m_stdio_communication.IsConnected())
2540 {
2541 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2542 m_stdio_communication.StartReadThread();
2543
2544 // Now read thread is set up, set up input reader.
2545
2546 if (!m_process_input_reader.get())
2547 {
2548 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2549 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2550 this,
2551 eInputReaderGranularityByte,
2552 NULL,
2553 NULL,
2554 false));
2555
2556 if (err.Fail())
2557 m_process_input_reader.reset();
2558 }
2559 }
2560 }
2561}
2562
2563void
2564Process::PushProcessInputReader ()
2565{
2566 if (m_process_input_reader && !m_process_input_reader->IsActive())
2567 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2568}
2569
2570void
2571Process::PopProcessInputReader ()
2572{
2573 if (m_process_input_reader && m_process_input_reader->IsActive())
2574 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2575}
2576
Greg Clayton99d0faf2010-11-18 23:32:35 +00002577
2578void
2579Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002580{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002581 UserSettingsControllerSP &usc = GetSettingsController();
2582 usc.reset (new SettingsController);
2583 UserSettingsController::InitializeSettingsController (usc,
2584 SettingsController::global_settings_table,
2585 SettingsController::instance_settings_table);
2586}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002587
Greg Clayton99d0faf2010-11-18 23:32:35 +00002588void
2589Process::Terminate ()
2590{
2591 UserSettingsControllerSP &usc = GetSettingsController();
2592 UserSettingsController::FinalizeSettingsController (usc);
2593 usc.reset();
2594}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002595
Greg Clayton99d0faf2010-11-18 23:32:35 +00002596UserSettingsControllerSP &
2597Process::GetSettingsController ()
2598{
2599 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002600 return g_settings_controller;
2601}
2602
Caroline Tice1559a462010-09-27 00:30:10 +00002603void
2604Process::UpdateInstanceName ()
2605{
2606 ModuleSP module_sp = GetTarget().GetExecutableModule();
2607 if (module_sp)
2608 {
2609 StreamString sstr;
2610 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2611
Greg Claytondbe54502010-11-19 03:46:01 +00002612 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002613 sstr.GetData());
2614 }
2615}
2616
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002617ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002618Process::RunThreadPlan (ExecutionContext &exe_ctx,
2619 lldb::ThreadPlanSP &thread_plan_sp,
2620 bool stop_others,
2621 bool try_all_threads,
2622 bool discard_on_error,
2623 uint32_t single_thread_timeout_usec,
2624 Stream &errors)
2625{
2626 ExecutionResults return_value = eExecutionSetupError;
2627
Jim Ingham77787032011-01-20 02:03:18 +00002628 if (thread_plan_sp.get() == NULL)
2629 {
2630 errors.Printf("RunThreadPlan called with empty thread plan.");
2631 return lldb::eExecutionSetupError;
2632 }
2633
Jim Ingham444586b2011-01-24 06:34:17 +00002634 if (m_private_state.GetValue() != eStateStopped)
2635 {
2636 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
2637 // REMOVE BEAR TRAP...
2638 // abort();
2639 }
2640
Jim Inghamf48169b2010-11-30 02:22:11 +00002641 // Save this value for restoration of the execution context after we run
2642 uint32_t tid = exe_ctx.thread->GetIndexID();
2643
2644 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2645 // so we should arrange to reset them as well.
2646
2647 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2648 lldb::StackFrameSP selected_frame_sp;
2649
2650 uint32_t selected_tid;
2651 if (selected_thread_sp != NULL)
2652 {
2653 selected_tid = selected_thread_sp->GetIndexID();
2654 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2655 }
2656 else
2657 {
2658 selected_tid = LLDB_INVALID_THREAD_ID;
2659 }
2660
2661 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2662
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002663 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf48169b2010-11-30 02:22:11 +00002664 exe_ctx.process->HijackProcessEvents(&listener);
Jim Ingham444586b2011-01-24 06:34:17 +00002665
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002666 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00002667 if (log)
2668 {
2669 StreamString s;
2670 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton414f5d32011-01-25 02:58:48 +00002671 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 +00002672 }
2673
Jim Inghamf48169b2010-11-30 02:22:11 +00002674 Error resume_error = exe_ctx.process->Resume ();
2675 if (!resume_error.Success())
2676 {
2677 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2678 exe_ctx.process->RestoreProcessEvents();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002679 return lldb::eExecutionSetupError;
Jim Inghamf48169b2010-11-30 02:22:11 +00002680 }
2681
2682 // We need to call the function synchronously, so spin waiting for it to return.
2683 // If we get interrupted while executing, we're going to lose our context, and
2684 // won't be able to gather the result at this point.
2685 // We set the timeout AFTER the resume, since the resume takes some time and we
2686 // don't want to charge that to the timeout.
2687
2688 TimeValue* timeout_ptr = NULL;
2689 TimeValue real_timeout;
2690
2691 if (single_thread_timeout_usec != 0)
2692 {
2693 real_timeout = TimeValue::Now();
2694 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2695 timeout_ptr = &real_timeout;
2696 }
2697
Jim Inghamf48169b2010-11-30 02:22:11 +00002698 while (1)
2699 {
2700 lldb::EventSP event_sp;
2701 lldb::StateType stop_state = lldb::eStateInvalid;
2702 // Now wait for the process to stop again:
2703 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2704
2705 if (!got_event)
2706 {
2707 // Right now this is the only way to tell we've timed out...
2708 // We should interrupt the process here...
2709 // Not really sure what to do if Halt fails here...
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002710 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002711 if (try_all_threads)
Greg Clayton414f5d32011-01-25 02:58:48 +00002712 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, trying with all threads enabled.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002713 single_thread_timeout_usec);
2714 else
Greg Clayton414f5d32011-01-25 02:58:48 +00002715 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002716 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002717 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002718
Jim Inghame22e88b2011-01-22 01:30:53 +00002719 Error halt_error = exe_ctx.process->Halt();
2720
2721 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002722 {
2723 timeout_ptr = NULL;
2724 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002725 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002726
2727 // Between the time that we got the timeout and the time we halted, but target
2728 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2729 // timeout to
2730 got_event = listener.WaitForEvent(NULL, event_sp);
2731
2732 if (got_event)
2733 {
2734 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2735 if (log)
2736 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002737 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf48169b2010-11-30 02:22:11 +00002738 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2739 log->Printf (" Event was the Halt interruption event.");
2740 }
2741
2742 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2743 {
2744 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002745 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002746 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002747 break;
2748 }
2749
2750 if (try_all_threads
2751 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2752 {
2753
2754 thread_plan_sp->SetStopOthers (false);
2755 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002756 log->Printf ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002757
2758 exe_ctx.process->Resume();
2759 continue;
2760 }
2761 else
2762 {
2763 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002764 return lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002765 }
2766 }
2767 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002768 else
2769 {
2770
2771 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002772 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 +00002773 halt_error.AsCString());
Jim Ingham444586b2011-01-24 06:34:17 +00002774// abort();
Jim Inghame22e88b2011-01-22 01:30:53 +00002775
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002776 if (single_thread_timeout_usec != 0)
2777 {
2778 real_timeout = TimeValue::Now();
2779 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2780 timeout_ptr = &real_timeout;
2781 }
2782 continue;
Jim Inghame22e88b2011-01-22 01:30:53 +00002783 }
2784
Jim Inghamf48169b2010-11-30 02:22:11 +00002785 }
2786
2787 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2788 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002789 log->Printf("Process::RunThreadPlan(): got event: %s.", StateAsCString(stop_state));
Jim Inghamf48169b2010-11-30 02:22:11 +00002790
2791 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2792 continue;
2793
2794 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2795 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002796 if (log)
2797 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002798 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002799 break;
2800 }
2801 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2802 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002803 if (log)
2804 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002805 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00002806 break;
2807 }
2808 else
2809 {
2810 if (log)
2811 {
2812 StreamString s;
Jim Inghame22e88b2011-01-22 01:30:53 +00002813 if (event_sp)
2814 event_sp->Dump (&s);
2815 else
2816 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002817 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghame22e88b2011-01-22 01:30:53 +00002818 }
2819
Jim Inghamf48169b2010-11-30 02:22:11 +00002820 StreamString ts;
2821
2822 const char *event_explanation;
2823
2824 do
2825 {
2826 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2827
2828 if (!event_data)
2829 {
2830 event_explanation = "<no event data>";
2831 break;
2832 }
2833
2834 Process *process = event_data->GetProcessSP().get();
2835
2836 if (!process)
2837 {
2838 event_explanation = "<no process>";
2839 break;
2840 }
2841
2842 ThreadList &thread_list = process->GetThreadList();
2843
2844 uint32_t num_threads = thread_list.GetSize();
2845 uint32_t thread_index;
2846
2847 ts.Printf("<%u threads> ", num_threads);
2848
2849 for (thread_index = 0;
2850 thread_index < num_threads;
2851 ++thread_index)
2852 {
2853 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2854
2855 if (!thread)
2856 {
2857 ts.Printf("<?> ");
2858 continue;
2859 }
2860
Jim Inghame22e88b2011-01-22 01:30:53 +00002861 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton5ccbd292011-01-06 22:15:06 +00002862 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Inghamf48169b2010-11-30 02:22:11 +00002863
2864 if (register_context)
2865 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2866 else
2867 ts.Printf("[ip unknown] ");
2868
2869 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2870 if (stop_info_sp)
2871 {
2872 const char *stop_desc = stop_info_sp->GetDescription();
2873 if (stop_desc)
2874 ts.PutCString (stop_desc);
2875 }
2876 ts.Printf(">");
2877 }
2878
2879 event_explanation = ts.GetData();
2880 } while (0);
2881
Jim Inghame22e88b2011-01-22 01:30:53 +00002882 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2883 if (!GetThreadList().ShouldStop(event_sp.get()))
2884 {
2885 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002886 log->Printf("Process::RunThreadPlan(): execution interrupted, but nobody wanted to stop, so we continued: %s %s",
Jim Inghame22e88b2011-01-22 01:30:53 +00002887 s.GetData(), event_explanation);
2888 if (single_thread_timeout_usec != 0)
2889 {
2890 real_timeout = TimeValue::Now();
2891 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2892 timeout_ptr = &real_timeout;
2893 }
2894
2895 continue;
2896 }
2897 else
2898 {
2899 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002900 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Jim Inghame22e88b2011-01-22 01:30:53 +00002901 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002902 }
2903
2904 if (discard_on_error && thread_plan_sp)
2905 {
2906 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2907 }
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002908 return_value = lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002909 break;
2910 }
2911 }
2912
2913 if (exe_ctx.process)
2914 exe_ctx.process->RestoreProcessEvents ();
2915
2916 // Thread we ran the function in may have gone away because we ran the target
2917 // Check that it's still there.
2918 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2919 if (exe_ctx.thread)
2920 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2921
2922 // Also restore the current process'es selected frame & thread, since this function calling may
2923 // be done behind the user's back.
2924
2925 if (selected_tid != LLDB_INVALID_THREAD_ID)
2926 {
2927 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2928 {
2929 // We were able to restore the selected thread, now restore the frame:
2930 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2931 }
2932 }
2933
2934 return return_value;
2935}
2936
2937const char *
2938Process::ExecutionResultAsCString (ExecutionResults result)
2939{
2940 const char *result_name;
2941
2942 switch (result)
2943 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002944 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002945 result_name = "eExecutionCompleted";
2946 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002947 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00002948 result_name = "eExecutionDiscarded";
2949 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002950 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002951 result_name = "eExecutionInterrupted";
2952 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002953 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00002954 result_name = "eExecutionSetupError";
2955 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002956 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00002957 result_name = "eExecutionTimedOut";
2958 break;
2959 }
2960 return result_name;
2961}
2962
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002963//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002964// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002965//--------------------------------------------------------------
2966
Greg Clayton1b654882010-09-19 02:33:57 +00002967Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002968 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002969{
Greg Clayton85851dd2010-12-04 00:10:17 +00002970 m_default_settings.reset (new ProcessInstanceSettings (*this,
2971 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002972 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002973}
2974
Greg Clayton1b654882010-09-19 02:33:57 +00002975Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002976{
2977}
2978
2979lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002980Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002981{
Greg Claytondbe54502010-11-19 03:46:01 +00002982 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2983 false,
2984 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002985 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2986 return new_settings_sp;
2987}
2988
2989//--------------------------------------------------------------
2990// class ProcessInstanceSettings
2991//--------------------------------------------------------------
2992
Greg Clayton85851dd2010-12-04 00:10:17 +00002993ProcessInstanceSettings::ProcessInstanceSettings
2994(
2995 UserSettingsController &owner,
2996 bool live_instance,
2997 const char *name
2998) :
2999 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003000 m_run_args (),
3001 m_env_vars (),
3002 m_input_path (),
3003 m_output_path (),
3004 m_error_path (),
3005 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00003006 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00003007 m_disable_stdio (false),
3008 m_inherit_host_env (true),
3009 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003010{
Caroline Ticef20e8232010-09-09 18:26:37 +00003011 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3012 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3013 // 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 +00003014 // This is true for CreateInstanceName() too.
3015
3016 if (GetInstanceName () == InstanceSettings::InvalidName())
3017 {
3018 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3019 m_owner.RegisterInstanceSettings (this);
3020 }
Caroline Ticef20e8232010-09-09 18:26:37 +00003021
3022 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003023 {
3024 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3025 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00003026 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003027 }
3028}
3029
3030ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00003031 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003032 m_run_args (rhs.m_run_args),
3033 m_env_vars (rhs.m_env_vars),
3034 m_input_path (rhs.m_input_path),
3035 m_output_path (rhs.m_output_path),
3036 m_error_path (rhs.m_error_path),
3037 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00003038 m_disable_aslr (rhs.m_disable_aslr),
3039 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003040{
3041 if (m_instance_name != InstanceSettings::GetDefaultName())
3042 {
3043 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3044 CopyInstanceSettings (pending_settings,false);
3045 m_owner.RemovePendingSettings (m_instance_name);
3046 }
3047}
3048
3049ProcessInstanceSettings::~ProcessInstanceSettings ()
3050{
3051}
3052
3053ProcessInstanceSettings&
3054ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3055{
3056 if (this != &rhs)
3057 {
3058 m_run_args = rhs.m_run_args;
3059 m_env_vars = rhs.m_env_vars;
3060 m_input_path = rhs.m_input_path;
3061 m_output_path = rhs.m_output_path;
3062 m_error_path = rhs.m_error_path;
3063 m_plugin = rhs.m_plugin;
3064 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003065 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00003066 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003067 }
3068
3069 return *this;
3070}
3071
3072
3073void
3074ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3075 const char *index_value,
3076 const char *value,
3077 const ConstString &instance_name,
3078 const SettingEntry &entry,
3079 lldb::VarSetOperationType op,
3080 Error &err,
3081 bool pending)
3082{
3083 if (var_name == RunArgsVarName())
3084 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3085 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003086 {
3087 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003088 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003089 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003090 else if (var_name == InputPathVarName())
3091 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3092 else if (var_name == OutputPathVarName())
3093 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3094 else if (var_name == ErrorPathVarName())
3095 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3096 else if (var_name == PluginVarName())
3097 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003098 else if (var_name == InheritHostEnvVarName())
3099 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003100 else if (var_name == DisableASLRVarName())
3101 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003102 else if (var_name == DisableSTDIOVarName ())
3103 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003104}
3105
3106void
3107ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3108 bool pending)
3109{
3110 if (new_settings.get() == NULL)
3111 return;
3112
3113 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3114
3115 m_run_args = new_process_settings->m_run_args;
3116 m_env_vars = new_process_settings->m_env_vars;
3117 m_input_path = new_process_settings->m_input_path;
3118 m_output_path = new_process_settings->m_output_path;
3119 m_error_path = new_process_settings->m_error_path;
3120 m_plugin = new_process_settings->m_plugin;
3121 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003122 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003123}
3124
Caroline Tice12cecd72010-09-20 21:37:42 +00003125bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003126ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3127 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003128 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003129 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003130{
3131 if (var_name == RunArgsVarName())
3132 {
3133 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003134 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003135 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3136 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003137 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003138 }
3139 else if (var_name == EnvVarsVarName())
3140 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003141 GetHostEnvironmentIfNeeded ();
3142
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003143 if (m_env_vars.size() > 0)
3144 {
3145 std::map<std::string, std::string>::iterator pos;
3146 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3147 {
3148 StreamString value_str;
3149 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3150 value.AppendString (value_str.GetData());
3151 }
3152 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003153 }
3154 else if (var_name == InputPathVarName())
3155 {
3156 value.AppendString (m_input_path.c_str());
3157 }
3158 else if (var_name == OutputPathVarName())
3159 {
3160 value.AppendString (m_output_path.c_str());
3161 }
3162 else if (var_name == ErrorPathVarName())
3163 {
3164 value.AppendString (m_error_path.c_str());
3165 }
3166 else if (var_name == PluginVarName())
3167 {
3168 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3169 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003170 else if (var_name == InheritHostEnvVarName())
3171 {
3172 if (m_inherit_host_env)
3173 value.AppendString ("true");
3174 else
3175 value.AppendString ("false");
3176 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003177 else if (var_name == DisableASLRVarName())
3178 {
3179 if (m_disable_aslr)
3180 value.AppendString ("true");
3181 else
3182 value.AppendString ("false");
3183 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003184 else if (var_name == DisableSTDIOVarName())
3185 {
3186 if (m_disable_stdio)
3187 value.AppendString ("true");
3188 else
3189 value.AppendString ("false");
3190 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003191 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003192 {
3193 if (err)
3194 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3195 return false;
3196 }
3197 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003198}
3199
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003200const ConstString
3201ProcessInstanceSettings::CreateInstanceName ()
3202{
3203 static int instance_count = 1;
3204 StreamString sstr;
3205
3206 sstr.Printf ("process_%d", instance_count);
3207 ++instance_count;
3208
3209 const ConstString ret_val (sstr.GetData());
3210 return ret_val;
3211}
3212
3213const ConstString &
3214ProcessInstanceSettings::RunArgsVarName ()
3215{
3216 static ConstString run_args_var_name ("run-args");
3217
3218 return run_args_var_name;
3219}
3220
3221const ConstString &
3222ProcessInstanceSettings::EnvVarsVarName ()
3223{
3224 static ConstString env_vars_var_name ("env-vars");
3225
3226 return env_vars_var_name;
3227}
3228
3229const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003230ProcessInstanceSettings::InheritHostEnvVarName ()
3231{
3232 static ConstString g_name ("inherit-env");
3233
3234 return g_name;
3235}
3236
3237const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003238ProcessInstanceSettings::InputPathVarName ()
3239{
3240 static ConstString input_path_var_name ("input-path");
3241
3242 return input_path_var_name;
3243}
3244
3245const ConstString &
3246ProcessInstanceSettings::OutputPathVarName ()
3247{
Caroline Tice49e27372010-09-07 18:35:40 +00003248 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003249
3250 return output_path_var_name;
3251}
3252
3253const ConstString &
3254ProcessInstanceSettings::ErrorPathVarName ()
3255{
Caroline Tice49e27372010-09-07 18:35:40 +00003256 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003257
3258 return error_path_var_name;
3259}
3260
3261const ConstString &
3262ProcessInstanceSettings::PluginVarName ()
3263{
3264 static ConstString plugin_var_name ("plugin");
3265
3266 return plugin_var_name;
3267}
3268
3269
3270const ConstString &
3271ProcessInstanceSettings::DisableASLRVarName ()
3272{
3273 static ConstString disable_aslr_var_name ("disable-aslr");
3274
3275 return disable_aslr_var_name;
3276}
3277
Caroline Ticef8da8632010-12-03 18:46:09 +00003278const ConstString &
3279ProcessInstanceSettings::DisableSTDIOVarName ()
3280{
3281 static ConstString disable_stdio_var_name ("disable-stdio");
3282
3283 return disable_stdio_var_name;
3284}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003285
3286//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003287// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003288//--------------------------------------------------
3289
3290SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003291Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003292{
3293 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3294 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3295};
3296
3297
3298lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003299Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003300{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003301 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3302 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3303 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003304};
3305
3306SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003307Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003308{
Greg Clayton85851dd2010-12-04 00:10:17 +00003309 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3310 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3311 { "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." },
3312 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00003313 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3314 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3315 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3316 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00003317 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3318 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3319 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003320};
3321
3322
Jim Ingham5aee1622010-08-09 23:31:02 +00003323