blob: 9d58fb06346cf74746073cfafd75561c753c1c5f [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 (),
Greg Clayton7fb56d02011-02-01 01:31:41 +0000233 m_byte_order (lldb::endian::InlHostByteOrder()),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000234 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 (),
Jim Inghambb3a2832011-01-29 01:49:25 +0000240 m_memory_cache (),
Greg Clayton513c26c2011-01-29 07:10:55 +0000241 m_next_event_action_ap()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000242{
Caroline Tice1559a462010-09-27 00:30:10 +0000243 UpdateInstanceName();
244
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000245 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000246 if (log)
247 log->Printf ("%p Process::Process()", this);
248
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000249 SetEventName (eBroadcastBitStateChanged, "state-changed");
250 SetEventName (eBroadcastBitInterrupt, "interrupt");
251 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
252 SetEventName (eBroadcastBitSTDERR, "stderr-available");
253
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000254 listener.StartListeningForEvents (this,
255 eBroadcastBitStateChanged |
256 eBroadcastBitInterrupt |
257 eBroadcastBitSTDOUT |
258 eBroadcastBitSTDERR);
259
260 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
261 eBroadcastBitStateChanged);
262
263 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
264 eBroadcastInternalStateControlStop |
265 eBroadcastInternalStateControlPause |
266 eBroadcastInternalStateControlResume);
267}
268
269//----------------------------------------------------------------------
270// Destructor
271//----------------------------------------------------------------------
272Process::~Process()
273{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000274 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275 if (log)
276 log->Printf ("%p Process::~Process()", this);
277 StopPrivateStateThread();
278}
279
280void
281Process::Finalize()
282{
283 // Do any cleanup needed prior to being destructed... Subclasses
284 // that override this method should call this superclass method as well.
285}
286
287void
288Process::RegisterNotificationCallbacks (const Notifications& callbacks)
289{
290 m_notifications.push_back(callbacks);
291 if (callbacks.initialize != NULL)
292 callbacks.initialize (callbacks.baton, this);
293}
294
295bool
296Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
297{
298 std::vector<Notifications>::iterator pos, end = m_notifications.end();
299 for (pos = m_notifications.begin(); pos != end; ++pos)
300 {
301 if (pos->baton == callbacks.baton &&
302 pos->initialize == callbacks.initialize &&
303 pos->process_state_changed == callbacks.process_state_changed)
304 {
305 m_notifications.erase(pos);
306 return true;
307 }
308 }
309 return false;
310}
311
312void
313Process::SynchronouslyNotifyStateChanged (StateType state)
314{
315 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
316 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
317 {
318 if (notification_pos->process_state_changed)
319 notification_pos->process_state_changed (notification_pos->baton, this, state);
320 }
321}
322
323// FIXME: We need to do some work on events before the general Listener sees them.
324// For instance if we are continuing from a breakpoint, we need to ensure that we do
325// the little "insert real insn, step & stop" trick. But we can't do that when the
326// event is delivered by the broadcaster - since that is done on the thread that is
327// waiting for new events, so if we needed more than one event for our handling, we would
328// stall. So instead we do it when we fetch the event off of the queue.
329//
330
331StateType
332Process::GetNextEvent (EventSP &event_sp)
333{
334 StateType state = eStateInvalid;
335
336 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
337 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
338
339 return state;
340}
341
342
343StateType
344Process::WaitForProcessToStop (const TimeValue *timeout)
345{
346 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
347 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
348}
349
350
351StateType
352Process::WaitForState
353(
354 const TimeValue *timeout,
355 const StateType *match_states, const uint32_t num_match_states
356)
357{
358 EventSP event_sp;
359 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000360 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000361 while (state != eStateInvalid)
362 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000363 // If we are exited or detached, we won't ever get back to any
364 // other valid state...
365 if (state == eStateDetached || state == eStateExited)
366 return state;
367
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368 state = WaitForStateChangedEvents (timeout, event_sp);
369
370 for (i=0; i<num_match_states; ++i)
371 {
372 if (match_states[i] == state)
373 return state;
374 }
375 }
376 return state;
377}
378
Jim Ingham30f9b212010-10-11 23:53:14 +0000379bool
380Process::HijackProcessEvents (Listener *listener)
381{
382 if (listener != NULL)
383 {
384 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
385 }
386 else
387 return false;
388}
389
390void
391Process::RestoreProcessEvents ()
392{
393 RestoreBroadcaster();
394}
395
Jim Ingham0f16e732011-02-08 05:20:59 +0000396bool
397Process::HijackPrivateProcessEvents (Listener *listener)
398{
399 if (listener != NULL)
400 {
401 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
402 }
403 else
404 return false;
405}
406
407void
408Process::RestorePrivateProcessEvents ()
409{
410 m_private_state_broadcaster.RestoreBroadcaster();
411}
412
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000413StateType
414Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
415{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000416 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000417
418 if (log)
419 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
420
421 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000422 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
423 this,
424 eBroadcastBitStateChanged,
425 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
427
428 if (log)
429 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
430 __FUNCTION__,
431 timeout,
432 StateAsCString(state));
433 return state;
434}
435
436Event *
437Process::PeekAtStateChangedEvents ()
438{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000439 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440
441 if (log)
442 log->Printf ("Process::%s...", __FUNCTION__);
443
444 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000445 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
446 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447 if (log)
448 {
449 if (event_ptr)
450 {
451 log->Printf ("Process::%s (event_ptr) => %s",
452 __FUNCTION__,
453 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
454 }
455 else
456 {
457 log->Printf ("Process::%s no events found",
458 __FUNCTION__);
459 }
460 }
461 return event_ptr;
462}
463
464StateType
465Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
466{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000467 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000468
469 if (log)
470 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
471
472 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000473 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
474 &m_private_state_broadcaster,
475 eBroadcastBitStateChanged,
476 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
478
479 // This is a bit of a hack, but when we wait here we could very well return
480 // to the command-line, and that could disable the log, which would render the
481 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000482 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000483 {
484 if (state == eStateInvalid)
485 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
486 else
487 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
488 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489 return state;
490}
491
492bool
493Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
494{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000495 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496
497 if (log)
498 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
499
500 if (control_only)
501 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
502 else
503 return m_private_state_listener.WaitForEvent(timeout, event_sp);
504}
505
506bool
507Process::IsRunning () const
508{
509 return StateIsRunningState (m_public_state.GetValue());
510}
511
512int
513Process::GetExitStatus ()
514{
515 if (m_public_state.GetValue() == eStateExited)
516 return m_exit_status;
517 return -1;
518}
519
Greg Clayton85851dd2010-12-04 00:10:17 +0000520
521void
522Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
523{
524 if (m_inherit_host_env && !m_got_host_env)
525 {
526 m_got_host_env = true;
527 StringList host_env;
528 const size_t host_env_count = Host::GetEnvironment (host_env);
529 for (size_t idx=0; idx<host_env_count; idx++)
530 {
531 const char *env_entry = host_env.GetStringAtIndex (idx);
532 if (env_entry)
533 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000534 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000535 if (equal_pos)
536 {
537 std::string key (env_entry, equal_pos - env_entry);
538 std::string value (equal_pos + 1);
539 if (m_env_vars.find (key) == m_env_vars.end())
540 m_env_vars[key] = value;
541 }
542 }
543 }
544 }
545}
546
547
548size_t
549Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
550{
551 GetHostEnvironmentIfNeeded ();
552
553 dictionary::const_iterator pos, end = m_env_vars.end();
554 for (pos = m_env_vars.begin(); pos != end; ++pos)
555 {
556 std::string env_var_equal_value (pos->first);
557 env_var_equal_value.append(1, '=');
558 env_var_equal_value.append (pos->second);
559 env.AppendArgument (env_var_equal_value.c_str());
560 }
561 return env.GetArgumentCount();
562}
563
564
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565const char *
566Process::GetExitDescription ()
567{
568 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
569 return m_exit_string.c_str();
570 return NULL;
571}
572
Greg Clayton6779606a2011-01-22 23:43:18 +0000573bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000574Process::SetExitStatus (int status, const char *cstr)
575{
Greg Clayton414f5d32011-01-25 02:58:48 +0000576 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
577 if (log)
578 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
579 status, status,
580 cstr ? "\"" : "",
581 cstr ? cstr : "NULL",
582 cstr ? "\"" : "");
583
Greg Clayton6779606a2011-01-22 23:43:18 +0000584 // We were already in the exited state
585 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000586 {
Greg Clayton385d6032011-01-26 23:47:29 +0000587 if (log)
588 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000589 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000590 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000591
592 m_exit_status = status;
593 if (cstr)
594 m_exit_string = cstr;
595 else
596 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597
Greg Clayton6779606a2011-01-22 23:43:18 +0000598 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000599
Greg Clayton6779606a2011-01-22 23:43:18 +0000600 SetPrivateState (eStateExited);
601 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602}
603
604// This static callback can be used to watch for local child processes on
605// the current host. The the child process exits, the process will be
606// found in the global target list (we want to be completely sure that the
607// lldb_private::Process doesn't go away before we can deliver the signal.
608bool
609Process::SetProcessExitStatus
610(
611 void *callback_baton,
612 lldb::pid_t pid,
613 int signo, // Zero for no signal
614 int exit_status // Exit value of process if signal is zero
615)
616{
617 if (signo == 0 || exit_status)
618 {
Greg Clayton66111032010-06-23 01:19:29 +0000619 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620 if (target_sp)
621 {
622 ProcessSP process_sp (target_sp->GetProcessSP());
623 if (process_sp)
624 {
625 const char *signal_cstr = NULL;
626 if (signo)
627 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
628
629 process_sp->SetExitStatus (exit_status, signal_cstr);
630 }
631 }
632 return true;
633 }
634 return false;
635}
636
637
638uint32_t
639Process::GetNextThreadIndexID ()
640{
641 return ++m_thread_index_id;
642}
643
644StateType
645Process::GetState()
646{
647 // If any other threads access this we will need a mutex for it
648 return m_public_state.GetValue ();
649}
650
651void
652Process::SetPublicState (StateType new_state)
653{
Greg Clayton414f5d32011-01-25 02:58:48 +0000654 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 if (log)
656 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
657 m_public_state.SetValue (new_state);
658}
659
660StateType
661Process::GetPrivateState ()
662{
663 return m_private_state.GetValue();
664}
665
666void
667Process::SetPrivateState (StateType new_state)
668{
Greg Clayton414f5d32011-01-25 02:58:48 +0000669 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 bool state_changed = false;
671
672 if (log)
673 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
674
675 Mutex::Locker locker(m_private_state.GetMutex());
676
677 const StateType old_state = m_private_state.GetValueNoLock ();
678 state_changed = old_state != new_state;
679 if (state_changed)
680 {
681 m_private_state.SetValueNoLock (new_state);
682 if (StateIsStoppedState(new_state))
683 {
684 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000685 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686 if (log)
687 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
688 }
689 // Use our target to get a shared pointer to ourselves...
690 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
691 }
692 else
693 {
694 if (log)
695 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
696 }
697}
698
699
700uint32_t
701Process::GetStopID() const
702{
703 return m_stop_id;
704}
705
706addr_t
707Process::GetImageInfoAddress()
708{
709 return LLDB_INVALID_ADDRESS;
710}
711
Greg Clayton8f343b02010-11-04 01:54:29 +0000712//----------------------------------------------------------------------
713// LoadImage
714//
715// This function provides a default implementation that works for most
716// unix variants. Any Process subclasses that need to do shared library
717// loading differently should override LoadImage and UnloadImage and
718// do what is needed.
719//----------------------------------------------------------------------
720uint32_t
721Process::LoadImage (const FileSpec &image_spec, Error &error)
722{
723 DynamicLoader *loader = GetDynamicLoader();
724 if (loader)
725 {
726 error = loader->CanLoadImage();
727 if (error.Fail())
728 return LLDB_INVALID_IMAGE_TOKEN;
729 }
730
731 if (error.Success())
732 {
733 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
734 if (thread_sp == NULL)
735 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
736
737 if (thread_sp)
738 {
739 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
740
741 if (frame_sp)
742 {
743 ExecutionContext exe_ctx;
744 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000745 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000746 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000747 StreamString expr;
748 char path[PATH_MAX];
749 image_spec.GetPath(path, sizeof(path));
750 expr.Printf("dlopen (\"%s\", 2)", path);
751 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000752 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000753 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000754 if (result_valobj_sp->GetError().Success())
755 {
756 Scalar scalar;
757 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
758 {
759 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
760 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
761 {
762 uint32_t image_token = m_image_tokens.size();
763 m_image_tokens.push_back (image_ptr);
764 return image_token;
765 }
766 }
767 }
768 }
769 }
770 }
771 return LLDB_INVALID_IMAGE_TOKEN;
772}
773
774//----------------------------------------------------------------------
775// UnloadImage
776//
777// This function provides a default implementation that works for most
778// unix variants. Any Process subclasses that need to do shared library
779// loading differently should override LoadImage and UnloadImage and
780// do what is needed.
781//----------------------------------------------------------------------
782Error
783Process::UnloadImage (uint32_t image_token)
784{
785 Error error;
786 if (image_token < m_image_tokens.size())
787 {
788 const addr_t image_addr = m_image_tokens[image_token];
789 if (image_addr == LLDB_INVALID_ADDRESS)
790 {
791 error.SetErrorString("image already unloaded");
792 }
793 else
794 {
795 DynamicLoader *loader = GetDynamicLoader();
796 if (loader)
797 error = loader->CanLoadImage();
798
799 if (error.Success())
800 {
801 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
802 if (thread_sp == NULL)
803 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
804
805 if (thread_sp)
806 {
807 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
808
809 if (frame_sp)
810 {
811 ExecutionContext exe_ctx;
812 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000813 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000814 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000815 StreamString expr;
816 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
817 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000818 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000819 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000820 if (result_valobj_sp->GetError().Success())
821 {
822 Scalar scalar;
823 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
824 {
825 if (scalar.UInt(1))
826 {
827 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
828 }
829 else
830 {
831 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
832 }
833 }
834 }
835 else
836 {
837 error = result_valobj_sp->GetError();
838 }
839 }
840 }
841 }
842 }
843 }
844 else
845 {
846 error.SetErrorString("invalid image token");
847 }
848 return error;
849}
850
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851DynamicLoader *
852Process::GetDynamicLoader()
853{
854 return NULL;
855}
856
857const ABI *
858Process::GetABI()
859{
860 ConstString& triple = m_target_triple;
861
862 if (triple.IsEmpty())
863 return NULL;
864
865 if (m_abi_sp.get() == NULL)
866 {
867 m_abi_sp.reset(ABI::FindPlugin(triple));
868 }
869
870 return m_abi_sp.get();
871}
872
Jim Ingham22777012010-09-23 02:01:19 +0000873LanguageRuntime *
874Process::GetLanguageRuntime(lldb::LanguageType language)
875{
876 LanguageRuntimeCollection::iterator pos;
877 pos = m_language_runtimes.find (language);
878 if (pos == m_language_runtimes.end())
879 {
880 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
881
882 m_language_runtimes[language]
883 = runtime;
884 return runtime.get();
885 }
886 else
887 return (*pos).second.get();
888}
889
890CPPLanguageRuntime *
891Process::GetCPPLanguageRuntime ()
892{
893 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
894 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
895 return static_cast<CPPLanguageRuntime *> (runtime);
896 return NULL;
897}
898
899ObjCLanguageRuntime *
900Process::GetObjCLanguageRuntime ()
901{
902 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
903 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
904 return static_cast<ObjCLanguageRuntime *> (runtime);
905 return NULL;
906}
907
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908BreakpointSiteList &
909Process::GetBreakpointSiteList()
910{
911 return m_breakpoint_site_list;
912}
913
914const BreakpointSiteList &
915Process::GetBreakpointSiteList() const
916{
917 return m_breakpoint_site_list;
918}
919
920
921void
922Process::DisableAllBreakpointSites ()
923{
924 m_breakpoint_site_list.SetEnabledForAll (false);
925}
926
927Error
928Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
929{
930 Error error (DisableBreakpointSiteByID (break_id));
931
932 if (error.Success())
933 m_breakpoint_site_list.Remove(break_id);
934
935 return error;
936}
937
938Error
939Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
940{
941 Error error;
942 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
943 if (bp_site_sp)
944 {
945 if (bp_site_sp->IsEnabled())
946 error = DisableBreakpoint (bp_site_sp.get());
947 }
948 else
949 {
950 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
951 }
952
953 return error;
954}
955
956Error
957Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
958{
959 Error error;
960 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
961 if (bp_site_sp)
962 {
963 if (!bp_site_sp->IsEnabled())
964 error = EnableBreakpoint (bp_site_sp.get());
965 }
966 else
967 {
968 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
969 }
970 return error;
971}
972
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000973lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
975{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000976 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 if (load_addr != LLDB_INVALID_ADDRESS)
978 {
979 BreakpointSiteSP bp_site_sp;
980
981 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
982 // create a new breakpoint site and add it.
983
984 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
985
986 if (bp_site_sp)
987 {
988 bp_site_sp->AddOwner (owner);
989 owner->SetBreakpointSite (bp_site_sp);
990 return bp_site_sp->GetID();
991 }
992 else
993 {
994 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
995 if (bp_site_sp)
996 {
997 if (EnableBreakpoint (bp_site_sp.get()).Success())
998 {
999 owner->SetBreakpointSite (bp_site_sp);
1000 return m_breakpoint_site_list.Add (bp_site_sp);
1001 }
1002 }
1003 }
1004 }
1005 // We failed to enable the breakpoint
1006 return LLDB_INVALID_BREAK_ID;
1007
1008}
1009
1010void
1011Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1012{
1013 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1014 if (num_owners == 0)
1015 {
1016 DisableBreakpoint(bp_site_sp.get());
1017 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1018 }
1019}
1020
1021
1022size_t
1023Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1024{
1025 size_t bytes_removed = 0;
1026 addr_t intersect_addr;
1027 size_t intersect_size;
1028 size_t opcode_offset;
1029 size_t idx;
1030 BreakpointSiteSP bp;
1031
1032 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1033 {
1034 if (bp->GetType() == BreakpointSite::eSoftware)
1035 {
1036 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1037 {
1038 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1039 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1040 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1041 size_t buf_offset = intersect_addr - bp_addr;
1042 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1043 }
1044 }
1045 }
1046 return bytes_removed;
1047}
1048
1049
1050Error
1051Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1052{
1053 Error error;
1054 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001055 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 const addr_t bp_addr = bp_site->GetLoadAddress();
1057 if (log)
1058 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1059 if (bp_site->IsEnabled())
1060 {
1061 if (log)
1062 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1063 return error;
1064 }
1065
1066 if (bp_addr == LLDB_INVALID_ADDRESS)
1067 {
1068 error.SetErrorString("BreakpointSite contains an invalid load address.");
1069 return error;
1070 }
1071 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1072 // trap for the breakpoint site
1073 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1074
1075 if (bp_opcode_size == 0)
1076 {
1077 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1078 }
1079 else
1080 {
1081 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1082
1083 if (bp_opcode_bytes == NULL)
1084 {
1085 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1086 return error;
1087 }
1088
1089 // Save the original opcode by reading it
1090 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1091 {
1092 // Write a software breakpoint in place of the original opcode
1093 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1094 {
1095 uint8_t verify_bp_opcode_bytes[64];
1096 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1097 {
1098 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1099 {
1100 bp_site->SetEnabled(true);
1101 bp_site->SetType (BreakpointSite::eSoftware);
1102 if (log)
1103 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1104 bp_site->GetID(),
1105 (uint64_t)bp_addr);
1106 }
1107 else
1108 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1109 }
1110 else
1111 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1112 }
1113 else
1114 error.SetErrorString("Unable to write breakpoint trap to memory.");
1115 }
1116 else
1117 error.SetErrorString("Unable to read memory at breakpoint address.");
1118 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001119 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001120 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1121 bp_site->GetID(),
1122 (uint64_t)bp_addr,
1123 error.AsCString());
1124 return error;
1125}
1126
1127Error
1128Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1129{
1130 Error error;
1131 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001132 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133 addr_t bp_addr = bp_site->GetLoadAddress();
1134 lldb::user_id_t breakID = bp_site->GetID();
1135 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001136 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137
1138 if (bp_site->IsHardware())
1139 {
1140 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1141 }
1142 else if (bp_site->IsEnabled())
1143 {
1144 const size_t break_op_size = bp_site->GetByteSize();
1145 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1146 if (break_op_size > 0)
1147 {
1148 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001149 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001150 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151 bool break_op_found = false;
1152
1153 // Read the breakpoint opcode
1154 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1155 {
1156 bool verify = false;
1157 // Make sure we have the a breakpoint opcode exists at this address
1158 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1159 {
1160 break_op_found = true;
1161 // We found a valid breakpoint opcode at this address, now restore
1162 // the saved opcode.
1163 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1164 {
1165 verify = true;
1166 }
1167 else
1168 error.SetErrorString("Memory write failed when restoring original opcode.");
1169 }
1170 else
1171 {
1172 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1173 // Set verify to true and so we can check if the original opcode has already been restored
1174 verify = true;
1175 }
1176
1177 if (verify)
1178 {
Greg Claytonc982c762010-07-09 20:39:50 +00001179 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001180 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181 // Verify that our original opcode made it back to the inferior
1182 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1183 {
1184 // compare the memory we just read with the original opcode
1185 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1186 {
1187 // SUCCESS
1188 bp_site->SetEnabled(false);
1189 if (log)
1190 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1191 return error;
1192 }
1193 else
1194 {
1195 if (break_op_found)
1196 error.SetErrorString("Failed to restore original opcode.");
1197 }
1198 }
1199 else
1200 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1201 }
1202 }
1203 else
1204 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1205 }
1206 }
1207 else
1208 {
1209 if (log)
1210 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1211 return error;
1212 }
1213
1214 if (log)
1215 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1216 bp_site->GetID(),
1217 (uint64_t)bp_addr,
1218 error.AsCString());
1219 return error;
1220
1221}
1222
Greg Clayton58be07b2011-01-07 06:08:19 +00001223// Comment out line below to disable memory caching
1224#define ENABLE_MEMORY_CACHING
1225// Uncomment to verify memory caching works after making changes to caching code
1226//#define VERIFY_MEMORY_READS
1227
1228#if defined (ENABLE_MEMORY_CACHING)
1229
1230#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001231
1232size_t
1233Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1234{
Greg Clayton58be07b2011-01-07 06:08:19 +00001235 // Memory caching is enabled, with debug verification
1236 if (buf && size)
1237 {
1238 // Uncomment the line below to make sure memory caching is working.
1239 // I ran this through the test suite and got no assertions, so I am
1240 // pretty confident this is working well. If any changes are made to
1241 // memory caching, uncomment the line below and test your changes!
1242
1243 // Verify all memory reads by using the cache first, then redundantly
1244 // reading the same memory from the inferior and comparing to make sure
1245 // everything is exactly the same.
1246 std::string verify_buf (size, '\0');
1247 assert (verify_buf.size() == size);
1248 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1249 Error verify_error;
1250 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1251 assert (cache_bytes_read == verify_bytes_read);
1252 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1253 assert (verify_error.Success() == error.Success());
1254 return cache_bytes_read;
1255 }
1256 return 0;
1257}
1258
1259#else // #if defined (VERIFY_MEMORY_READS)
1260
1261size_t
1262Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1263{
1264 // Memory caching enabled, no verification
1265 return m_memory_cache.Read (this, addr, buf, size, error);
1266}
1267
1268#endif // #else for #if defined (VERIFY_MEMORY_READS)
1269
1270#else // #if defined (ENABLE_MEMORY_CACHING)
1271
1272size_t
1273Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1274{
1275 // Memory caching is disabled
1276 return ReadMemoryFromInferior (addr, buf, size, error);
1277}
1278
1279#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1280
1281
1282size_t
1283Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1284{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001285 if (buf == NULL || size == 0)
1286 return 0;
1287
1288 size_t bytes_read = 0;
1289 uint8_t *bytes = (uint8_t *)buf;
1290
1291 while (bytes_read < size)
1292 {
1293 const size_t curr_size = size - bytes_read;
1294 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1295 bytes + bytes_read,
1296 curr_size,
1297 error);
1298 bytes_read += curr_bytes_read;
1299 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1300 break;
1301 }
1302
1303 // Replace any software breakpoint opcodes that fall into this range back
1304 // into "buf" before we return
1305 if (bytes_read > 0)
1306 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1307 return bytes_read;
1308}
1309
Greg Clayton58a4c462010-12-16 20:01:20 +00001310uint64_t
1311Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1312{
1313 if (integer_byte_size > sizeof(uint64_t))
1314 {
1315 error.SetErrorString ("unsupported integer size");
1316 }
1317 else
1318 {
1319 uint8_t tmp[sizeof(uint64_t)];
1320 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1321 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1322 {
1323 uint32_t offset = 0;
1324 return data.GetMaxU64 (&offset, integer_byte_size);
1325 }
1326 }
1327 // Any plug-in that doesn't return success a memory read with the number
1328 // of bytes that were requested should be setting the error
1329 assert (error.Fail());
1330 return 0;
1331}
1332
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333size_t
1334Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1335{
1336 size_t bytes_written = 0;
1337 const uint8_t *bytes = (const uint8_t *)buf;
1338
1339 while (bytes_written < size)
1340 {
1341 const size_t curr_size = size - bytes_written;
1342 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1343 bytes + bytes_written,
1344 curr_size,
1345 error);
1346 bytes_written += curr_bytes_written;
1347 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1348 break;
1349 }
1350 return bytes_written;
1351}
1352
1353size_t
1354Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1355{
Greg Clayton58be07b2011-01-07 06:08:19 +00001356#if defined (ENABLE_MEMORY_CACHING)
1357 m_memory_cache.Flush (addr, size);
1358#endif
1359
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360 if (buf == NULL || size == 0)
1361 return 0;
1362 // We need to write any data that would go where any current software traps
1363 // (enabled software breakpoints) any software traps (breakpoints) that we
1364 // may have placed in our tasks memory.
1365
1366 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1367 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1368
1369 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1370 return DoWriteMemory(addr, buf, size, error);
1371
1372 BreakpointSiteList::collection::const_iterator pos;
1373 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001374 addr_t intersect_addr = 0;
1375 size_t intersect_size = 0;
1376 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001377 const uint8_t *ubuf = (const uint8_t *)buf;
1378
1379 for (pos = iter; pos != end; ++pos)
1380 {
1381 BreakpointSiteSP bp;
1382 bp = pos->second;
1383
1384 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1385 assert(addr <= intersect_addr && intersect_addr < addr + size);
1386 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1387 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1388
1389 // Check for bytes before this breakpoint
1390 const addr_t curr_addr = addr + bytes_written;
1391 if (intersect_addr > curr_addr)
1392 {
1393 // There are some bytes before this breakpoint that we need to
1394 // just write to memory
1395 size_t curr_size = intersect_addr - curr_addr;
1396 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1397 ubuf + bytes_written,
1398 curr_size,
1399 error);
1400 bytes_written += curr_bytes_written;
1401 if (curr_bytes_written != curr_size)
1402 {
1403 // We weren't able to write all of the requested bytes, we
1404 // are done looping and will return the number of bytes that
1405 // we have written so far.
1406 break;
1407 }
1408 }
1409
1410 // Now write any bytes that would cover up any software breakpoints
1411 // directly into the breakpoint opcode buffer
1412 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1413 bytes_written += intersect_size;
1414 }
1415
1416 // Write any remaining bytes after the last breakpoint if we have any left
1417 if (bytes_written < size)
1418 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1419 ubuf + bytes_written,
1420 size - bytes_written,
1421 error);
1422
1423 return bytes_written;
1424}
1425
1426addr_t
1427Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1428{
1429 // Fixme: we should track the blocks we've allocated, and clean them up...
1430 // We could even do our own allocator here if that ends up being more efficient.
Greg Claytonb2daec92011-01-23 19:58:49 +00001431 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1432 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1433 if (log)
Greg Clayton2ad66702011-01-24 06:30:45 +00001434 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001435 size,
1436 permissions & ePermissionsReadable ? 'r' : '-',
1437 permissions & ePermissionsWritable ? 'w' : '-',
1438 permissions & ePermissionsExecutable ? 'x' : '-',
1439 (uint64_t)allocated_addr,
1440 m_stop_id);
1441 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442}
1443
1444Error
1445Process::DeallocateMemory (addr_t ptr)
1446{
Greg Claytonb2daec92011-01-23 19:58:49 +00001447 Error error(DoDeallocateMemory (ptr));
1448
1449 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1450 if (log)
1451 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1452 ptr,
1453 error.AsCString("SUCCESS"),
1454 m_stop_id);
1455 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456}
1457
1458
1459Error
1460Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1461{
1462 Error error;
1463 error.SetErrorString("watchpoints are not supported");
1464 return error;
1465}
1466
1467Error
1468Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1469{
1470 Error error;
1471 error.SetErrorString("watchpoints are not supported");
1472 return error;
1473}
1474
1475StateType
1476Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1477{
1478 StateType state;
1479 // Now wait for the process to launch and return control to us, and then
1480 // call DidLaunch:
1481 while (1)
1482 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001483 event_sp.reset();
1484 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1485
1486 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00001488
1489 // If state is invalid, then we timed out
1490 if (state == eStateInvalid)
1491 break;
1492
1493 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494 HandlePrivateEvent (event_sp);
1495 }
1496 return state;
1497}
1498
1499Error
1500Process::Launch
1501(
1502 char const *argv[],
1503 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001504 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505 const char *stdin_path,
1506 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001507 const char *stderr_path,
1508 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509)
1510{
1511 Error error;
1512 m_target_triple.Clear();
1513 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001514 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001515
1516 Module *exe_module = m_target.GetExecutableModule().get();
1517 if (exe_module)
1518 {
1519 char exec_file_path[PATH_MAX];
1520 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1521 if (exe_module->GetFileSpec().Exists())
1522 {
1523 error = WillLaunch (exe_module);
1524 if (error.Success())
1525 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001526 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527 // The args coming in should not contain the application name, the
1528 // lldb_private::Process class will add this in case the executable
1529 // gets resolved to a different file than was given on the command
1530 // line (like when an applicaiton bundle is specified and will
1531 // resolve to the contained exectuable file, or the file given was
1532 // a symlink or other file system link that resolves to a different
1533 // file).
1534
1535 // Get the resolved exectuable path
1536
1537 // Make a new argument vector
1538 std::vector<const char *> exec_path_plus_argv;
1539 // Append the resolved executable path
1540 exec_path_plus_argv.push_back (exec_file_path);
1541
1542 // Push all args if there are any
1543 if (argv)
1544 {
1545 for (int i = 0; argv[i]; ++i)
1546 exec_path_plus_argv.push_back(argv[i]);
1547 }
1548
1549 // Push a NULL to terminate the args.
1550 exec_path_plus_argv.push_back(NULL);
1551
1552 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001553 error = DoLaunch (exe_module,
1554 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1555 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001556 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001557 stdin_path,
1558 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001559 stderr_path,
1560 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001561
1562 if (error.Fail())
1563 {
1564 if (GetID() != LLDB_INVALID_PROCESS_ID)
1565 {
1566 SetID (LLDB_INVALID_PROCESS_ID);
1567 const char *error_string = error.AsCString();
1568 if (error_string == NULL)
1569 error_string = "launch failed";
1570 SetExitStatus (-1, error_string);
1571 }
1572 }
1573 else
1574 {
1575 EventSP event_sp;
1576 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1577
1578 if (state == eStateStopped || state == eStateCrashed)
1579 {
1580 DidLaunch ();
1581
1582 // This delays passing the stopped event to listeners till DidLaunch gets
1583 // a chance to complete...
1584 HandlePrivateEvent (event_sp);
1585 StartPrivateStateThread ();
1586 }
1587 else if (state == eStateExited)
1588 {
1589 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1590 // not likely to work, and return an invalid pid.
1591 HandlePrivateEvent (event_sp);
1592 }
1593 }
1594 }
1595 }
1596 else
1597 {
1598 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1599 }
1600 }
1601 return error;
1602}
1603
Jim Inghambb3a2832011-01-29 01:49:25 +00001604Process::NextEventAction::EventActionResult
1605Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001606{
Jim Inghambb3a2832011-01-29 01:49:25 +00001607 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1608 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00001609 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001610 case eStateRunning:
1611 return eEventActionRetry;
1612
1613 case eStateStopped:
1614 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00001615 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001616 // During attach, prior to sending the eStateStopped event,
1617 // lldb_private::Process subclasses must set the process must set
1618 // the new process ID.
1619 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
1620 m_process->DidAttach ();
1621 // Figure out which one is the executable, and set that in our target:
1622 ModuleList &modules = m_process->GetTarget().GetImages();
1623
1624 size_t num_modules = modules.GetSize();
1625 for (int i = 0; i < num_modules; i++)
Jim Ingham5aee1622010-08-09 23:31:02 +00001626 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001627 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1628 if (module_sp->IsExecutable())
Jim Ingham5aee1622010-08-09 23:31:02 +00001629 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001630 ModuleSP exec_module = m_process->GetTarget().GetExecutableModule();
1631 if (!exec_module || exec_module != module_sp)
1632 {
1633
1634 m_process->GetTarget().SetExecutableModule (module_sp, false);
1635 }
1636 break;
Jim Ingham5aee1622010-08-09 23:31:02 +00001637 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001638 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001639 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00001640 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001641
1642
1643 break;
1644 default:
1645 case eStateExited:
1646 case eStateInvalid:
1647 m_exit_string.assign ("No valid Process");
1648 return eEventActionExit;
1649 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00001650 }
1651}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652
Jim Inghambb3a2832011-01-29 01:49:25 +00001653Process::NextEventAction::EventActionResult
1654Process::AttachCompletionHandler::HandleBeingInterrupted()
1655{
1656 return eEventActionSuccess;
1657}
1658
1659const char *
1660Process::AttachCompletionHandler::GetExitString ()
1661{
1662 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663}
1664
1665Error
1666Process::Attach (lldb::pid_t attach_pid)
1667{
1668
1669 m_target_triple.Clear();
1670 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001671 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672
Jim Ingham5aee1622010-08-09 23:31:02 +00001673 // Find the process and its architecture. Make sure it matches the architecture
1674 // of the current Target, and if not adjust it.
1675
1676 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1677 if (attach_spec != GetTarget().GetArchitecture())
1678 {
1679 // Set the architecture on the target.
1680 GetTarget().SetArchitecture(attach_spec);
1681 }
1682
Greg Claytonc982c762010-07-09 20:39:50 +00001683 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 if (error.Success())
1685 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001686 SetPublicState (eStateAttaching);
1687
Greg Claytonc982c762010-07-09 20:39:50 +00001688 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001689 if (error.Success())
1690 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001691 SetNextEventAction(new Process::AttachCompletionHandler(this));
1692 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001693 }
1694 else
1695 {
1696 if (GetID() != LLDB_INVALID_PROCESS_ID)
1697 {
1698 SetID (LLDB_INVALID_PROCESS_ID);
1699 const char *error_string = error.AsCString();
1700 if (error_string == NULL)
1701 error_string = "attach failed";
1702
1703 SetExitStatus(-1, error_string);
1704 }
1705 }
1706 }
1707 return error;
1708}
1709
1710Error
1711Process::Attach (const char *process_name, bool wait_for_launch)
1712{
1713 m_target_triple.Clear();
1714 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001715 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001716
1717 // Find the process and its architecture. Make sure it matches the architecture
1718 // of the current Target, and if not adjust it.
1719
Jim Ingham2ecb7422010-08-17 21:54:19 +00001720 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001721 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001722 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001723 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001724 {
1725 // Set the architecture on the target.
1726 GetTarget().SetArchitecture(attach_spec);
1727 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001728 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001729
Greg Claytonc982c762010-07-09 20:39:50 +00001730 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 if (error.Success())
1732 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001733 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001734 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001735 if (error.Fail())
1736 {
1737 if (GetID() != LLDB_INVALID_PROCESS_ID)
1738 {
1739 SetID (LLDB_INVALID_PROCESS_ID);
1740 const char *error_string = error.AsCString();
1741 if (error_string == NULL)
1742 error_string = "attach failed";
1743
1744 SetExitStatus(-1, error_string);
1745 }
1746 }
1747 else
1748 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001749 SetNextEventAction(new Process::AttachCompletionHandler(this));
1750 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 }
1752 }
1753 return error;
1754}
1755
1756Error
Greg Claytonb766a732011-02-04 01:58:07 +00001757Process::ConnectRemote (const char *remote_url)
1758{
1759 m_target_triple.Clear();
1760 m_abi_sp.reset();
1761 m_process_input_reader.reset();
1762
1763 // Find the process and its architecture. Make sure it matches the architecture
1764 // of the current Target, and if not adjust it.
1765
1766 Error error (DoConnectRemote (remote_url));
1767 if (error.Success())
1768 {
1769 SetNextEventAction(new Process::AttachCompletionHandler(this));
1770 StartPrivateStateThread();
1771// TimeValue timeout;
1772// timeout = TimeValue::Now();
1773// timeout.OffsetWithMicroSeconds(000);
1774// EventSP event_sp;
1775// StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1776//
1777// if (state == eStateStopped || state == eStateCrashed)
1778// {
1779// DidLaunch ();
1780//
1781// // This delays passing the stopped event to listeners till DidLaunch gets
1782// // a chance to complete...
1783// HandlePrivateEvent (event_sp);
1784// StartPrivateStateThread ();
1785// }
1786// else if (state == eStateExited)
1787// {
1788// // We exited while trying to launch somehow. Don't call DidLaunch as that's
1789// // not likely to work, and return an invalid pid.
1790// HandlePrivateEvent (event_sp);
1791// }
1792//
1793// StartPrivateStateThread();
1794 }
1795 return error;
1796}
1797
1798
1799Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001800Process::Resume ()
1801{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001802 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00001804 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1805 m_stop_id,
1806 StateAsCString(m_public_state.GetValue()),
1807 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808
1809 Error error (WillResume());
1810 // Tell the process it is about to resume before the thread list
1811 if (error.Success())
1812 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001813 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001814 // can let all of our threads know that they are about to be
1815 // resumed. Threads will each be called with
1816 // Thread::WillResume(StateType) where StateType contains the state
1817 // that they are supposed to have when the process is resumed
1818 // (suspended/running/stepping). Threads should also check
1819 // their resume signal in lldb::Thread::GetResumeSignal()
1820 // to see if they are suppoed to start back up with a signal.
1821 if (m_thread_list.WillResume())
1822 {
1823 error = DoResume();
1824 if (error.Success())
1825 {
1826 DidResume();
1827 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00001828 if (log)
1829 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 }
1831 }
1832 else
1833 {
Jim Ingham444586b2011-01-24 06:34:17 +00001834 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
1836 }
Jim Ingham444586b2011-01-24 06:34:17 +00001837 else if (log)
1838 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001839 return error;
1840}
1841
1842Error
1843Process::Halt ()
1844{
Jim Inghambb3a2832011-01-29 01:49:25 +00001845 // Pause our private state thread so we can ensure no one else eats
1846 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00001847 Listener halt_listener ("lldb.process.halt_listener");
1848 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001849
Jim Inghambb3a2832011-01-29 01:49:25 +00001850 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00001851 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00001852
Greg Clayton513c26c2011-01-29 07:10:55 +00001853 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00001854 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001855
Greg Clayton513c26c2011-01-29 07:10:55 +00001856 bool caused_stop = false;
1857
1858 // Ask the process subclass to actually halt our process
1859 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001861 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001862 if (m_public_state.GetValue() == eStateAttaching)
1863 {
1864 SetExitStatus(SIGKILL, "Cancelled async attach.");
1865 Destroy ();
1866 }
1867 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001868 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001869 // If "caused_stop" is true, then DoHalt stopped the process. If
1870 // "caused_stop" is false, the process was already stopped.
1871 // If the DoHalt caused the process to stop, then we want to catch
1872 // this event and set the interrupted bool to true before we pass
1873 // this along so clients know that the process was interrupted by
1874 // a halt command.
1875 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001876 {
Jim Ingham0f16e732011-02-08 05:20:59 +00001877 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00001878 TimeValue timeout_time;
1879 timeout_time = TimeValue::Now();
1880 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00001881 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1882 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00001883
Jim Ingham0f16e732011-02-08 05:20:59 +00001884 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001885 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001886 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00001887 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00001888 }
1889 else
1890 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001891 if (StateIsStoppedState (state))
1892 {
1893 // We caused the process to interrupt itself, so mark this
1894 // as such in the stop event so clients can tell an interrupted
1895 // process from a natural stop
1896 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1897 }
1898 else
1899 {
1900 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1901 if (log)
1902 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1903 error.SetErrorString ("Did not get stopped event after halt.");
1904 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001905 }
1906 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001907 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001908 }
1909 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001910 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001911 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00001912 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00001913
1914 // Post any event we might have consumed. If all goes well, we will have
1915 // stopped the process, intercepted the event and set the interrupted
1916 // bool in the event. Post it to the private event queue and that will end up
1917 // correctly setting the state.
1918 if (event_sp)
1919 m_private_state_broadcaster.BroadcastEvent(event_sp);
1920
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921 return error;
1922}
1923
1924Error
1925Process::Detach ()
1926{
1927 Error error (WillDetach());
1928
1929 if (error.Success())
1930 {
1931 DisableAllBreakpointSites();
1932 error = DoDetach();
1933 if (error.Success())
1934 {
1935 DidDetach();
1936 StopPrivateStateThread();
1937 }
1938 }
1939 return error;
1940}
1941
1942Error
1943Process::Destroy ()
1944{
1945 Error error (WillDestroy());
1946 if (error.Success())
1947 {
1948 DisableAllBreakpointSites();
1949 error = DoDestroy();
1950 if (error.Success())
1951 {
1952 DidDestroy();
1953 StopPrivateStateThread();
1954 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001955 m_stdio_communication.StopReadThread();
1956 m_stdio_communication.Disconnect();
1957 if (m_process_input_reader && m_process_input_reader->IsActive())
1958 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1959 if (m_process_input_reader)
1960 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001961 }
1962 return error;
1963}
1964
1965Error
1966Process::Signal (int signal)
1967{
1968 Error error (WillSignal());
1969 if (error.Success())
1970 {
1971 error = DoSignal(signal);
1972 if (error.Success())
1973 DidSignal();
1974 }
1975 return error;
1976}
1977
1978UnixSignals &
1979Process::GetUnixSignals ()
1980{
1981 return m_unix_signals;
1982}
1983
1984Target &
1985Process::GetTarget ()
1986{
1987 return m_target;
1988}
1989
1990const Target &
1991Process::GetTarget () const
1992{
1993 return m_target;
1994}
1995
1996uint32_t
1997Process::GetAddressByteSize()
1998{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001999 if (m_addr_byte_size == 0)
2000 return m_target.GetArchitecture().GetAddressByteSize();
2001 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002}
2003
2004bool
2005Process::ShouldBroadcastEvent (Event *event_ptr)
2006{
2007 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2008 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002009 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010
2011 switch (state)
2012 {
Greg Claytonb766a732011-02-04 01:58:07 +00002013 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 case eStateAttaching:
2015 case eStateLaunching:
2016 case eStateDetached:
2017 case eStateExited:
2018 case eStateUnloaded:
2019 // These events indicate changes in the state of the debugging session, always report them.
2020 return_value = true;
2021 break;
2022 case eStateInvalid:
2023 // We stopped for no apparent reason, don't report it.
2024 return_value = false;
2025 break;
2026 case eStateRunning:
2027 case eStateStepping:
2028 // If we've started the target running, we handle the cases where we
2029 // are already running and where there is a transition from stopped to
2030 // running differently.
2031 // running -> running: Automatically suppress extra running events
2032 // stopped -> running: Report except when there is one or more no votes
2033 // and no yes votes.
2034 SynchronouslyNotifyStateChanged (state);
2035 switch (m_public_state.GetValue())
2036 {
2037 case eStateRunning:
2038 case eStateStepping:
2039 // We always suppress multiple runnings with no PUBLIC stop in between.
2040 return_value = false;
2041 break;
2042 default:
2043 // TODO: make this work correctly. For now always report
2044 // run if we aren't running so we don't miss any runnning
2045 // events. If I run the lldb/test/thread/a.out file and
2046 // break at main.cpp:58, run and hit the breakpoints on
2047 // multiple threads, then somehow during the stepping over
2048 // of all breakpoints no run gets reported.
2049 return_value = true;
2050
2051 // This is a transition from stop to run.
2052 switch (m_thread_list.ShouldReportRun (event_ptr))
2053 {
2054 case eVoteYes:
2055 case eVoteNoOpinion:
2056 return_value = true;
2057 break;
2058 case eVoteNo:
2059 return_value = false;
2060 break;
2061 }
2062 break;
2063 }
2064 break;
2065 case eStateStopped:
2066 case eStateCrashed:
2067 case eStateSuspended:
2068 {
2069 // We've stopped. First see if we're going to restart the target.
2070 // If we are going to stop, then we always broadcast the event.
2071 // 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 +00002072 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002073 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002075 if (log)
2076 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002077 return true;
2078 }
2079 else
2080 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081 RefreshStateAfterStop ();
2082
2083 if (m_thread_list.ShouldStop (event_ptr) == false)
2084 {
2085 switch (m_thread_list.ShouldReportStop (event_ptr))
2086 {
2087 case eVoteYes:
2088 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002089 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002091 case eVoteNo:
2092 return_value = false;
2093 break;
2094 }
2095
2096 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002097 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 Resume ();
2099 }
2100 else
2101 {
2102 return_value = true;
2103 SynchronouslyNotifyStateChanged (state);
2104 }
2105 }
2106 }
2107 }
2108
2109 if (log)
2110 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2111 return return_value;
2112}
2113
2114//------------------------------------------------------------------
2115// Thread Queries
2116//------------------------------------------------------------------
2117
2118ThreadList &
2119Process::GetThreadList ()
2120{
2121 return m_thread_list;
2122}
2123
2124const ThreadList &
2125Process::GetThreadList () const
2126{
2127 return m_thread_list;
2128}
2129
2130
2131bool
2132Process::StartPrivateStateThread ()
2133{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002134 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135
2136 if (log)
2137 log->Printf ("Process::%s ( )", __FUNCTION__);
2138
2139 // Create a thread that watches our internal state and controls which
2140 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002141 char thread_name[1024];
2142 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2143 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002144 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145}
2146
2147void
2148Process::PausePrivateStateThread ()
2149{
2150 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2151}
2152
2153void
2154Process::ResumePrivateStateThread ()
2155{
2156 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2157}
2158
2159void
2160Process::StopPrivateStateThread ()
2161{
2162 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2163}
2164
2165void
2166Process::ControlPrivateStateThread (uint32_t signal)
2167{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002168 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169
2170 assert (signal == eBroadcastInternalStateControlStop ||
2171 signal == eBroadcastInternalStateControlPause ||
2172 signal == eBroadcastInternalStateControlResume);
2173
2174 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002175 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002177 // Signal the private state thread. First we should copy this is case the
2178 // thread starts exiting since the private state thread will NULL this out
2179 // when it exits
2180 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002181 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182 {
2183 TimeValue timeout_time;
2184 bool timed_out;
2185
2186 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2187
2188 timeout_time = TimeValue::Now();
2189 timeout_time.OffsetWithSeconds(2);
2190 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2191 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2192
2193 if (signal == eBroadcastInternalStateControlStop)
2194 {
2195 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002196 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197
2198 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002199 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002200 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201 }
2202 }
2203}
2204
2205void
2206Process::HandlePrivateEvent (EventSP &event_sp)
2207{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002208 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002209
Greg Clayton414f5d32011-01-25 02:58:48 +00002210 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002211
2212 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002213 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002214 {
Jim Ingham754ab982011-01-29 04:05:41 +00002215 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002216 switch (action_result)
2217 {
2218 case NextEventAction::eEventActionSuccess:
2219 SetNextEventAction(NULL);
2220 break;
2221 case NextEventAction::eEventActionRetry:
2222 break;
2223 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002224 // Handle Exiting Here. If we already got an exited event,
2225 // we should just propagate it. Otherwise, swallow this event,
2226 // and set our state to exit so the next event will kill us.
2227 if (new_state != eStateExited)
2228 {
2229 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002230 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002231 SetNextEventAction(NULL);
2232 return;
2233 }
2234 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002235 break;
2236 }
2237 }
2238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 // See if we should broadcast this state to external clients?
2240 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241
2242 if (should_broadcast)
2243 {
2244 if (log)
2245 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002246 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2247 __FUNCTION__,
2248 GetID(),
2249 StateAsCString(new_state),
2250 StateAsCString (GetState ()),
2251 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252 }
Greg Clayton414f5d32011-01-25 02:58:48 +00002253 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002254 PushProcessInputReader ();
2255 else
2256 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002257 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2258 BroadcastEvent (event_sp);
2259 }
2260 else
2261 {
2262 if (log)
2263 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002264 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2265 __FUNCTION__,
2266 GetID(),
2267 StateAsCString(new_state),
2268 StateAsCString (GetState ()),
2269 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 }
2271 }
2272}
2273
2274void *
2275Process::PrivateStateThread (void *arg)
2276{
2277 Process *proc = static_cast<Process*> (arg);
2278 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 return result;
2280}
2281
2282void *
2283Process::RunPrivateStateThread ()
2284{
2285 bool control_only = false;
2286 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2287
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002288 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 if (log)
2290 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2291
2292 bool exit_now = false;
2293 while (!exit_now)
2294 {
2295 EventSP event_sp;
2296 WaitForEventsPrivate (NULL, event_sp, control_only);
2297 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2298 {
2299 switch (event_sp->GetType())
2300 {
2301 case eBroadcastInternalStateControlStop:
2302 exit_now = true;
2303 continue; // Go to next loop iteration so we exit without
2304 break; // doing any internal state managment below
2305
2306 case eBroadcastInternalStateControlPause:
2307 control_only = true;
2308 break;
2309
2310 case eBroadcastInternalStateControlResume:
2311 control_only = false;
2312 break;
2313 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002314
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002315 if (log)
2316 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2317
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002319 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002320 }
2321
2322
2323 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2324
2325 if (internal_state != eStateInvalid)
2326 {
2327 HandlePrivateEvent (event_sp);
2328 }
2329
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002330 if (internal_state == eStateInvalid ||
2331 internal_state == eStateExited ||
2332 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002333 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002334 if (log)
2335 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2336
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002338 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 }
2340
Caroline Tice20ad3c42010-10-29 21:48:37 +00002341 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342 if (log)
2343 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2344
Greg Clayton6ed95942011-01-22 07:12:45 +00002345 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2346 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 return NULL;
2348}
2349
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350//------------------------------------------------------------------
2351// Process Event Data
2352//------------------------------------------------------------------
2353
2354Process::ProcessEventData::ProcessEventData () :
2355 EventData (),
2356 m_process_sp (),
2357 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002358 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002359 m_update_state (false),
2360 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361{
2362}
2363
2364Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2365 EventData (),
2366 m_process_sp (process_sp),
2367 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002368 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002369 m_update_state (false),
2370 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371{
2372}
2373
2374Process::ProcessEventData::~ProcessEventData()
2375{
2376}
2377
2378const ConstString &
2379Process::ProcessEventData::GetFlavorString ()
2380{
2381 static ConstString g_flavor ("Process::ProcessEventData");
2382 return g_flavor;
2383}
2384
2385const ConstString &
2386Process::ProcessEventData::GetFlavor () const
2387{
2388 return ProcessEventData::GetFlavorString ();
2389}
2390
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002391void
2392Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2393{
2394 // This function gets called twice for each event, once when the event gets pulled
2395 // off of the private process event queue, and once when it gets pulled off of
2396 // the public event queue. m_update_state is used to distinguish these
2397 // two cases; it is false when we're just pulling it off for private handling,
2398 // and we don't want to do the breakpoint command handling then.
2399
2400 if (!m_update_state)
2401 return;
2402
2403 m_process_sp->SetPublicState (m_state);
2404
2405 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2406 if (m_state == eStateStopped && ! m_restarted)
2407 {
2408 int num_threads = m_process_sp->GetThreadList().GetSize();
2409 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002410
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 for (idx = 0; idx < num_threads; ++idx)
2412 {
2413 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2414
Jim Inghamb15bfc72010-10-20 00:39:53 +00002415 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2416 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002418 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002419 }
2420 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002421
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002422 // The stop action might restart the target. If it does, then we want to mark that in the
2423 // event so that whoever is receiving it will know to wait for the running event and reflect
2424 // that state appropriately.
2425
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426 if (m_process_sp->GetPrivateState() == eStateRunning)
2427 SetRestarted(true);
2428 }
2429}
2430
2431void
2432Process::ProcessEventData::Dump (Stream *s) const
2433{
2434 if (m_process_sp)
2435 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2436
2437 s->Printf("state = %s", StateAsCString(GetState()));;
2438}
2439
2440const Process::ProcessEventData *
2441Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2442{
2443 if (event_ptr)
2444 {
2445 const EventData *event_data = event_ptr->GetData();
2446 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2447 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2448 }
2449 return NULL;
2450}
2451
2452ProcessSP
2453Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2454{
2455 ProcessSP process_sp;
2456 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2457 if (data)
2458 process_sp = data->GetProcessSP();
2459 return process_sp;
2460}
2461
2462StateType
2463Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2464{
2465 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2466 if (data == NULL)
2467 return eStateInvalid;
2468 else
2469 return data->GetState();
2470}
2471
2472bool
2473Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2474{
2475 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2476 if (data == NULL)
2477 return false;
2478 else
2479 return data->GetRestarted();
2480}
2481
2482void
2483Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2484{
2485 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2486 if (data != NULL)
2487 data->SetRestarted(new_value);
2488}
2489
2490bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002491Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2492{
2493 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2494 if (data == NULL)
2495 return false;
2496 else
2497 return data->GetInterrupted ();
2498}
2499
2500void
2501Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2502{
2503 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2504 if (data != NULL)
2505 data->SetInterrupted(new_value);
2506}
2507
2508bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2510{
2511 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2512 if (data)
2513 {
2514 data->SetUpdateStateOnRemoval();
2515 return true;
2516 }
2517 return false;
2518}
2519
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520Target *
2521Process::CalculateTarget ()
2522{
2523 return &m_target;
2524}
2525
2526Process *
2527Process::CalculateProcess ()
2528{
2529 return this;
2530}
2531
2532Thread *
2533Process::CalculateThread ()
2534{
2535 return NULL;
2536}
2537
2538StackFrame *
2539Process::CalculateStackFrame ()
2540{
2541 return NULL;
2542}
2543
2544void
Greg Clayton0603aa92010-10-04 01:05:56 +00002545Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002546{
2547 exe_ctx.target = &m_target;
2548 exe_ctx.process = this;
2549 exe_ctx.thread = NULL;
2550 exe_ctx.frame = NULL;
2551}
2552
2553lldb::ProcessSP
2554Process::GetSP ()
2555{
2556 return GetTarget().GetProcessSP();
2557}
2558
Jim Ingham5aee1622010-08-09 23:31:02 +00002559uint32_t
2560Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2561{
2562 return 0;
2563}
2564
2565ArchSpec
2566Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2567{
2568 return Host::GetArchSpecForExistingProcess (pid);
2569}
2570
2571ArchSpec
2572Process::GetArchSpecForExistingProcess (const char *process_name)
2573{
2574 return Host::GetArchSpecForExistingProcess (process_name);
2575}
2576
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002577void
2578Process::AppendSTDOUT (const char * s, size_t len)
2579{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002580 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002581 m_stdout_data.append (s, len);
2582
Greg Claytona9ff3062010-12-05 19:16:56 +00002583 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002584}
2585
2586void
2587Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2588{
2589 Process *process = (Process *) baton;
2590 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2591}
2592
2593size_t
2594Process::ProcessInputReaderCallback (void *baton,
2595 InputReader &reader,
2596 lldb::InputReaderAction notification,
2597 const char *bytes,
2598 size_t bytes_len)
2599{
2600 Process *process = (Process *) baton;
2601
2602 switch (notification)
2603 {
2604 case eInputReaderActivate:
2605 break;
2606
2607 case eInputReaderDeactivate:
2608 break;
2609
2610 case eInputReaderReactivate:
2611 break;
2612
2613 case eInputReaderGotToken:
2614 {
2615 Error error;
2616 process->PutSTDIN (bytes, bytes_len, error);
2617 }
2618 break;
2619
Caroline Ticeefed6132010-11-19 20:47:54 +00002620 case eInputReaderInterrupt:
2621 process->Halt ();
2622 break;
2623
2624 case eInputReaderEndOfFile:
2625 process->AppendSTDOUT ("^D", 2);
2626 break;
2627
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002628 case eInputReaderDone:
2629 break;
2630
2631 }
2632
2633 return bytes_len;
2634}
2635
2636void
2637Process::ResetProcessInputReader ()
2638{
2639 m_process_input_reader.reset();
2640}
2641
2642void
2643Process::SetUpProcessInputReader (int file_descriptor)
2644{
2645 // First set up the Read Thread for reading/handling process I/O
2646
2647 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2648
2649 if (conn_ap.get())
2650 {
2651 m_stdio_communication.SetConnection (conn_ap.release());
2652 if (m_stdio_communication.IsConnected())
2653 {
2654 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2655 m_stdio_communication.StartReadThread();
2656
2657 // Now read thread is set up, set up input reader.
2658
2659 if (!m_process_input_reader.get())
2660 {
2661 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2662 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2663 this,
2664 eInputReaderGranularityByte,
2665 NULL,
2666 NULL,
2667 false));
2668
2669 if (err.Fail())
2670 m_process_input_reader.reset();
2671 }
2672 }
2673 }
2674}
2675
2676void
2677Process::PushProcessInputReader ()
2678{
2679 if (m_process_input_reader && !m_process_input_reader->IsActive())
2680 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2681}
2682
2683void
2684Process::PopProcessInputReader ()
2685{
2686 if (m_process_input_reader && m_process_input_reader->IsActive())
2687 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2688}
2689
Greg Clayton99d0faf2010-11-18 23:32:35 +00002690
2691void
2692Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002693{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002694 UserSettingsControllerSP &usc = GetSettingsController();
2695 usc.reset (new SettingsController);
2696 UserSettingsController::InitializeSettingsController (usc,
2697 SettingsController::global_settings_table,
2698 SettingsController::instance_settings_table);
2699}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002700
Greg Clayton99d0faf2010-11-18 23:32:35 +00002701void
2702Process::Terminate ()
2703{
2704 UserSettingsControllerSP &usc = GetSettingsController();
2705 UserSettingsController::FinalizeSettingsController (usc);
2706 usc.reset();
2707}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002708
Greg Clayton99d0faf2010-11-18 23:32:35 +00002709UserSettingsControllerSP &
2710Process::GetSettingsController ()
2711{
2712 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002713 return g_settings_controller;
2714}
2715
Caroline Tice1559a462010-09-27 00:30:10 +00002716void
2717Process::UpdateInstanceName ()
2718{
2719 ModuleSP module_sp = GetTarget().GetExecutableModule();
2720 if (module_sp)
2721 {
2722 StreamString sstr;
2723 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2724
Greg Claytondbe54502010-11-19 03:46:01 +00002725 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002726 sstr.GetData());
2727 }
2728}
2729
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002730ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002731Process::RunThreadPlan (ExecutionContext &exe_ctx,
2732 lldb::ThreadPlanSP &thread_plan_sp,
2733 bool stop_others,
2734 bool try_all_threads,
2735 bool discard_on_error,
2736 uint32_t single_thread_timeout_usec,
2737 Stream &errors)
2738{
2739 ExecutionResults return_value = eExecutionSetupError;
2740
Jim Ingham77787032011-01-20 02:03:18 +00002741 if (thread_plan_sp.get() == NULL)
2742 {
2743 errors.Printf("RunThreadPlan called with empty thread plan.");
2744 return lldb::eExecutionSetupError;
2745 }
2746
Jim Ingham444586b2011-01-24 06:34:17 +00002747 if (m_private_state.GetValue() != eStateStopped)
2748 {
2749 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham0f16e732011-02-08 05:20:59 +00002750 return lldb::eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00002751 }
2752
Jim Inghamf48169b2010-11-30 02:22:11 +00002753 // Save this value for restoration of the execution context after we run
2754 uint32_t tid = exe_ctx.thread->GetIndexID();
2755
2756 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2757 // so we should arrange to reset them as well.
2758
2759 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2760 lldb::StackFrameSP selected_frame_sp;
2761
2762 uint32_t selected_tid;
2763 if (selected_thread_sp != NULL)
2764 {
2765 selected_tid = selected_thread_sp->GetIndexID();
2766 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2767 }
2768 else
2769 {
2770 selected_tid = LLDB_INVALID_THREAD_ID;
2771 }
2772
2773 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2774
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002775 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00002776
2777 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2778 // restored on exit to the function.
2779
2780 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00002781
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002782 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00002783 if (log)
2784 {
2785 StreamString s;
2786 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham0f16e732011-02-08 05:20:59 +00002787 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2788 exe_ctx.thread->GetIndexID(),
2789 exe_ctx.thread->GetID(),
2790 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00002791 }
2792
Jim Ingham0f16e732011-02-08 05:20:59 +00002793 bool got_event;
2794 lldb::EventSP event_sp;
2795 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00002796
2797 TimeValue* timeout_ptr = NULL;
2798 TimeValue real_timeout;
2799
Jim Ingham0f16e732011-02-08 05:20:59 +00002800 bool first_timeout = true;
2801 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00002802
Jim Inghamf48169b2010-11-30 02:22:11 +00002803 while (1)
2804 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002805 // We usually want to resume the process if we get to the top of the loop.
2806 // The only exception is if we get two running events with no intervening
2807 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00002808
Jim Ingham0f16e732011-02-08 05:20:59 +00002809 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00002810 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002811 // Do the initial resume and wait for the running event before going further.
2812
2813 Error resume_error = exe_ctx.process->Resume ();
2814 if (!resume_error.Success())
2815 {
2816 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2817 return_value = lldb::eExecutionSetupError;
2818 break;
2819 }
2820
2821 real_timeout = TimeValue::Now();
2822 real_timeout.OffsetWithMicroSeconds(500000);
2823 timeout_ptr = &real_timeout;
2824
2825 got_event = listener.WaitForEvent(NULL, event_sp);
2826 if (!got_event)
2827 {
2828 if (log)
2829 log->Printf("Didn't get any event after initial resume, exiting.");
2830
2831 errors.Printf("Didn't get any event after initial resume, exiting.");
2832 return_value = lldb::eExecutionSetupError;
2833 break;
2834 }
2835
2836 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2837 if (stop_state != eStateRunning)
2838 {
2839 if (log)
2840 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2841
2842 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2843 return_value = lldb::eExecutionSetupError;
2844 break;
2845 }
2846
2847 if (log)
2848 log->Printf ("Resuming succeeded.");
2849 // We need to call the function synchronously, so spin waiting for it to return.
2850 // If we get interrupted while executing, we're going to lose our context, and
2851 // won't be able to gather the result at this point.
2852 // We set the timeout AFTER the resume, since the resume takes some time and we
2853 // don't want to charge that to the timeout.
2854
2855 if (single_thread_timeout_usec != 0)
2856 {
2857 real_timeout = TimeValue::Now();
2858 if (first_timeout)
2859 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2860 else
2861 real_timeout.OffsetWithSeconds(10);
2862
2863 timeout_ptr = &real_timeout;
2864 }
2865 }
2866 else
2867 {
2868 if (log)
2869 log->Printf ("Handled an extra running event.");
2870 do_resume = true;
2871 }
2872
2873 // Now wait for the process to stop again:
2874 stop_state = lldb::eStateInvalid;
2875 event_sp.reset();
2876 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2877
2878 if (got_event)
2879 {
2880 if (event_sp.get())
2881 {
2882 bool keep_going = false;
2883 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2884 if (log)
2885 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2886
2887 switch (stop_state)
2888 {
2889 case lldb::eStateStopped:
2890 // Yay, we're done.
2891 if (log)
2892 log->Printf ("Execution completed successfully.");
2893 return_value = lldb::eExecutionCompleted;
2894 break;
2895 case lldb::eStateCrashed:
2896 if (log)
2897 log->Printf ("Execution crashed.");
2898 return_value = lldb::eExecutionInterrupted;
2899 break;
2900 case lldb::eStateRunning:
2901 do_resume = false;
2902 keep_going = true;
2903 break;
2904 default:
2905 if (log)
2906 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
2907 return_value = lldb::eExecutionInterrupted;
2908 break;
2909 }
2910 if (keep_going)
2911 continue;
2912 else
2913 break;
2914 }
2915 else
2916 {
2917 if (log)
2918 log->Printf ("got_event was true, but the event pointer was null. How odd...");
2919 return_value = lldb::eExecutionInterrupted;
2920 break;
2921 }
2922 }
2923 else
2924 {
2925 // If we didn't get an event that means we've timed out...
2926 // We will interrupt the process here. Depending on what we were asked to do we will
2927 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00002928 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00002929
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002930 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002931 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00002932 {
2933 if (first_timeout)
2934 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2935 "trying with all threads enabled.",
2936 single_thread_timeout_usec);
2937 else
2938 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2939 "and timeout: %d timed out.",
2940 single_thread_timeout_usec);
2941 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002942 else
Jim Ingham0f16e732011-02-08 05:20:59 +00002943 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2944 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002945 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002946 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002947
Jim Inghame22e88b2011-01-22 01:30:53 +00002948 Error halt_error = exe_ctx.process->Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00002949 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002950 {
Jim Inghamf48169b2010-11-30 02:22:11 +00002951 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002952 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002953
Jim Ingham0f16e732011-02-08 05:20:59 +00002954 // If halt succeeds, it always produces a stopped event. Wait for that:
2955
2956 real_timeout = TimeValue::Now();
2957 real_timeout.OffsetWithMicroSeconds(500000);
2958
2959 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00002960
2961 if (got_event)
2962 {
2963 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2964 if (log)
2965 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002966 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00002967 if (stop_state == lldb::eStateStopped
2968 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00002969 log->Printf (" Event was the Halt interruption event.");
2970 }
2971
Jim Ingham0f16e732011-02-08 05:20:59 +00002972 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00002973 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002974 // Between the time we initiated the Halt and the time we delivered it, the process could have
2975 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00002976
Jim Ingham0f16e732011-02-08 05:20:59 +00002977 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2978 {
2979 if (log)
2980 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
2981 "Exiting wait loop.");
2982 return_value = lldb::eExecutionCompleted;
2983 break;
2984 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002985
Jim Ingham0f16e732011-02-08 05:20:59 +00002986 if (!try_all_threads)
2987 {
2988 if (log)
2989 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
2990 return_value = lldb::eExecutionInterrupted;
2991 break;
2992 }
2993
2994 if (first_timeout)
2995 {
2996 // Set all the other threads to run, and return to the top of the loop, which will continue;
2997 first_timeout = false;
2998 thread_plan_sp->SetStopOthers (false);
2999 if (log)
3000 log->Printf ("Process::RunThreadPlan(): About to resume.");
3001
3002 continue;
3003 }
3004 else
3005 {
3006 // Running all threads failed, so return Interrupted.
3007 if (log)
3008 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3009 return_value = lldb::eExecutionInterrupted;
3010 break;
3011 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003012 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003013 }
3014 else
3015 { if (log)
3016 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
3017 "I'm getting out of here passing Interrupted.");
3018 return_value = lldb::eExecutionInterrupted;
3019 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003020 }
3021 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003022 else
3023 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003024 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3025 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003026 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003027 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.",
3028 halt_error.AsCString());
3029 real_timeout = TimeValue::Now();
3030 real_timeout.OffsetWithMicroSeconds(500000);
3031 timeout_ptr = &real_timeout;
3032 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3033 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003034 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003035 // This is not going anywhere, bag out.
3036 if (log)
3037 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
3038 return_value = lldb::eExecutionInterrupted;
3039 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003040 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003041 else
3042 {
3043 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3044 if (log)
3045 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3046 if (stop_state == lldb::eStateStopped)
3047 {
3048 // Between the time we initiated the Halt and the time we delivered it, the process could have
3049 // already finished its job. Check that here:
3050
3051 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3052 {
3053 if (log)
3054 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3055 "Exiting wait loop.");
3056 return_value = lldb::eExecutionCompleted;
3057 break;
3058 }
3059
3060 if (first_timeout)
3061 {
3062 // Set all the other threads to run, and return to the top of the loop, which will continue;
3063 first_timeout = false;
3064 thread_plan_sp->SetStopOthers (false);
3065 if (log)
3066 log->Printf ("Process::RunThreadPlan(): About to resume.");
3067
3068 continue;
3069 }
3070 else
3071 {
3072 // Running all threads failed, so return Interrupted.
3073 if (log)
3074 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3075 return_value = lldb::eExecutionInterrupted;
3076 break;
3077 }
3078 }
3079 else
3080 {
3081 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3082 " a stopped event, instead got %s.", StateAsCString(stop_state));
3083 return_value = lldb::eExecutionInterrupted;
3084 break;
3085 }
3086 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003087 }
3088
Jim Inghamf48169b2010-11-30 02:22:11 +00003089 }
3090
Jim Ingham0f16e732011-02-08 05:20:59 +00003091 } // END WAIT LOOP
3092
3093 // Now do some processing on the results of the run:
3094 if (return_value == eExecutionInterrupted)
3095 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003096 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003097 {
3098 StreamString s;
3099 if (event_sp)
3100 event_sp->Dump (&s);
3101 else
3102 {
3103 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3104 }
3105
3106 StreamString ts;
3107
3108 const char *event_explanation;
3109
3110 do
3111 {
3112 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3113
3114 if (!event_data)
3115 {
3116 event_explanation = "<no event data>";
3117 break;
3118 }
3119
3120 Process *process = event_data->GetProcessSP().get();
3121
3122 if (!process)
3123 {
3124 event_explanation = "<no process>";
3125 break;
3126 }
3127
3128 ThreadList &thread_list = process->GetThreadList();
3129
3130 uint32_t num_threads = thread_list.GetSize();
3131 uint32_t thread_index;
3132
3133 ts.Printf("<%u threads> ", num_threads);
3134
3135 for (thread_index = 0;
3136 thread_index < num_threads;
3137 ++thread_index)
3138 {
3139 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3140
3141 if (!thread)
3142 {
3143 ts.Printf("<?> ");
3144 continue;
3145 }
3146
3147 ts.Printf("<0x%4.4x ", thread->GetID());
3148 RegisterContext *register_context = thread->GetRegisterContext().get();
3149
3150 if (register_context)
3151 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3152 else
3153 ts.Printf("[ip unknown] ");
3154
3155 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3156 if (stop_info_sp)
3157 {
3158 const char *stop_desc = stop_info_sp->GetDescription();
3159 if (stop_desc)
3160 ts.PutCString (stop_desc);
3161 }
3162 ts.Printf(">");
3163 }
3164
3165 event_explanation = ts.GetData();
3166 } while (0);
3167
3168 if (log)
3169 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3170
3171 if (discard_on_error && thread_plan_sp)
3172 {
3173 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3174 }
3175 }
3176 }
3177 else if (return_value == eExecutionSetupError)
3178 {
3179 if (log)
3180 log->Printf("Process::RunThreadPlan(): execution set up error.");
3181
3182 if (discard_on_error && thread_plan_sp)
3183 {
3184 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3185 }
3186 }
3187 else
3188 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003189 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3190 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003191 if (log)
3192 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003193 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003194 }
3195 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3196 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003197 if (log)
3198 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003199 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003200 }
3201 else
3202 {
3203 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003204 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003205 if (discard_on_error && thread_plan_sp)
3206 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003207 if (log)
3208 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003209 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3210 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003211 }
3212 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003213
Jim Inghamf48169b2010-11-30 02:22:11 +00003214 // Thread we ran the function in may have gone away because we ran the target
3215 // Check that it's still there.
3216 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3217 if (exe_ctx.thread)
3218 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3219
3220 // Also restore the current process'es selected frame & thread, since this function calling may
3221 // be done behind the user's back.
3222
3223 if (selected_tid != LLDB_INVALID_THREAD_ID)
3224 {
3225 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3226 {
3227 // We were able to restore the selected thread, now restore the frame:
3228 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3229 }
3230 }
3231
3232 return return_value;
3233}
3234
3235const char *
3236Process::ExecutionResultAsCString (ExecutionResults result)
3237{
3238 const char *result_name;
3239
3240 switch (result)
3241 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003242 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003243 result_name = "eExecutionCompleted";
3244 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003245 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003246 result_name = "eExecutionDiscarded";
3247 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003248 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003249 result_name = "eExecutionInterrupted";
3250 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003251 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003252 result_name = "eExecutionSetupError";
3253 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003254 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003255 result_name = "eExecutionTimedOut";
3256 break;
3257 }
3258 return result_name;
3259}
3260
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003261//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003262// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003263//--------------------------------------------------------------
3264
Greg Clayton1b654882010-09-19 02:33:57 +00003265Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00003266 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003267{
Greg Clayton85851dd2010-12-04 00:10:17 +00003268 m_default_settings.reset (new ProcessInstanceSettings (*this,
3269 false,
Caroline Tice91123da2010-09-08 17:48:55 +00003270 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003271}
3272
Greg Clayton1b654882010-09-19 02:33:57 +00003273Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003274{
3275}
3276
3277lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00003278Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003279{
Greg Claytondbe54502010-11-19 03:46:01 +00003280 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3281 false,
3282 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003283 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3284 return new_settings_sp;
3285}
3286
3287//--------------------------------------------------------------
3288// class ProcessInstanceSettings
3289//--------------------------------------------------------------
3290
Greg Clayton85851dd2010-12-04 00:10:17 +00003291ProcessInstanceSettings::ProcessInstanceSettings
3292(
3293 UserSettingsController &owner,
3294 bool live_instance,
3295 const char *name
3296) :
3297 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003298 m_run_args (),
3299 m_env_vars (),
3300 m_input_path (),
3301 m_output_path (),
3302 m_error_path (),
3303 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00003304 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00003305 m_disable_stdio (false),
3306 m_inherit_host_env (true),
3307 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003308{
Caroline Ticef20e8232010-09-09 18:26:37 +00003309 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3310 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3311 // 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 +00003312 // This is true for CreateInstanceName() too.
3313
3314 if (GetInstanceName () == InstanceSettings::InvalidName())
3315 {
3316 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3317 m_owner.RegisterInstanceSettings (this);
3318 }
Caroline Ticef20e8232010-09-09 18:26:37 +00003319
3320 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003321 {
3322 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3323 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00003324 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003325 }
3326}
3327
3328ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00003329 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003330 m_run_args (rhs.m_run_args),
3331 m_env_vars (rhs.m_env_vars),
3332 m_input_path (rhs.m_input_path),
3333 m_output_path (rhs.m_output_path),
3334 m_error_path (rhs.m_error_path),
3335 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00003336 m_disable_aslr (rhs.m_disable_aslr),
3337 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003338{
3339 if (m_instance_name != InstanceSettings::GetDefaultName())
3340 {
3341 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3342 CopyInstanceSettings (pending_settings,false);
3343 m_owner.RemovePendingSettings (m_instance_name);
3344 }
3345}
3346
3347ProcessInstanceSettings::~ProcessInstanceSettings ()
3348{
3349}
3350
3351ProcessInstanceSettings&
3352ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3353{
3354 if (this != &rhs)
3355 {
3356 m_run_args = rhs.m_run_args;
3357 m_env_vars = rhs.m_env_vars;
3358 m_input_path = rhs.m_input_path;
3359 m_output_path = rhs.m_output_path;
3360 m_error_path = rhs.m_error_path;
3361 m_plugin = rhs.m_plugin;
3362 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003363 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00003364 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003365 }
3366
3367 return *this;
3368}
3369
3370
3371void
3372ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3373 const char *index_value,
3374 const char *value,
3375 const ConstString &instance_name,
3376 const SettingEntry &entry,
3377 lldb::VarSetOperationType op,
3378 Error &err,
3379 bool pending)
3380{
3381 if (var_name == RunArgsVarName())
3382 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3383 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003384 {
3385 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003386 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003387 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003388 else if (var_name == InputPathVarName())
3389 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3390 else if (var_name == OutputPathVarName())
3391 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3392 else if (var_name == ErrorPathVarName())
3393 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3394 else if (var_name == PluginVarName())
3395 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003396 else if (var_name == InheritHostEnvVarName())
3397 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003398 else if (var_name == DisableASLRVarName())
3399 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003400 else if (var_name == DisableSTDIOVarName ())
3401 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003402}
3403
3404void
3405ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3406 bool pending)
3407{
3408 if (new_settings.get() == NULL)
3409 return;
3410
3411 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3412
3413 m_run_args = new_process_settings->m_run_args;
3414 m_env_vars = new_process_settings->m_env_vars;
3415 m_input_path = new_process_settings->m_input_path;
3416 m_output_path = new_process_settings->m_output_path;
3417 m_error_path = new_process_settings->m_error_path;
3418 m_plugin = new_process_settings->m_plugin;
3419 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003420 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003421}
3422
Caroline Tice12cecd72010-09-20 21:37:42 +00003423bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003424ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3425 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003426 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003427 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003428{
3429 if (var_name == RunArgsVarName())
3430 {
3431 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003432 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003433 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3434 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003435 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003436 }
3437 else if (var_name == EnvVarsVarName())
3438 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003439 GetHostEnvironmentIfNeeded ();
3440
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003441 if (m_env_vars.size() > 0)
3442 {
3443 std::map<std::string, std::string>::iterator pos;
3444 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3445 {
3446 StreamString value_str;
3447 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3448 value.AppendString (value_str.GetData());
3449 }
3450 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003451 }
3452 else if (var_name == InputPathVarName())
3453 {
3454 value.AppendString (m_input_path.c_str());
3455 }
3456 else if (var_name == OutputPathVarName())
3457 {
3458 value.AppendString (m_output_path.c_str());
3459 }
3460 else if (var_name == ErrorPathVarName())
3461 {
3462 value.AppendString (m_error_path.c_str());
3463 }
3464 else if (var_name == PluginVarName())
3465 {
3466 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3467 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003468 else if (var_name == InheritHostEnvVarName())
3469 {
3470 if (m_inherit_host_env)
3471 value.AppendString ("true");
3472 else
3473 value.AppendString ("false");
3474 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003475 else if (var_name == DisableASLRVarName())
3476 {
3477 if (m_disable_aslr)
3478 value.AppendString ("true");
3479 else
3480 value.AppendString ("false");
3481 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003482 else if (var_name == DisableSTDIOVarName())
3483 {
3484 if (m_disable_stdio)
3485 value.AppendString ("true");
3486 else
3487 value.AppendString ("false");
3488 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003489 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003490 {
3491 if (err)
3492 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3493 return false;
3494 }
3495 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003496}
3497
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003498const ConstString
3499ProcessInstanceSettings::CreateInstanceName ()
3500{
3501 static int instance_count = 1;
3502 StreamString sstr;
3503
3504 sstr.Printf ("process_%d", instance_count);
3505 ++instance_count;
3506
3507 const ConstString ret_val (sstr.GetData());
3508 return ret_val;
3509}
3510
3511const ConstString &
3512ProcessInstanceSettings::RunArgsVarName ()
3513{
3514 static ConstString run_args_var_name ("run-args");
3515
3516 return run_args_var_name;
3517}
3518
3519const ConstString &
3520ProcessInstanceSettings::EnvVarsVarName ()
3521{
3522 static ConstString env_vars_var_name ("env-vars");
3523
3524 return env_vars_var_name;
3525}
3526
3527const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003528ProcessInstanceSettings::InheritHostEnvVarName ()
3529{
3530 static ConstString g_name ("inherit-env");
3531
3532 return g_name;
3533}
3534
3535const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003536ProcessInstanceSettings::InputPathVarName ()
3537{
3538 static ConstString input_path_var_name ("input-path");
3539
3540 return input_path_var_name;
3541}
3542
3543const ConstString &
3544ProcessInstanceSettings::OutputPathVarName ()
3545{
Caroline Tice49e27372010-09-07 18:35:40 +00003546 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003547
3548 return output_path_var_name;
3549}
3550
3551const ConstString &
3552ProcessInstanceSettings::ErrorPathVarName ()
3553{
Caroline Tice49e27372010-09-07 18:35:40 +00003554 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003555
3556 return error_path_var_name;
3557}
3558
3559const ConstString &
3560ProcessInstanceSettings::PluginVarName ()
3561{
3562 static ConstString plugin_var_name ("plugin");
3563
3564 return plugin_var_name;
3565}
3566
3567
3568const ConstString &
3569ProcessInstanceSettings::DisableASLRVarName ()
3570{
3571 static ConstString disable_aslr_var_name ("disable-aslr");
3572
3573 return disable_aslr_var_name;
3574}
3575
Caroline Ticef8da8632010-12-03 18:46:09 +00003576const ConstString &
3577ProcessInstanceSettings::DisableSTDIOVarName ()
3578{
3579 static ConstString disable_stdio_var_name ("disable-stdio");
3580
3581 return disable_stdio_var_name;
3582}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003583
3584//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003585// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003586//--------------------------------------------------
3587
3588SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003589Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003590{
3591 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3592 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3593};
3594
3595
3596lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003597Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003598{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003599 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3600 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3601 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003602};
3603
3604SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003605Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003606{
Greg Clayton85851dd2010-12-04 00:10:17 +00003607 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3608 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3609 { "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." },
3610 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00003611 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3612 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3613 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3614 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00003615 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3616 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3617 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003618};
3619
3620
Jim Ingham5aee1622010-08-09 23:31:02 +00003621