blob: fb6614d3f6753c9c4af26aff61505c46124f05de [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_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000233 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000234 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000235 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000236 m_stdout_data (),
Jim Inghambb3a2832011-01-29 01:49:25 +0000237 m_memory_cache (),
Greg Clayton513c26c2011-01-29 07:10:55 +0000238 m_next_event_action_ap()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239{
Caroline Tice1559a462010-09-27 00:30:10 +0000240 UpdateInstanceName();
241
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000242 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000243 if (log)
244 log->Printf ("%p Process::Process()", this);
245
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000246 SetEventName (eBroadcastBitStateChanged, "state-changed");
247 SetEventName (eBroadcastBitInterrupt, "interrupt");
248 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
249 SetEventName (eBroadcastBitSTDERR, "stderr-available");
250
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251 listener.StartListeningForEvents (this,
252 eBroadcastBitStateChanged |
253 eBroadcastBitInterrupt |
254 eBroadcastBitSTDOUT |
255 eBroadcastBitSTDERR);
256
257 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
258 eBroadcastBitStateChanged);
259
260 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
261 eBroadcastInternalStateControlStop |
262 eBroadcastInternalStateControlPause |
263 eBroadcastInternalStateControlResume);
264}
265
266//----------------------------------------------------------------------
267// Destructor
268//----------------------------------------------------------------------
269Process::~Process()
270{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000271 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272 if (log)
273 log->Printf ("%p Process::~Process()", this);
274 StopPrivateStateThread();
275}
276
277void
278Process::Finalize()
279{
280 // Do any cleanup needed prior to being destructed... Subclasses
281 // that override this method should call this superclass method as well.
282}
283
284void
285Process::RegisterNotificationCallbacks (const Notifications& callbacks)
286{
287 m_notifications.push_back(callbacks);
288 if (callbacks.initialize != NULL)
289 callbacks.initialize (callbacks.baton, this);
290}
291
292bool
293Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
294{
295 std::vector<Notifications>::iterator pos, end = m_notifications.end();
296 for (pos = m_notifications.begin(); pos != end; ++pos)
297 {
298 if (pos->baton == callbacks.baton &&
299 pos->initialize == callbacks.initialize &&
300 pos->process_state_changed == callbacks.process_state_changed)
301 {
302 m_notifications.erase(pos);
303 return true;
304 }
305 }
306 return false;
307}
308
309void
310Process::SynchronouslyNotifyStateChanged (StateType state)
311{
312 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
313 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
314 {
315 if (notification_pos->process_state_changed)
316 notification_pos->process_state_changed (notification_pos->baton, this, state);
317 }
318}
319
320// FIXME: We need to do some work on events before the general Listener sees them.
321// For instance if we are continuing from a breakpoint, we need to ensure that we do
322// the little "insert real insn, step & stop" trick. But we can't do that when the
323// event is delivered by the broadcaster - since that is done on the thread that is
324// waiting for new events, so if we needed more than one event for our handling, we would
325// stall. So instead we do it when we fetch the event off of the queue.
326//
327
328StateType
329Process::GetNextEvent (EventSP &event_sp)
330{
331 StateType state = eStateInvalid;
332
333 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
334 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
335
336 return state;
337}
338
339
340StateType
341Process::WaitForProcessToStop (const TimeValue *timeout)
342{
343 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
344 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
345}
346
347
348StateType
349Process::WaitForState
350(
351 const TimeValue *timeout,
352 const StateType *match_states, const uint32_t num_match_states
353)
354{
355 EventSP event_sp;
356 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000357 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358 while (state != eStateInvalid)
359 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000360 // If we are exited or detached, we won't ever get back to any
361 // other valid state...
362 if (state == eStateDetached || state == eStateExited)
363 return state;
364
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000365 state = WaitForStateChangedEvents (timeout, event_sp);
366
367 for (i=0; i<num_match_states; ++i)
368 {
369 if (match_states[i] == state)
370 return state;
371 }
372 }
373 return state;
374}
375
Jim Ingham30f9b212010-10-11 23:53:14 +0000376bool
377Process::HijackProcessEvents (Listener *listener)
378{
379 if (listener != NULL)
380 {
381 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
382 }
383 else
384 return false;
385}
386
387void
388Process::RestoreProcessEvents ()
389{
390 RestoreBroadcaster();
391}
392
Jim Ingham0f16e732011-02-08 05:20:59 +0000393bool
394Process::HijackPrivateProcessEvents (Listener *listener)
395{
396 if (listener != NULL)
397 {
398 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
399 }
400 else
401 return false;
402}
403
404void
405Process::RestorePrivateProcessEvents ()
406{
407 m_private_state_broadcaster.RestoreBroadcaster();
408}
409
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410StateType
411Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
412{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000413 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
415 if (log)
416 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
417
418 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000419 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
420 this,
421 eBroadcastBitStateChanged,
422 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
424
425 if (log)
426 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
427 __FUNCTION__,
428 timeout,
429 StateAsCString(state));
430 return state;
431}
432
433Event *
434Process::PeekAtStateChangedEvents ()
435{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000436 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437
438 if (log)
439 log->Printf ("Process::%s...", __FUNCTION__);
440
441 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000442 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
443 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444 if (log)
445 {
446 if (event_ptr)
447 {
448 log->Printf ("Process::%s (event_ptr) => %s",
449 __FUNCTION__,
450 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
451 }
452 else
453 {
454 log->Printf ("Process::%s no events found",
455 __FUNCTION__);
456 }
457 }
458 return event_ptr;
459}
460
461StateType
462Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
463{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000464 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465
466 if (log)
467 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
468
469 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000470 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
471 &m_private_state_broadcaster,
472 eBroadcastBitStateChanged,
473 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
475
476 // This is a bit of a hack, but when we wait here we could very well return
477 // to the command-line, and that could disable the log, which would render the
478 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000480 {
481 if (state == eStateInvalid)
482 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
483 else
484 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000486 return state;
487}
488
489bool
490Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
491{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000492 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493
494 if (log)
495 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
496
497 if (control_only)
498 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
499 else
500 return m_private_state_listener.WaitForEvent(timeout, event_sp);
501}
502
503bool
504Process::IsRunning () const
505{
506 return StateIsRunningState (m_public_state.GetValue());
507}
508
509int
510Process::GetExitStatus ()
511{
512 if (m_public_state.GetValue() == eStateExited)
513 return m_exit_status;
514 return -1;
515}
516
Greg Clayton85851dd2010-12-04 00:10:17 +0000517
518void
519Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
520{
521 if (m_inherit_host_env && !m_got_host_env)
522 {
523 m_got_host_env = true;
524 StringList host_env;
525 const size_t host_env_count = Host::GetEnvironment (host_env);
526 for (size_t idx=0; idx<host_env_count; idx++)
527 {
528 const char *env_entry = host_env.GetStringAtIndex (idx);
529 if (env_entry)
530 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000531 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000532 if (equal_pos)
533 {
534 std::string key (env_entry, equal_pos - env_entry);
535 std::string value (equal_pos + 1);
536 if (m_env_vars.find (key) == m_env_vars.end())
537 m_env_vars[key] = value;
538 }
539 }
540 }
541 }
542}
543
544
545size_t
546Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
547{
548 GetHostEnvironmentIfNeeded ();
549
550 dictionary::const_iterator pos, end = m_env_vars.end();
551 for (pos = m_env_vars.begin(); pos != end; ++pos)
552 {
553 std::string env_var_equal_value (pos->first);
554 env_var_equal_value.append(1, '=');
555 env_var_equal_value.append (pos->second);
556 env.AppendArgument (env_var_equal_value.c_str());
557 }
558 return env.GetArgumentCount();
559}
560
561
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562const char *
563Process::GetExitDescription ()
564{
565 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
566 return m_exit_string.c_str();
567 return NULL;
568}
569
Greg Clayton6779606a2011-01-22 23:43:18 +0000570bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000571Process::SetExitStatus (int status, const char *cstr)
572{
Greg Clayton414f5d32011-01-25 02:58:48 +0000573 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
574 if (log)
575 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
576 status, status,
577 cstr ? "\"" : "",
578 cstr ? cstr : "NULL",
579 cstr ? "\"" : "");
580
Greg Clayton6779606a2011-01-22 23:43:18 +0000581 // We were already in the exited state
582 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000583 {
Greg Clayton385d6032011-01-26 23:47:29 +0000584 if (log)
585 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000586 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000587 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000588
589 m_exit_status = status;
590 if (cstr)
591 m_exit_string = cstr;
592 else
593 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000594
Greg Clayton6779606a2011-01-22 23:43:18 +0000595 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000596
Greg Clayton6779606a2011-01-22 23:43:18 +0000597 SetPrivateState (eStateExited);
598 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599}
600
601// This static callback can be used to watch for local child processes on
602// the current host. The the child process exits, the process will be
603// found in the global target list (we want to be completely sure that the
604// lldb_private::Process doesn't go away before we can deliver the signal.
605bool
606Process::SetProcessExitStatus
607(
608 void *callback_baton,
609 lldb::pid_t pid,
610 int signo, // Zero for no signal
611 int exit_status // Exit value of process if signal is zero
612)
613{
614 if (signo == 0 || exit_status)
615 {
Greg Clayton66111032010-06-23 01:19:29 +0000616 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617 if (target_sp)
618 {
619 ProcessSP process_sp (target_sp->GetProcessSP());
620 if (process_sp)
621 {
622 const char *signal_cstr = NULL;
623 if (signo)
624 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
625
626 process_sp->SetExitStatus (exit_status, signal_cstr);
627 }
628 }
629 return true;
630 }
631 return false;
632}
633
634
635uint32_t
636Process::GetNextThreadIndexID ()
637{
638 return ++m_thread_index_id;
639}
640
641StateType
642Process::GetState()
643{
644 // If any other threads access this we will need a mutex for it
645 return m_public_state.GetValue ();
646}
647
648void
649Process::SetPublicState (StateType new_state)
650{
Greg Clayton414f5d32011-01-25 02:58:48 +0000651 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 if (log)
653 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
654 m_public_state.SetValue (new_state);
655}
656
657StateType
658Process::GetPrivateState ()
659{
660 return m_private_state.GetValue();
661}
662
663void
664Process::SetPrivateState (StateType new_state)
665{
Greg Clayton414f5d32011-01-25 02:58:48 +0000666 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667 bool state_changed = false;
668
669 if (log)
670 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
671
672 Mutex::Locker locker(m_private_state.GetMutex());
673
674 const StateType old_state = m_private_state.GetValueNoLock ();
675 state_changed = old_state != new_state;
676 if (state_changed)
677 {
678 m_private_state.SetValueNoLock (new_state);
679 if (StateIsStoppedState(new_state))
680 {
681 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000682 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 if (log)
684 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
685 }
686 // Use our target to get a shared pointer to ourselves...
687 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
688 }
689 else
690 {
691 if (log)
692 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
693 }
694}
695
696
697uint32_t
698Process::GetStopID() const
699{
700 return m_stop_id;
701}
702
703addr_t
704Process::GetImageInfoAddress()
705{
706 return LLDB_INVALID_ADDRESS;
707}
708
Greg Clayton8f343b02010-11-04 01:54:29 +0000709//----------------------------------------------------------------------
710// LoadImage
711//
712// This function provides a default implementation that works for most
713// unix variants. Any Process subclasses that need to do shared library
714// loading differently should override LoadImage and UnloadImage and
715// do what is needed.
716//----------------------------------------------------------------------
717uint32_t
718Process::LoadImage (const FileSpec &image_spec, Error &error)
719{
720 DynamicLoader *loader = GetDynamicLoader();
721 if (loader)
722 {
723 error = loader->CanLoadImage();
724 if (error.Fail())
725 return LLDB_INVALID_IMAGE_TOKEN;
726 }
727
728 if (error.Success())
729 {
730 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
731 if (thread_sp == NULL)
732 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
733
734 if (thread_sp)
735 {
736 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
737
738 if (frame_sp)
739 {
740 ExecutionContext exe_ctx;
741 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000742 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000743 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000744 StreamString expr;
745 char path[PATH_MAX];
746 image_spec.GetPath(path, sizeof(path));
747 expr.Printf("dlopen (\"%s\", 2)", path);
748 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000749 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000750 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000751 if (result_valobj_sp->GetError().Success())
752 {
753 Scalar scalar;
754 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
755 {
756 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
757 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
758 {
759 uint32_t image_token = m_image_tokens.size();
760 m_image_tokens.push_back (image_ptr);
761 return image_token;
762 }
763 }
764 }
765 }
766 }
767 }
768 return LLDB_INVALID_IMAGE_TOKEN;
769}
770
771//----------------------------------------------------------------------
772// UnloadImage
773//
774// This function provides a default implementation that works for most
775// unix variants. Any Process subclasses that need to do shared library
776// loading differently should override LoadImage and UnloadImage and
777// do what is needed.
778//----------------------------------------------------------------------
779Error
780Process::UnloadImage (uint32_t image_token)
781{
782 Error error;
783 if (image_token < m_image_tokens.size())
784 {
785 const addr_t image_addr = m_image_tokens[image_token];
786 if (image_addr == LLDB_INVALID_ADDRESS)
787 {
788 error.SetErrorString("image already unloaded");
789 }
790 else
791 {
792 DynamicLoader *loader = GetDynamicLoader();
793 if (loader)
794 error = loader->CanLoadImage();
795
796 if (error.Success())
797 {
798 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
799 if (thread_sp == NULL)
800 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
801
802 if (thread_sp)
803 {
804 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
805
806 if (frame_sp)
807 {
808 ExecutionContext exe_ctx;
809 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000810 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000811 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000812 StreamString expr;
813 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
814 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000815 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000816 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000817 if (result_valobj_sp->GetError().Success())
818 {
819 Scalar scalar;
820 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
821 {
822 if (scalar.UInt(1))
823 {
824 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
825 }
826 else
827 {
828 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
829 }
830 }
831 }
832 else
833 {
834 error = result_valobj_sp->GetError();
835 }
836 }
837 }
838 }
839 }
840 }
841 else
842 {
843 error.SetErrorString("invalid image token");
844 }
845 return error;
846}
847
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848const ABI *
849Process::GetABI()
850{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 if (m_abi_sp.get() == NULL)
Greg Clayton514487e2011-02-15 21:59:32 +0000852 m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853
854 return m_abi_sp.get();
855}
856
Jim Ingham22777012010-09-23 02:01:19 +0000857LanguageRuntime *
858Process::GetLanguageRuntime(lldb::LanguageType language)
859{
860 LanguageRuntimeCollection::iterator pos;
861 pos = m_language_runtimes.find (language);
862 if (pos == m_language_runtimes.end())
863 {
864 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
865
866 m_language_runtimes[language]
867 = runtime;
868 return runtime.get();
869 }
870 else
871 return (*pos).second.get();
872}
873
874CPPLanguageRuntime *
875Process::GetCPPLanguageRuntime ()
876{
877 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
878 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
879 return static_cast<CPPLanguageRuntime *> (runtime);
880 return NULL;
881}
882
883ObjCLanguageRuntime *
884Process::GetObjCLanguageRuntime ()
885{
886 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
887 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
888 return static_cast<ObjCLanguageRuntime *> (runtime);
889 return NULL;
890}
891
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892BreakpointSiteList &
893Process::GetBreakpointSiteList()
894{
895 return m_breakpoint_site_list;
896}
897
898const BreakpointSiteList &
899Process::GetBreakpointSiteList() const
900{
901 return m_breakpoint_site_list;
902}
903
904
905void
906Process::DisableAllBreakpointSites ()
907{
908 m_breakpoint_site_list.SetEnabledForAll (false);
909}
910
911Error
912Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
913{
914 Error error (DisableBreakpointSiteByID (break_id));
915
916 if (error.Success())
917 m_breakpoint_site_list.Remove(break_id);
918
919 return error;
920}
921
922Error
923Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
924{
925 Error error;
926 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
927 if (bp_site_sp)
928 {
929 if (bp_site_sp->IsEnabled())
930 error = DisableBreakpoint (bp_site_sp.get());
931 }
932 else
933 {
934 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
935 }
936
937 return error;
938}
939
940Error
941Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
942{
943 Error error;
944 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
945 if (bp_site_sp)
946 {
947 if (!bp_site_sp->IsEnabled())
948 error = EnableBreakpoint (bp_site_sp.get());
949 }
950 else
951 {
952 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
953 }
954 return error;
955}
956
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000957lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
959{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000960 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 if (load_addr != LLDB_INVALID_ADDRESS)
962 {
963 BreakpointSiteSP bp_site_sp;
964
965 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
966 // create a new breakpoint site and add it.
967
968 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
969
970 if (bp_site_sp)
971 {
972 bp_site_sp->AddOwner (owner);
973 owner->SetBreakpointSite (bp_site_sp);
974 return bp_site_sp->GetID();
975 }
976 else
977 {
978 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
979 if (bp_site_sp)
980 {
981 if (EnableBreakpoint (bp_site_sp.get()).Success())
982 {
983 owner->SetBreakpointSite (bp_site_sp);
984 return m_breakpoint_site_list.Add (bp_site_sp);
985 }
986 }
987 }
988 }
989 // We failed to enable the breakpoint
990 return LLDB_INVALID_BREAK_ID;
991
992}
993
994void
995Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
996{
997 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
998 if (num_owners == 0)
999 {
1000 DisableBreakpoint(bp_site_sp.get());
1001 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1002 }
1003}
1004
1005
1006size_t
1007Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1008{
1009 size_t bytes_removed = 0;
1010 addr_t intersect_addr;
1011 size_t intersect_size;
1012 size_t opcode_offset;
1013 size_t idx;
1014 BreakpointSiteSP bp;
1015
1016 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1017 {
1018 if (bp->GetType() == BreakpointSite::eSoftware)
1019 {
1020 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1021 {
1022 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1023 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1024 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1025 size_t buf_offset = intersect_addr - bp_addr;
1026 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1027 }
1028 }
1029 }
1030 return bytes_removed;
1031}
1032
1033
1034Error
1035Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1036{
1037 Error error;
1038 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001039 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040 const addr_t bp_addr = bp_site->GetLoadAddress();
1041 if (log)
1042 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1043 if (bp_site->IsEnabled())
1044 {
1045 if (log)
1046 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1047 return error;
1048 }
1049
1050 if (bp_addr == LLDB_INVALID_ADDRESS)
1051 {
1052 error.SetErrorString("BreakpointSite contains an invalid load address.");
1053 return error;
1054 }
1055 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1056 // trap for the breakpoint site
1057 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1058
1059 if (bp_opcode_size == 0)
1060 {
1061 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1062 }
1063 else
1064 {
1065 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1066
1067 if (bp_opcode_bytes == NULL)
1068 {
1069 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1070 return error;
1071 }
1072
1073 // Save the original opcode by reading it
1074 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1075 {
1076 // Write a software breakpoint in place of the original opcode
1077 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1078 {
1079 uint8_t verify_bp_opcode_bytes[64];
1080 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1081 {
1082 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1083 {
1084 bp_site->SetEnabled(true);
1085 bp_site->SetType (BreakpointSite::eSoftware);
1086 if (log)
1087 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1088 bp_site->GetID(),
1089 (uint64_t)bp_addr);
1090 }
1091 else
1092 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1093 }
1094 else
1095 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1096 }
1097 else
1098 error.SetErrorString("Unable to write breakpoint trap to memory.");
1099 }
1100 else
1101 error.SetErrorString("Unable to read memory at breakpoint address.");
1102 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001103 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1105 bp_site->GetID(),
1106 (uint64_t)bp_addr,
1107 error.AsCString());
1108 return error;
1109}
1110
1111Error
1112Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1113{
1114 Error error;
1115 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001116 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 addr_t bp_addr = bp_site->GetLoadAddress();
1118 lldb::user_id_t breakID = bp_site->GetID();
1119 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001120 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121
1122 if (bp_site->IsHardware())
1123 {
1124 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1125 }
1126 else if (bp_site->IsEnabled())
1127 {
1128 const size_t break_op_size = bp_site->GetByteSize();
1129 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1130 if (break_op_size > 0)
1131 {
1132 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001133 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001134 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135 bool break_op_found = false;
1136
1137 // Read the breakpoint opcode
1138 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1139 {
1140 bool verify = false;
1141 // Make sure we have the a breakpoint opcode exists at this address
1142 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1143 {
1144 break_op_found = true;
1145 // We found a valid breakpoint opcode at this address, now restore
1146 // the saved opcode.
1147 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1148 {
1149 verify = true;
1150 }
1151 else
1152 error.SetErrorString("Memory write failed when restoring original opcode.");
1153 }
1154 else
1155 {
1156 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1157 // Set verify to true and so we can check if the original opcode has already been restored
1158 verify = true;
1159 }
1160
1161 if (verify)
1162 {
Greg Claytonc982c762010-07-09 20:39:50 +00001163 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001164 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165 // Verify that our original opcode made it back to the inferior
1166 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1167 {
1168 // compare the memory we just read with the original opcode
1169 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1170 {
1171 // SUCCESS
1172 bp_site->SetEnabled(false);
1173 if (log)
1174 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1175 return error;
1176 }
1177 else
1178 {
1179 if (break_op_found)
1180 error.SetErrorString("Failed to restore original opcode.");
1181 }
1182 }
1183 else
1184 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1185 }
1186 }
1187 else
1188 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1189 }
1190 }
1191 else
1192 {
1193 if (log)
1194 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1195 return error;
1196 }
1197
1198 if (log)
1199 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1200 bp_site->GetID(),
1201 (uint64_t)bp_addr,
1202 error.AsCString());
1203 return error;
1204
1205}
1206
Greg Clayton58be07b2011-01-07 06:08:19 +00001207// Comment out line below to disable memory caching
1208#define ENABLE_MEMORY_CACHING
1209// Uncomment to verify memory caching works after making changes to caching code
1210//#define VERIFY_MEMORY_READS
1211
1212#if defined (ENABLE_MEMORY_CACHING)
1213
1214#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215
1216size_t
1217Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1218{
Greg Clayton58be07b2011-01-07 06:08:19 +00001219 // Memory caching is enabled, with debug verification
1220 if (buf && size)
1221 {
1222 // Uncomment the line below to make sure memory caching is working.
1223 // I ran this through the test suite and got no assertions, so I am
1224 // pretty confident this is working well. If any changes are made to
1225 // memory caching, uncomment the line below and test your changes!
1226
1227 // Verify all memory reads by using the cache first, then redundantly
1228 // reading the same memory from the inferior and comparing to make sure
1229 // everything is exactly the same.
1230 std::string verify_buf (size, '\0');
1231 assert (verify_buf.size() == size);
1232 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1233 Error verify_error;
1234 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1235 assert (cache_bytes_read == verify_bytes_read);
1236 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1237 assert (verify_error.Success() == error.Success());
1238 return cache_bytes_read;
1239 }
1240 return 0;
1241}
1242
1243#else // #if defined (VERIFY_MEMORY_READS)
1244
1245size_t
1246Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1247{
1248 // Memory caching enabled, no verification
1249 return m_memory_cache.Read (this, addr, buf, size, error);
1250}
1251
1252#endif // #else for #if defined (VERIFY_MEMORY_READS)
1253
1254#else // #if defined (ENABLE_MEMORY_CACHING)
1255
1256size_t
1257Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1258{
1259 // Memory caching is disabled
1260 return ReadMemoryFromInferior (addr, buf, size, error);
1261}
1262
1263#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1264
1265
1266size_t
1267Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1268{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269 if (buf == NULL || size == 0)
1270 return 0;
1271
1272 size_t bytes_read = 0;
1273 uint8_t *bytes = (uint8_t *)buf;
1274
1275 while (bytes_read < size)
1276 {
1277 const size_t curr_size = size - bytes_read;
1278 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1279 bytes + bytes_read,
1280 curr_size,
1281 error);
1282 bytes_read += curr_bytes_read;
1283 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1284 break;
1285 }
1286
1287 // Replace any software breakpoint opcodes that fall into this range back
1288 // into "buf" before we return
1289 if (bytes_read > 0)
1290 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1291 return bytes_read;
1292}
1293
Greg Clayton58a4c462010-12-16 20:01:20 +00001294uint64_t
1295Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1296{
1297 if (integer_byte_size > sizeof(uint64_t))
1298 {
1299 error.SetErrorString ("unsupported integer size");
1300 }
1301 else
1302 {
1303 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton514487e2011-02-15 21:59:32 +00001304 DataExtractor data (tmp,
1305 integer_byte_size,
1306 m_target.GetArchitecture().GetByteOrder(),
1307 m_target.GetArchitecture().GetAddressByteSize());
Greg Clayton58a4c462010-12-16 20:01:20 +00001308 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1309 {
1310 uint32_t offset = 0;
1311 return data.GetMaxU64 (&offset, integer_byte_size);
1312 }
1313 }
1314 // Any plug-in that doesn't return success a memory read with the number
1315 // of bytes that were requested should be setting the error
1316 assert (error.Fail());
1317 return 0;
1318}
1319
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320size_t
1321Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1322{
1323 size_t bytes_written = 0;
1324 const uint8_t *bytes = (const uint8_t *)buf;
1325
1326 while (bytes_written < size)
1327 {
1328 const size_t curr_size = size - bytes_written;
1329 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1330 bytes + bytes_written,
1331 curr_size,
1332 error);
1333 bytes_written += curr_bytes_written;
1334 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1335 break;
1336 }
1337 return bytes_written;
1338}
1339
1340size_t
1341Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1342{
Greg Clayton58be07b2011-01-07 06:08:19 +00001343#if defined (ENABLE_MEMORY_CACHING)
1344 m_memory_cache.Flush (addr, size);
1345#endif
1346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347 if (buf == NULL || size == 0)
1348 return 0;
1349 // We need to write any data that would go where any current software traps
1350 // (enabled software breakpoints) any software traps (breakpoints) that we
1351 // may have placed in our tasks memory.
1352
1353 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1354 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1355
1356 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1357 return DoWriteMemory(addr, buf, size, error);
1358
1359 BreakpointSiteList::collection::const_iterator pos;
1360 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001361 addr_t intersect_addr = 0;
1362 size_t intersect_size = 0;
1363 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364 const uint8_t *ubuf = (const uint8_t *)buf;
1365
1366 for (pos = iter; pos != end; ++pos)
1367 {
1368 BreakpointSiteSP bp;
1369 bp = pos->second;
1370
1371 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1372 assert(addr <= intersect_addr && intersect_addr < addr + size);
1373 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1374 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1375
1376 // Check for bytes before this breakpoint
1377 const addr_t curr_addr = addr + bytes_written;
1378 if (intersect_addr > curr_addr)
1379 {
1380 // There are some bytes before this breakpoint that we need to
1381 // just write to memory
1382 size_t curr_size = intersect_addr - curr_addr;
1383 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1384 ubuf + bytes_written,
1385 curr_size,
1386 error);
1387 bytes_written += curr_bytes_written;
1388 if (curr_bytes_written != curr_size)
1389 {
1390 // We weren't able to write all of the requested bytes, we
1391 // are done looping and will return the number of bytes that
1392 // we have written so far.
1393 break;
1394 }
1395 }
1396
1397 // Now write any bytes that would cover up any software breakpoints
1398 // directly into the breakpoint opcode buffer
1399 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1400 bytes_written += intersect_size;
1401 }
1402
1403 // Write any remaining bytes after the last breakpoint if we have any left
1404 if (bytes_written < size)
1405 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1406 ubuf + bytes_written,
1407 size - bytes_written,
1408 error);
1409
1410 return bytes_written;
1411}
1412
1413addr_t
1414Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1415{
1416 // Fixme: we should track the blocks we've allocated, and clean them up...
1417 // We could even do our own allocator here if that ends up being more efficient.
Greg Claytonb2daec92011-01-23 19:58:49 +00001418 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1419 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1420 if (log)
Greg Clayton2ad66702011-01-24 06:30:45 +00001421 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001422 size,
1423 permissions & ePermissionsReadable ? 'r' : '-',
1424 permissions & ePermissionsWritable ? 'w' : '-',
1425 permissions & ePermissionsExecutable ? 'x' : '-',
1426 (uint64_t)allocated_addr,
1427 m_stop_id);
1428 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429}
1430
1431Error
1432Process::DeallocateMemory (addr_t ptr)
1433{
Greg Claytonb2daec92011-01-23 19:58:49 +00001434 Error error(DoDeallocateMemory (ptr));
1435
1436 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1437 if (log)
1438 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1439 ptr,
1440 error.AsCString("SUCCESS"),
1441 m_stop_id);
1442 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001443}
1444
1445
1446Error
1447Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1448{
1449 Error error;
1450 error.SetErrorString("watchpoints are not supported");
1451 return error;
1452}
1453
1454Error
1455Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1456{
1457 Error error;
1458 error.SetErrorString("watchpoints are not supported");
1459 return error;
1460}
1461
1462StateType
1463Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1464{
1465 StateType state;
1466 // Now wait for the process to launch and return control to us, and then
1467 // call DidLaunch:
1468 while (1)
1469 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001470 event_sp.reset();
1471 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1472
1473 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00001475
1476 // If state is invalid, then we timed out
1477 if (state == eStateInvalid)
1478 break;
1479
1480 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481 HandlePrivateEvent (event_sp);
1482 }
1483 return state;
1484}
1485
1486Error
1487Process::Launch
1488(
1489 char const *argv[],
1490 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001491 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492 const char *stdin_path,
1493 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001494 const char *stderr_path,
1495 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496)
1497{
1498 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00001500 m_dyld_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001501 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502
1503 Module *exe_module = m_target.GetExecutableModule().get();
1504 if (exe_module)
1505 {
1506 char exec_file_path[PATH_MAX];
1507 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1508 if (exe_module->GetFileSpec().Exists())
1509 {
1510 error = WillLaunch (exe_module);
1511 if (error.Success())
1512 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001513 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 // The args coming in should not contain the application name, the
1515 // lldb_private::Process class will add this in case the executable
1516 // gets resolved to a different file than was given on the command
1517 // line (like when an applicaiton bundle is specified and will
1518 // resolve to the contained exectuable file, or the file given was
1519 // a symlink or other file system link that resolves to a different
1520 // file).
1521
1522 // Get the resolved exectuable path
1523
1524 // Make a new argument vector
1525 std::vector<const char *> exec_path_plus_argv;
1526 // Append the resolved executable path
1527 exec_path_plus_argv.push_back (exec_file_path);
1528
1529 // Push all args if there are any
1530 if (argv)
1531 {
1532 for (int i = 0; argv[i]; ++i)
1533 exec_path_plus_argv.push_back(argv[i]);
1534 }
1535
1536 // Push a NULL to terminate the args.
1537 exec_path_plus_argv.push_back(NULL);
1538
1539 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001540 error = DoLaunch (exe_module,
1541 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1542 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001543 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001544 stdin_path,
1545 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001546 stderr_path,
1547 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001548
1549 if (error.Fail())
1550 {
1551 if (GetID() != LLDB_INVALID_PROCESS_ID)
1552 {
1553 SetID (LLDB_INVALID_PROCESS_ID);
1554 const char *error_string = error.AsCString();
1555 if (error_string == NULL)
1556 error_string = "launch failed";
1557 SetExitStatus (-1, error_string);
1558 }
1559 }
1560 else
1561 {
1562 EventSP event_sp;
1563 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1564
1565 if (state == eStateStopped || state == eStateCrashed)
1566 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00001567
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568 DidLaunch ();
1569
Greg Clayton93d3c8332011-02-16 04:46:07 +00001570 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1571 if (m_dyld_ap.get())
1572 m_dyld_ap->DidLaunch();
1573
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001574 // This delays passing the stopped event to listeners till DidLaunch gets
1575 // a chance to complete...
1576 HandlePrivateEvent (event_sp);
1577 StartPrivateStateThread ();
1578 }
1579 else if (state == eStateExited)
1580 {
1581 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1582 // not likely to work, and return an invalid pid.
1583 HandlePrivateEvent (event_sp);
1584 }
1585 }
1586 }
1587 }
1588 else
1589 {
1590 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1591 }
1592 }
1593 return error;
1594}
1595
Jim Inghambb3a2832011-01-29 01:49:25 +00001596Process::NextEventAction::EventActionResult
1597Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001598{
Jim Inghambb3a2832011-01-29 01:49:25 +00001599 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1600 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00001601 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001602 case eStateRunning:
1603 return eEventActionRetry;
1604
1605 case eStateStopped:
1606 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00001607 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001608 // During attach, prior to sending the eStateStopped event,
1609 // lldb_private::Process subclasses must set the process must set
1610 // the new process ID.
1611 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton93d3c8332011-02-16 04:46:07 +00001612 m_process->CompleteAttach ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001613 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00001614 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001615
1616
1617 break;
1618 default:
1619 case eStateExited:
1620 case eStateInvalid:
1621 m_exit_string.assign ("No valid Process");
1622 return eEventActionExit;
1623 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00001624 }
1625}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001626
Jim Inghambb3a2832011-01-29 01:49:25 +00001627Process::NextEventAction::EventActionResult
1628Process::AttachCompletionHandler::HandleBeingInterrupted()
1629{
1630 return eEventActionSuccess;
1631}
1632
1633const char *
1634Process::AttachCompletionHandler::GetExitString ()
1635{
1636 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637}
1638
1639Error
1640Process::Attach (lldb::pid_t attach_pid)
1641{
1642
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001644 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001645
Jim Ingham5aee1622010-08-09 23:31:02 +00001646 // Find the process and its architecture. Make sure it matches the architecture
1647 // of the current Target, and if not adjust it.
1648
1649 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1650 if (attach_spec != GetTarget().GetArchitecture())
1651 {
1652 // Set the architecture on the target.
1653 GetTarget().SetArchitecture(attach_spec);
1654 }
1655
Greg Clayton93d3c8332011-02-16 04:46:07 +00001656 m_dyld_ap.reset();
1657
Greg Claytonc982c762010-07-09 20:39:50 +00001658 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659 if (error.Success())
1660 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001661 SetPublicState (eStateAttaching);
1662
Greg Claytonc982c762010-07-09 20:39:50 +00001663 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 if (error.Success())
1665 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001666 SetNextEventAction(new Process::AttachCompletionHandler(this));
1667 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001668 }
1669 else
1670 {
1671 if (GetID() != LLDB_INVALID_PROCESS_ID)
1672 {
1673 SetID (LLDB_INVALID_PROCESS_ID);
1674 const char *error_string = error.AsCString();
1675 if (error_string == NULL)
1676 error_string = "attach failed";
1677
1678 SetExitStatus(-1, error_string);
1679 }
1680 }
1681 }
1682 return error;
1683}
1684
1685Error
1686Process::Attach (const char *process_name, bool wait_for_launch)
1687{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001689 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001690
1691 // Find the process and its architecture. Make sure it matches the architecture
1692 // of the current Target, and if not adjust it.
1693
Jim Ingham2ecb7422010-08-17 21:54:19 +00001694 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001695 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001696 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001697 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001698 {
1699 // Set the architecture on the target.
1700 GetTarget().SetArchitecture(attach_spec);
1701 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001702 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00001703
1704 m_dyld_ap.reset();
Jim Ingham2ecb7422010-08-17 21:54:19 +00001705
Greg Claytonc982c762010-07-09 20:39:50 +00001706 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001707 if (error.Success())
1708 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001709 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001710 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711 if (error.Fail())
1712 {
1713 if (GetID() != LLDB_INVALID_PROCESS_ID)
1714 {
1715 SetID (LLDB_INVALID_PROCESS_ID);
1716 const char *error_string = error.AsCString();
1717 if (error_string == NULL)
1718 error_string = "attach failed";
1719
1720 SetExitStatus(-1, error_string);
1721 }
1722 }
1723 else
1724 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001725 SetNextEventAction(new Process::AttachCompletionHandler(this));
1726 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001727 }
1728 }
1729 return error;
1730}
1731
Greg Clayton93d3c8332011-02-16 04:46:07 +00001732void
1733Process::CompleteAttach ()
1734{
1735 // Let the process subclass figure out at much as it can about the process
1736 // before we go looking for a dynamic loader plug-in.
1737 DidAttach();
1738
1739 // We have complete the attach, now it is time to find the dynamic loader
1740 // plug-in
1741 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1742 if (m_dyld_ap.get())
1743 m_dyld_ap->DidAttach();
1744
1745 // Figure out which one is the executable, and set that in our target:
1746 ModuleList &modules = m_target.GetImages();
1747
1748 size_t num_modules = modules.GetSize();
1749 for (int i = 0; i < num_modules; i++)
1750 {
1751 ModuleSP module_sp (modules.GetModuleAtIndex(i));
1752 if (module_sp->IsExecutable())
1753 {
1754 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
1755 if (target_exe_module_sp != module_sp)
1756 m_target.SetExecutableModule (module_sp, false);
1757 break;
1758 }
1759 }
1760}
1761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762Error
Greg Claytonb766a732011-02-04 01:58:07 +00001763Process::ConnectRemote (const char *remote_url)
1764{
Greg Claytonb766a732011-02-04 01:58:07 +00001765 m_abi_sp.reset();
1766 m_process_input_reader.reset();
1767
1768 // Find the process and its architecture. Make sure it matches the architecture
1769 // of the current Target, and if not adjust it.
1770
1771 Error error (DoConnectRemote (remote_url));
1772 if (error.Success())
1773 {
1774 SetNextEventAction(new Process::AttachCompletionHandler(this));
1775 StartPrivateStateThread();
1776// TimeValue timeout;
1777// timeout = TimeValue::Now();
1778// timeout.OffsetWithMicroSeconds(000);
1779// EventSP event_sp;
1780// StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1781//
1782// if (state == eStateStopped || state == eStateCrashed)
1783// {
1784// DidLaunch ();
1785//
1786// // This delays passing the stopped event to listeners till DidLaunch gets
1787// // a chance to complete...
1788// HandlePrivateEvent (event_sp);
1789// StartPrivateStateThread ();
1790// }
1791// else if (state == eStateExited)
1792// {
1793// // We exited while trying to launch somehow. Don't call DidLaunch as that's
1794// // not likely to work, and return an invalid pid.
1795// HandlePrivateEvent (event_sp);
1796// }
1797//
1798// StartPrivateStateThread();
1799 }
1800 return error;
1801}
1802
1803
1804Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805Process::Resume ()
1806{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001807 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00001809 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1810 m_stop_id,
1811 StateAsCString(m_public_state.GetValue()),
1812 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813
1814 Error error (WillResume());
1815 // Tell the process it is about to resume before the thread list
1816 if (error.Success())
1817 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001818 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 // can let all of our threads know that they are about to be
1820 // resumed. Threads will each be called with
1821 // Thread::WillResume(StateType) where StateType contains the state
1822 // that they are supposed to have when the process is resumed
1823 // (suspended/running/stepping). Threads should also check
1824 // their resume signal in lldb::Thread::GetResumeSignal()
1825 // to see if they are suppoed to start back up with a signal.
1826 if (m_thread_list.WillResume())
1827 {
1828 error = DoResume();
1829 if (error.Success())
1830 {
1831 DidResume();
1832 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00001833 if (log)
1834 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
1836 }
1837 else
1838 {
Jim Ingham444586b2011-01-24 06:34:17 +00001839 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840 }
1841 }
Jim Ingham444586b2011-01-24 06:34:17 +00001842 else if (log)
1843 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001844 return error;
1845}
1846
1847Error
1848Process::Halt ()
1849{
Jim Inghambb3a2832011-01-29 01:49:25 +00001850 // Pause our private state thread so we can ensure no one else eats
1851 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00001852 Listener halt_listener ("lldb.process.halt_listener");
1853 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001854
Jim Inghambb3a2832011-01-29 01:49:25 +00001855 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00001856 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00001857
Greg Clayton513c26c2011-01-29 07:10:55 +00001858 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00001859 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001860
Greg Clayton513c26c2011-01-29 07:10:55 +00001861 bool caused_stop = false;
1862
1863 // Ask the process subclass to actually halt our process
1864 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001866 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001867 if (m_public_state.GetValue() == eStateAttaching)
1868 {
1869 SetExitStatus(SIGKILL, "Cancelled async attach.");
1870 Destroy ();
1871 }
1872 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001873 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001874 // If "caused_stop" is true, then DoHalt stopped the process. If
1875 // "caused_stop" is false, the process was already stopped.
1876 // If the DoHalt caused the process to stop, then we want to catch
1877 // this event and set the interrupted bool to true before we pass
1878 // this along so clients know that the process was interrupted by
1879 // a halt command.
1880 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001881 {
Jim Ingham0f16e732011-02-08 05:20:59 +00001882 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00001883 TimeValue timeout_time;
1884 timeout_time = TimeValue::Now();
1885 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00001886 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1887 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00001888
Jim Ingham0f16e732011-02-08 05:20:59 +00001889 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001890 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001891 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00001892 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00001893 }
1894 else
1895 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001896 if (StateIsStoppedState (state))
1897 {
1898 // We caused the process to interrupt itself, so mark this
1899 // as such in the stop event so clients can tell an interrupted
1900 // process from a natural stop
1901 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1902 }
1903 else
1904 {
1905 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1906 if (log)
1907 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1908 error.SetErrorString ("Did not get stopped event after halt.");
1909 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001910 }
1911 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001912 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001913 }
1914 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001916 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00001917 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00001918
1919 // Post any event we might have consumed. If all goes well, we will have
1920 // stopped the process, intercepted the event and set the interrupted
1921 // bool in the event. Post it to the private event queue and that will end up
1922 // correctly setting the state.
1923 if (event_sp)
1924 m_private_state_broadcaster.BroadcastEvent(event_sp);
1925
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001926 return error;
1927}
1928
1929Error
1930Process::Detach ()
1931{
1932 Error error (WillDetach());
1933
1934 if (error.Success())
1935 {
1936 DisableAllBreakpointSites();
1937 error = DoDetach();
1938 if (error.Success())
1939 {
1940 DidDetach();
1941 StopPrivateStateThread();
1942 }
1943 }
1944 return error;
1945}
1946
1947Error
1948Process::Destroy ()
1949{
1950 Error error (WillDestroy());
1951 if (error.Success())
1952 {
1953 DisableAllBreakpointSites();
1954 error = DoDestroy();
1955 if (error.Success())
1956 {
1957 DidDestroy();
1958 StopPrivateStateThread();
1959 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001960 m_stdio_communication.StopReadThread();
1961 m_stdio_communication.Disconnect();
1962 if (m_process_input_reader && m_process_input_reader->IsActive())
1963 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1964 if (m_process_input_reader)
1965 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001966 }
1967 return error;
1968}
1969
1970Error
1971Process::Signal (int signal)
1972{
1973 Error error (WillSignal());
1974 if (error.Success())
1975 {
1976 error = DoSignal(signal);
1977 if (error.Success())
1978 DidSignal();
1979 }
1980 return error;
1981}
1982
Greg Clayton514487e2011-02-15 21:59:32 +00001983lldb::ByteOrder
1984Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001985{
Greg Clayton514487e2011-02-15 21:59:32 +00001986 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987}
1988
1989uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00001990Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001991{
Greg Clayton514487e2011-02-15 21:59:32 +00001992 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001993}
1994
Greg Clayton514487e2011-02-15 21:59:32 +00001995
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001996bool
1997Process::ShouldBroadcastEvent (Event *event_ptr)
1998{
1999 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2000 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002001 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002
2003 switch (state)
2004 {
Greg Claytonb766a732011-02-04 01:58:07 +00002005 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 case eStateAttaching:
2007 case eStateLaunching:
2008 case eStateDetached:
2009 case eStateExited:
2010 case eStateUnloaded:
2011 // These events indicate changes in the state of the debugging session, always report them.
2012 return_value = true;
2013 break;
2014 case eStateInvalid:
2015 // We stopped for no apparent reason, don't report it.
2016 return_value = false;
2017 break;
2018 case eStateRunning:
2019 case eStateStepping:
2020 // If we've started the target running, we handle the cases where we
2021 // are already running and where there is a transition from stopped to
2022 // running differently.
2023 // running -> running: Automatically suppress extra running events
2024 // stopped -> running: Report except when there is one or more no votes
2025 // and no yes votes.
2026 SynchronouslyNotifyStateChanged (state);
2027 switch (m_public_state.GetValue())
2028 {
2029 case eStateRunning:
2030 case eStateStepping:
2031 // We always suppress multiple runnings with no PUBLIC stop in between.
2032 return_value = false;
2033 break;
2034 default:
2035 // TODO: make this work correctly. For now always report
2036 // run if we aren't running so we don't miss any runnning
2037 // events. If I run the lldb/test/thread/a.out file and
2038 // break at main.cpp:58, run and hit the breakpoints on
2039 // multiple threads, then somehow during the stepping over
2040 // of all breakpoints no run gets reported.
2041 return_value = true;
2042
2043 // This is a transition from stop to run.
2044 switch (m_thread_list.ShouldReportRun (event_ptr))
2045 {
2046 case eVoteYes:
2047 case eVoteNoOpinion:
2048 return_value = true;
2049 break;
2050 case eVoteNo:
2051 return_value = false;
2052 break;
2053 }
2054 break;
2055 }
2056 break;
2057 case eStateStopped:
2058 case eStateCrashed:
2059 case eStateSuspended:
2060 {
2061 // We've stopped. First see if we're going to restart the target.
2062 // If we are going to stop, then we always broadcast the event.
2063 // 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 +00002064 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002065 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002067 if (log)
2068 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002069 return true;
2070 }
2071 else
2072 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 RefreshStateAfterStop ();
2074
2075 if (m_thread_list.ShouldStop (event_ptr) == false)
2076 {
2077 switch (m_thread_list.ShouldReportStop (event_ptr))
2078 {
2079 case eVoteYes:
2080 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002081 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002083 case eVoteNo:
2084 return_value = false;
2085 break;
2086 }
2087
2088 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002089 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 Resume ();
2091 }
2092 else
2093 {
2094 return_value = true;
2095 SynchronouslyNotifyStateChanged (state);
2096 }
2097 }
2098 }
2099 }
2100
2101 if (log)
2102 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2103 return return_value;
2104}
2105
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106
2107bool
2108Process::StartPrivateStateThread ()
2109{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002110 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111
2112 if (log)
2113 log->Printf ("Process::%s ( )", __FUNCTION__);
2114
2115 // Create a thread that watches our internal state and controls which
2116 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002117 char thread_name[1024];
2118 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2119 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002120 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121}
2122
2123void
2124Process::PausePrivateStateThread ()
2125{
2126 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2127}
2128
2129void
2130Process::ResumePrivateStateThread ()
2131{
2132 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2133}
2134
2135void
2136Process::StopPrivateStateThread ()
2137{
2138 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2139}
2140
2141void
2142Process::ControlPrivateStateThread (uint32_t signal)
2143{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002144 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145
2146 assert (signal == eBroadcastInternalStateControlStop ||
2147 signal == eBroadcastInternalStateControlPause ||
2148 signal == eBroadcastInternalStateControlResume);
2149
2150 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002151 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002153 // Signal the private state thread. First we should copy this is case the
2154 // thread starts exiting since the private state thread will NULL this out
2155 // when it exits
2156 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002157 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158 {
2159 TimeValue timeout_time;
2160 bool timed_out;
2161
2162 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2163
2164 timeout_time = TimeValue::Now();
2165 timeout_time.OffsetWithSeconds(2);
2166 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2167 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2168
2169 if (signal == eBroadcastInternalStateControlStop)
2170 {
2171 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002172 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173
2174 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002175 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002176 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177 }
2178 }
2179}
2180
2181void
2182Process::HandlePrivateEvent (EventSP &event_sp)
2183{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002184 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002185
Greg Clayton414f5d32011-01-25 02:58:48 +00002186 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002187
2188 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002189 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002190 {
Jim Ingham754ab982011-01-29 04:05:41 +00002191 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002192 switch (action_result)
2193 {
2194 case NextEventAction::eEventActionSuccess:
2195 SetNextEventAction(NULL);
2196 break;
2197 case NextEventAction::eEventActionRetry:
2198 break;
2199 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002200 // Handle Exiting Here. If we already got an exited event,
2201 // we should just propagate it. Otherwise, swallow this event,
2202 // and set our state to exit so the next event will kill us.
2203 if (new_state != eStateExited)
2204 {
2205 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002206 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002207 SetNextEventAction(NULL);
2208 return;
2209 }
2210 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002211 break;
2212 }
2213 }
2214
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002215 // See if we should broadcast this state to external clients?
2216 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217
2218 if (should_broadcast)
2219 {
2220 if (log)
2221 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002222 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2223 __FUNCTION__,
2224 GetID(),
2225 StateAsCString(new_state),
2226 StateAsCString (GetState ()),
2227 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002228 }
Greg Clayton414f5d32011-01-25 02:58:48 +00002229 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002230 PushProcessInputReader ();
2231 else
2232 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2234 BroadcastEvent (event_sp);
2235 }
2236 else
2237 {
2238 if (log)
2239 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002240 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2241 __FUNCTION__,
2242 GetID(),
2243 StateAsCString(new_state),
2244 StateAsCString (GetState ()),
2245 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 }
2247 }
2248}
2249
2250void *
2251Process::PrivateStateThread (void *arg)
2252{
2253 Process *proc = static_cast<Process*> (arg);
2254 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002255 return result;
2256}
2257
2258void *
2259Process::RunPrivateStateThread ()
2260{
2261 bool control_only = false;
2262 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2263
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002264 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002265 if (log)
2266 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2267
2268 bool exit_now = false;
2269 while (!exit_now)
2270 {
2271 EventSP event_sp;
2272 WaitForEventsPrivate (NULL, event_sp, control_only);
2273 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2274 {
2275 switch (event_sp->GetType())
2276 {
2277 case eBroadcastInternalStateControlStop:
2278 exit_now = true;
2279 continue; // Go to next loop iteration so we exit without
2280 break; // doing any internal state managment below
2281
2282 case eBroadcastInternalStateControlPause:
2283 control_only = true;
2284 break;
2285
2286 case eBroadcastInternalStateControlResume:
2287 control_only = false;
2288 break;
2289 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002290
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002291 if (log)
2292 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2293
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002294 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002295 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296 }
2297
2298
2299 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2300
2301 if (internal_state != eStateInvalid)
2302 {
2303 HandlePrivateEvent (event_sp);
2304 }
2305
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002306 if (internal_state == eStateInvalid ||
2307 internal_state == eStateExited ||
2308 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002309 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002310 if (log)
2311 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002314 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 }
2316
Caroline Tice20ad3c42010-10-29 21:48:37 +00002317 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 if (log)
2319 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2320
Greg Clayton6ed95942011-01-22 07:12:45 +00002321 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2322 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 return NULL;
2324}
2325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326//------------------------------------------------------------------
2327// Process Event Data
2328//------------------------------------------------------------------
2329
2330Process::ProcessEventData::ProcessEventData () :
2331 EventData (),
2332 m_process_sp (),
2333 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002334 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002335 m_update_state (false),
2336 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337{
2338}
2339
2340Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2341 EventData (),
2342 m_process_sp (process_sp),
2343 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002344 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002345 m_update_state (false),
2346 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347{
2348}
2349
2350Process::ProcessEventData::~ProcessEventData()
2351{
2352}
2353
2354const ConstString &
2355Process::ProcessEventData::GetFlavorString ()
2356{
2357 static ConstString g_flavor ("Process::ProcessEventData");
2358 return g_flavor;
2359}
2360
2361const ConstString &
2362Process::ProcessEventData::GetFlavor () const
2363{
2364 return ProcessEventData::GetFlavorString ();
2365}
2366
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367void
2368Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2369{
2370 // This function gets called twice for each event, once when the event gets pulled
2371 // off of the private process event queue, and once when it gets pulled off of
2372 // the public event queue. m_update_state is used to distinguish these
2373 // two cases; it is false when we're just pulling it off for private handling,
2374 // and we don't want to do the breakpoint command handling then.
2375
2376 if (!m_update_state)
2377 return;
2378
2379 m_process_sp->SetPublicState (m_state);
2380
2381 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2382 if (m_state == eStateStopped && ! m_restarted)
2383 {
2384 int num_threads = m_process_sp->GetThreadList().GetSize();
2385 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002386
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002387 for (idx = 0; idx < num_threads; ++idx)
2388 {
2389 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2390
Jim Inghamb15bfc72010-10-20 00:39:53 +00002391 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2392 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002394 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002395 }
2396 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002397
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002398 // The stop action might restart the target. If it does, then we want to mark that in the
2399 // event so that whoever is receiving it will know to wait for the running event and reflect
2400 // that state appropriately.
2401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 if (m_process_sp->GetPrivateState() == eStateRunning)
2403 SetRestarted(true);
2404 }
2405}
2406
2407void
2408Process::ProcessEventData::Dump (Stream *s) const
2409{
2410 if (m_process_sp)
2411 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2412
2413 s->Printf("state = %s", StateAsCString(GetState()));;
2414}
2415
2416const Process::ProcessEventData *
2417Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2418{
2419 if (event_ptr)
2420 {
2421 const EventData *event_data = event_ptr->GetData();
2422 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2423 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2424 }
2425 return NULL;
2426}
2427
2428ProcessSP
2429Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2430{
2431 ProcessSP process_sp;
2432 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2433 if (data)
2434 process_sp = data->GetProcessSP();
2435 return process_sp;
2436}
2437
2438StateType
2439Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2440{
2441 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2442 if (data == NULL)
2443 return eStateInvalid;
2444 else
2445 return data->GetState();
2446}
2447
2448bool
2449Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2450{
2451 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2452 if (data == NULL)
2453 return false;
2454 else
2455 return data->GetRestarted();
2456}
2457
2458void
2459Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2460{
2461 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2462 if (data != NULL)
2463 data->SetRestarted(new_value);
2464}
2465
2466bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002467Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2468{
2469 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2470 if (data == NULL)
2471 return false;
2472 else
2473 return data->GetInterrupted ();
2474}
2475
2476void
2477Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2478{
2479 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2480 if (data != NULL)
2481 data->SetInterrupted(new_value);
2482}
2483
2484bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2486{
2487 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2488 if (data)
2489 {
2490 data->SetUpdateStateOnRemoval();
2491 return true;
2492 }
2493 return false;
2494}
2495
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496void
Greg Clayton0603aa92010-10-04 01:05:56 +00002497Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002498{
2499 exe_ctx.target = &m_target;
2500 exe_ctx.process = this;
2501 exe_ctx.thread = NULL;
2502 exe_ctx.frame = NULL;
2503}
2504
2505lldb::ProcessSP
2506Process::GetSP ()
2507{
2508 return GetTarget().GetProcessSP();
2509}
2510
Jim Ingham5aee1622010-08-09 23:31:02 +00002511uint32_t
2512Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2513{
2514 return 0;
2515}
2516
2517ArchSpec
2518Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2519{
2520 return Host::GetArchSpecForExistingProcess (pid);
2521}
2522
2523ArchSpec
2524Process::GetArchSpecForExistingProcess (const char *process_name)
2525{
2526 return Host::GetArchSpecForExistingProcess (process_name);
2527}
2528
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002529void
2530Process::AppendSTDOUT (const char * s, size_t len)
2531{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002532 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002533 m_stdout_data.append (s, len);
2534
Greg Claytona9ff3062010-12-05 19:16:56 +00002535 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002536}
2537
2538void
2539Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2540{
2541 Process *process = (Process *) baton;
2542 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2543}
2544
2545size_t
2546Process::ProcessInputReaderCallback (void *baton,
2547 InputReader &reader,
2548 lldb::InputReaderAction notification,
2549 const char *bytes,
2550 size_t bytes_len)
2551{
2552 Process *process = (Process *) baton;
2553
2554 switch (notification)
2555 {
2556 case eInputReaderActivate:
2557 break;
2558
2559 case eInputReaderDeactivate:
2560 break;
2561
2562 case eInputReaderReactivate:
2563 break;
2564
2565 case eInputReaderGotToken:
2566 {
2567 Error error;
2568 process->PutSTDIN (bytes, bytes_len, error);
2569 }
2570 break;
2571
Caroline Ticeefed6132010-11-19 20:47:54 +00002572 case eInputReaderInterrupt:
2573 process->Halt ();
2574 break;
2575
2576 case eInputReaderEndOfFile:
2577 process->AppendSTDOUT ("^D", 2);
2578 break;
2579
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002580 case eInputReaderDone:
2581 break;
2582
2583 }
2584
2585 return bytes_len;
2586}
2587
2588void
2589Process::ResetProcessInputReader ()
2590{
2591 m_process_input_reader.reset();
2592}
2593
2594void
2595Process::SetUpProcessInputReader (int file_descriptor)
2596{
2597 // First set up the Read Thread for reading/handling process I/O
2598
2599 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2600
2601 if (conn_ap.get())
2602 {
2603 m_stdio_communication.SetConnection (conn_ap.release());
2604 if (m_stdio_communication.IsConnected())
2605 {
2606 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2607 m_stdio_communication.StartReadThread();
2608
2609 // Now read thread is set up, set up input reader.
2610
2611 if (!m_process_input_reader.get())
2612 {
2613 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2614 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2615 this,
2616 eInputReaderGranularityByte,
2617 NULL,
2618 NULL,
2619 false));
2620
2621 if (err.Fail())
2622 m_process_input_reader.reset();
2623 }
2624 }
2625 }
2626}
2627
2628void
2629Process::PushProcessInputReader ()
2630{
2631 if (m_process_input_reader && !m_process_input_reader->IsActive())
2632 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2633}
2634
2635void
2636Process::PopProcessInputReader ()
2637{
2638 if (m_process_input_reader && m_process_input_reader->IsActive())
2639 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2640}
2641
Greg Clayton99d0faf2010-11-18 23:32:35 +00002642
2643void
2644Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002645{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002646 UserSettingsControllerSP &usc = GetSettingsController();
2647 usc.reset (new SettingsController);
2648 UserSettingsController::InitializeSettingsController (usc,
2649 SettingsController::global_settings_table,
2650 SettingsController::instance_settings_table);
2651}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002652
Greg Clayton99d0faf2010-11-18 23:32:35 +00002653void
2654Process::Terminate ()
2655{
2656 UserSettingsControllerSP &usc = GetSettingsController();
2657 UserSettingsController::FinalizeSettingsController (usc);
2658 usc.reset();
2659}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002660
Greg Clayton99d0faf2010-11-18 23:32:35 +00002661UserSettingsControllerSP &
2662Process::GetSettingsController ()
2663{
2664 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002665 return g_settings_controller;
2666}
2667
Caroline Tice1559a462010-09-27 00:30:10 +00002668void
2669Process::UpdateInstanceName ()
2670{
2671 ModuleSP module_sp = GetTarget().GetExecutableModule();
2672 if (module_sp)
2673 {
2674 StreamString sstr;
2675 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2676
Greg Claytondbe54502010-11-19 03:46:01 +00002677 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002678 sstr.GetData());
2679 }
2680}
2681
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002682ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002683Process::RunThreadPlan (ExecutionContext &exe_ctx,
2684 lldb::ThreadPlanSP &thread_plan_sp,
2685 bool stop_others,
2686 bool try_all_threads,
2687 bool discard_on_error,
2688 uint32_t single_thread_timeout_usec,
2689 Stream &errors)
2690{
2691 ExecutionResults return_value = eExecutionSetupError;
2692
Jim Ingham77787032011-01-20 02:03:18 +00002693 if (thread_plan_sp.get() == NULL)
2694 {
2695 errors.Printf("RunThreadPlan called with empty thread plan.");
2696 return lldb::eExecutionSetupError;
2697 }
2698
Jim Ingham444586b2011-01-24 06:34:17 +00002699 if (m_private_state.GetValue() != eStateStopped)
2700 {
2701 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham0f16e732011-02-08 05:20:59 +00002702 return lldb::eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00002703 }
2704
Jim Inghamf48169b2010-11-30 02:22:11 +00002705 // Save this value for restoration of the execution context after we run
2706 uint32_t tid = exe_ctx.thread->GetIndexID();
2707
2708 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2709 // so we should arrange to reset them as well.
2710
2711 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2712 lldb::StackFrameSP selected_frame_sp;
2713
2714 uint32_t selected_tid;
2715 if (selected_thread_sp != NULL)
2716 {
2717 selected_tid = selected_thread_sp->GetIndexID();
2718 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2719 }
2720 else
2721 {
2722 selected_tid = LLDB_INVALID_THREAD_ID;
2723 }
2724
2725 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2726
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002727 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00002728
2729 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2730 // restored on exit to the function.
2731
2732 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00002733
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002734 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00002735 if (log)
2736 {
2737 StreamString s;
2738 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham0f16e732011-02-08 05:20:59 +00002739 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2740 exe_ctx.thread->GetIndexID(),
2741 exe_ctx.thread->GetID(),
2742 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00002743 }
2744
Jim Ingham0f16e732011-02-08 05:20:59 +00002745 bool got_event;
2746 lldb::EventSP event_sp;
2747 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00002748
2749 TimeValue* timeout_ptr = NULL;
2750 TimeValue real_timeout;
2751
Jim Ingham0f16e732011-02-08 05:20:59 +00002752 bool first_timeout = true;
2753 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00002754
Jim Inghamf48169b2010-11-30 02:22:11 +00002755 while (1)
2756 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002757 // We usually want to resume the process if we get to the top of the loop.
2758 // The only exception is if we get two running events with no intervening
2759 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00002760
Jim Ingham0f16e732011-02-08 05:20:59 +00002761 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00002762 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002763 // Do the initial resume and wait for the running event before going further.
2764
2765 Error resume_error = exe_ctx.process->Resume ();
2766 if (!resume_error.Success())
2767 {
2768 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2769 return_value = lldb::eExecutionSetupError;
2770 break;
2771 }
2772
2773 real_timeout = TimeValue::Now();
2774 real_timeout.OffsetWithMicroSeconds(500000);
2775 timeout_ptr = &real_timeout;
2776
2777 got_event = listener.WaitForEvent(NULL, event_sp);
2778 if (!got_event)
2779 {
2780 if (log)
2781 log->Printf("Didn't get any event after initial resume, exiting.");
2782
2783 errors.Printf("Didn't get any event after initial resume, exiting.");
2784 return_value = lldb::eExecutionSetupError;
2785 break;
2786 }
2787
2788 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2789 if (stop_state != eStateRunning)
2790 {
2791 if (log)
2792 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2793
2794 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2795 return_value = lldb::eExecutionSetupError;
2796 break;
2797 }
2798
2799 if (log)
2800 log->Printf ("Resuming succeeded.");
2801 // We need to call the function synchronously, so spin waiting for it to return.
2802 // If we get interrupted while executing, we're going to lose our context, and
2803 // won't be able to gather the result at this point.
2804 // We set the timeout AFTER the resume, since the resume takes some time and we
2805 // don't want to charge that to the timeout.
2806
2807 if (single_thread_timeout_usec != 0)
2808 {
2809 real_timeout = TimeValue::Now();
2810 if (first_timeout)
2811 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2812 else
2813 real_timeout.OffsetWithSeconds(10);
2814
2815 timeout_ptr = &real_timeout;
2816 }
2817 }
2818 else
2819 {
2820 if (log)
2821 log->Printf ("Handled an extra running event.");
2822 do_resume = true;
2823 }
2824
2825 // Now wait for the process to stop again:
2826 stop_state = lldb::eStateInvalid;
2827 event_sp.reset();
2828 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2829
2830 if (got_event)
2831 {
2832 if (event_sp.get())
2833 {
2834 bool keep_going = false;
2835 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2836 if (log)
2837 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2838
2839 switch (stop_state)
2840 {
2841 case lldb::eStateStopped:
2842 // Yay, we're done.
2843 if (log)
2844 log->Printf ("Execution completed successfully.");
2845 return_value = lldb::eExecutionCompleted;
2846 break;
2847 case lldb::eStateCrashed:
2848 if (log)
2849 log->Printf ("Execution crashed.");
2850 return_value = lldb::eExecutionInterrupted;
2851 break;
2852 case lldb::eStateRunning:
2853 do_resume = false;
2854 keep_going = true;
2855 break;
2856 default:
2857 if (log)
2858 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
2859 return_value = lldb::eExecutionInterrupted;
2860 break;
2861 }
2862 if (keep_going)
2863 continue;
2864 else
2865 break;
2866 }
2867 else
2868 {
2869 if (log)
2870 log->Printf ("got_event was true, but the event pointer was null. How odd...");
2871 return_value = lldb::eExecutionInterrupted;
2872 break;
2873 }
2874 }
2875 else
2876 {
2877 // If we didn't get an event that means we've timed out...
2878 // We will interrupt the process here. Depending on what we were asked to do we will
2879 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00002880 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00002881
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002882 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002883 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00002884 {
2885 if (first_timeout)
2886 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2887 "trying with all threads enabled.",
2888 single_thread_timeout_usec);
2889 else
2890 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2891 "and timeout: %d timed out.",
2892 single_thread_timeout_usec);
2893 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002894 else
Jim Ingham0f16e732011-02-08 05:20:59 +00002895 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2896 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002897 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002898 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002899
Jim Inghame22e88b2011-01-22 01:30:53 +00002900 Error halt_error = exe_ctx.process->Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00002901 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002902 {
Jim Inghamf48169b2010-11-30 02:22:11 +00002903 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002904 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002905
Jim Ingham0f16e732011-02-08 05:20:59 +00002906 // If halt succeeds, it always produces a stopped event. Wait for that:
2907
2908 real_timeout = TimeValue::Now();
2909 real_timeout.OffsetWithMicroSeconds(500000);
2910
2911 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00002912
2913 if (got_event)
2914 {
2915 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2916 if (log)
2917 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002918 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00002919 if (stop_state == lldb::eStateStopped
2920 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00002921 log->Printf (" Event was the Halt interruption event.");
2922 }
2923
Jim Ingham0f16e732011-02-08 05:20:59 +00002924 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00002925 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002926 // Between the time we initiated the Halt and the time we delivered it, the process could have
2927 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00002928
Jim Ingham0f16e732011-02-08 05:20:59 +00002929 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2930 {
2931 if (log)
2932 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
2933 "Exiting wait loop.");
2934 return_value = lldb::eExecutionCompleted;
2935 break;
2936 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002937
Jim Ingham0f16e732011-02-08 05:20:59 +00002938 if (!try_all_threads)
2939 {
2940 if (log)
2941 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
2942 return_value = lldb::eExecutionInterrupted;
2943 break;
2944 }
2945
2946 if (first_timeout)
2947 {
2948 // Set all the other threads to run, and return to the top of the loop, which will continue;
2949 first_timeout = false;
2950 thread_plan_sp->SetStopOthers (false);
2951 if (log)
2952 log->Printf ("Process::RunThreadPlan(): About to resume.");
2953
2954 continue;
2955 }
2956 else
2957 {
2958 // Running all threads failed, so return Interrupted.
2959 if (log)
2960 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
2961 return_value = lldb::eExecutionInterrupted;
2962 break;
2963 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002964 }
Jim Ingham0f16e732011-02-08 05:20:59 +00002965 }
2966 else
2967 { if (log)
2968 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
2969 "I'm getting out of here passing Interrupted.");
2970 return_value = lldb::eExecutionInterrupted;
2971 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00002972 }
2973 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002974 else
2975 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002976 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
2977 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00002978 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00002979 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.",
2980 halt_error.AsCString());
2981 real_timeout = TimeValue::Now();
2982 real_timeout.OffsetWithMicroSeconds(500000);
2983 timeout_ptr = &real_timeout;
2984 got_event = listener.WaitForEvent(&real_timeout, event_sp);
2985 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002986 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002987 // This is not going anywhere, bag out.
2988 if (log)
2989 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
2990 return_value = lldb::eExecutionInterrupted;
2991 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002992 }
Jim Ingham0f16e732011-02-08 05:20:59 +00002993 else
2994 {
2995 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2996 if (log)
2997 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
2998 if (stop_state == lldb::eStateStopped)
2999 {
3000 // Between the time we initiated the Halt and the time we delivered it, the process could have
3001 // already finished its job. Check that here:
3002
3003 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3004 {
3005 if (log)
3006 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3007 "Exiting wait loop.");
3008 return_value = lldb::eExecutionCompleted;
3009 break;
3010 }
3011
3012 if (first_timeout)
3013 {
3014 // Set all the other threads to run, and return to the top of the loop, which will continue;
3015 first_timeout = false;
3016 thread_plan_sp->SetStopOthers (false);
3017 if (log)
3018 log->Printf ("Process::RunThreadPlan(): About to resume.");
3019
3020 continue;
3021 }
3022 else
3023 {
3024 // Running all threads failed, so return Interrupted.
3025 if (log)
3026 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3027 return_value = lldb::eExecutionInterrupted;
3028 break;
3029 }
3030 }
3031 else
3032 {
3033 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3034 " a stopped event, instead got %s.", StateAsCString(stop_state));
3035 return_value = lldb::eExecutionInterrupted;
3036 break;
3037 }
3038 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003039 }
3040
Jim Inghamf48169b2010-11-30 02:22:11 +00003041 }
3042
Jim Ingham0f16e732011-02-08 05:20:59 +00003043 } // END WAIT LOOP
3044
3045 // Now do some processing on the results of the run:
3046 if (return_value == eExecutionInterrupted)
3047 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003048 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003049 {
3050 StreamString s;
3051 if (event_sp)
3052 event_sp->Dump (&s);
3053 else
3054 {
3055 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3056 }
3057
3058 StreamString ts;
3059
3060 const char *event_explanation;
3061
3062 do
3063 {
3064 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3065
3066 if (!event_data)
3067 {
3068 event_explanation = "<no event data>";
3069 break;
3070 }
3071
3072 Process *process = event_data->GetProcessSP().get();
3073
3074 if (!process)
3075 {
3076 event_explanation = "<no process>";
3077 break;
3078 }
3079
3080 ThreadList &thread_list = process->GetThreadList();
3081
3082 uint32_t num_threads = thread_list.GetSize();
3083 uint32_t thread_index;
3084
3085 ts.Printf("<%u threads> ", num_threads);
3086
3087 for (thread_index = 0;
3088 thread_index < num_threads;
3089 ++thread_index)
3090 {
3091 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3092
3093 if (!thread)
3094 {
3095 ts.Printf("<?> ");
3096 continue;
3097 }
3098
3099 ts.Printf("<0x%4.4x ", thread->GetID());
3100 RegisterContext *register_context = thread->GetRegisterContext().get();
3101
3102 if (register_context)
3103 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3104 else
3105 ts.Printf("[ip unknown] ");
3106
3107 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3108 if (stop_info_sp)
3109 {
3110 const char *stop_desc = stop_info_sp->GetDescription();
3111 if (stop_desc)
3112 ts.PutCString (stop_desc);
3113 }
3114 ts.Printf(">");
3115 }
3116
3117 event_explanation = ts.GetData();
3118 } while (0);
3119
3120 if (log)
3121 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3122
3123 if (discard_on_error && thread_plan_sp)
3124 {
3125 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3126 }
3127 }
3128 }
3129 else if (return_value == eExecutionSetupError)
3130 {
3131 if (log)
3132 log->Printf("Process::RunThreadPlan(): execution set up error.");
3133
3134 if (discard_on_error && thread_plan_sp)
3135 {
3136 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3137 }
3138 }
3139 else
3140 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003141 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3142 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003143 if (log)
3144 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003145 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003146 }
3147 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3148 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003149 if (log)
3150 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003151 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003152 }
3153 else
3154 {
3155 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003156 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003157 if (discard_on_error && thread_plan_sp)
3158 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003159 if (log)
3160 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003161 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3162 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003163 }
3164 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003165
Jim Inghamf48169b2010-11-30 02:22:11 +00003166 // Thread we ran the function in may have gone away because we ran the target
3167 // Check that it's still there.
3168 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3169 if (exe_ctx.thread)
3170 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3171
3172 // Also restore the current process'es selected frame & thread, since this function calling may
3173 // be done behind the user's back.
3174
3175 if (selected_tid != LLDB_INVALID_THREAD_ID)
3176 {
3177 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3178 {
3179 // We were able to restore the selected thread, now restore the frame:
3180 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3181 }
3182 }
3183
3184 return return_value;
3185}
3186
3187const char *
3188Process::ExecutionResultAsCString (ExecutionResults result)
3189{
3190 const char *result_name;
3191
3192 switch (result)
3193 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003194 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003195 result_name = "eExecutionCompleted";
3196 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003197 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003198 result_name = "eExecutionDiscarded";
3199 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003200 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003201 result_name = "eExecutionInterrupted";
3202 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003203 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003204 result_name = "eExecutionSetupError";
3205 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003206 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003207 result_name = "eExecutionTimedOut";
3208 break;
3209 }
3210 return result_name;
3211}
3212
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003213//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003214// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003215//--------------------------------------------------------------
3216
Greg Clayton1b654882010-09-19 02:33:57 +00003217Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00003218 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003219{
Greg Clayton85851dd2010-12-04 00:10:17 +00003220 m_default_settings.reset (new ProcessInstanceSettings (*this,
3221 false,
Caroline Tice91123da2010-09-08 17:48:55 +00003222 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003223}
3224
Greg Clayton1b654882010-09-19 02:33:57 +00003225Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003226{
3227}
3228
3229lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00003230Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003231{
Greg Claytondbe54502010-11-19 03:46:01 +00003232 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3233 false,
3234 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003235 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3236 return new_settings_sp;
3237}
3238
3239//--------------------------------------------------------------
3240// class ProcessInstanceSettings
3241//--------------------------------------------------------------
3242
Greg Clayton85851dd2010-12-04 00:10:17 +00003243ProcessInstanceSettings::ProcessInstanceSettings
3244(
3245 UserSettingsController &owner,
3246 bool live_instance,
3247 const char *name
3248) :
3249 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003250 m_run_args (),
3251 m_env_vars (),
3252 m_input_path (),
3253 m_output_path (),
3254 m_error_path (),
3255 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00003256 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00003257 m_disable_stdio (false),
3258 m_inherit_host_env (true),
3259 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003260{
Caroline Ticef20e8232010-09-09 18:26:37 +00003261 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3262 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3263 // 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 +00003264 // This is true for CreateInstanceName() too.
3265
3266 if (GetInstanceName () == InstanceSettings::InvalidName())
3267 {
3268 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3269 m_owner.RegisterInstanceSettings (this);
3270 }
Caroline Ticef20e8232010-09-09 18:26:37 +00003271
3272 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003273 {
3274 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3275 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00003276 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003277 }
3278}
3279
3280ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00003281 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003282 m_run_args (rhs.m_run_args),
3283 m_env_vars (rhs.m_env_vars),
3284 m_input_path (rhs.m_input_path),
3285 m_output_path (rhs.m_output_path),
3286 m_error_path (rhs.m_error_path),
3287 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00003288 m_disable_aslr (rhs.m_disable_aslr),
3289 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003290{
3291 if (m_instance_name != InstanceSettings::GetDefaultName())
3292 {
3293 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3294 CopyInstanceSettings (pending_settings,false);
3295 m_owner.RemovePendingSettings (m_instance_name);
3296 }
3297}
3298
3299ProcessInstanceSettings::~ProcessInstanceSettings ()
3300{
3301}
3302
3303ProcessInstanceSettings&
3304ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3305{
3306 if (this != &rhs)
3307 {
3308 m_run_args = rhs.m_run_args;
3309 m_env_vars = rhs.m_env_vars;
3310 m_input_path = rhs.m_input_path;
3311 m_output_path = rhs.m_output_path;
3312 m_error_path = rhs.m_error_path;
3313 m_plugin = rhs.m_plugin;
3314 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003315 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00003316 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003317 }
3318
3319 return *this;
3320}
3321
3322
3323void
3324ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3325 const char *index_value,
3326 const char *value,
3327 const ConstString &instance_name,
3328 const SettingEntry &entry,
3329 lldb::VarSetOperationType op,
3330 Error &err,
3331 bool pending)
3332{
3333 if (var_name == RunArgsVarName())
3334 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3335 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003336 {
3337 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003338 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003339 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003340 else if (var_name == InputPathVarName())
3341 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3342 else if (var_name == OutputPathVarName())
3343 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3344 else if (var_name == ErrorPathVarName())
3345 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3346 else if (var_name == PluginVarName())
3347 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003348 else if (var_name == InheritHostEnvVarName())
3349 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003350 else if (var_name == DisableASLRVarName())
3351 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003352 else if (var_name == DisableSTDIOVarName ())
3353 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003354}
3355
3356void
3357ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3358 bool pending)
3359{
3360 if (new_settings.get() == NULL)
3361 return;
3362
3363 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3364
3365 m_run_args = new_process_settings->m_run_args;
3366 m_env_vars = new_process_settings->m_env_vars;
3367 m_input_path = new_process_settings->m_input_path;
3368 m_output_path = new_process_settings->m_output_path;
3369 m_error_path = new_process_settings->m_error_path;
3370 m_plugin = new_process_settings->m_plugin;
3371 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003372 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003373}
3374
Caroline Tice12cecd72010-09-20 21:37:42 +00003375bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003376ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3377 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003378 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003379 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003380{
3381 if (var_name == RunArgsVarName())
3382 {
3383 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003384 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003385 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3386 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003387 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003388 }
3389 else if (var_name == EnvVarsVarName())
3390 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003391 GetHostEnvironmentIfNeeded ();
3392
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003393 if (m_env_vars.size() > 0)
3394 {
3395 std::map<std::string, std::string>::iterator pos;
3396 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3397 {
3398 StreamString value_str;
3399 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3400 value.AppendString (value_str.GetData());
3401 }
3402 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003403 }
3404 else if (var_name == InputPathVarName())
3405 {
3406 value.AppendString (m_input_path.c_str());
3407 }
3408 else if (var_name == OutputPathVarName())
3409 {
3410 value.AppendString (m_output_path.c_str());
3411 }
3412 else if (var_name == ErrorPathVarName())
3413 {
3414 value.AppendString (m_error_path.c_str());
3415 }
3416 else if (var_name == PluginVarName())
3417 {
3418 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3419 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003420 else if (var_name == InheritHostEnvVarName())
3421 {
3422 if (m_inherit_host_env)
3423 value.AppendString ("true");
3424 else
3425 value.AppendString ("false");
3426 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003427 else if (var_name == DisableASLRVarName())
3428 {
3429 if (m_disable_aslr)
3430 value.AppendString ("true");
3431 else
3432 value.AppendString ("false");
3433 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003434 else if (var_name == DisableSTDIOVarName())
3435 {
3436 if (m_disable_stdio)
3437 value.AppendString ("true");
3438 else
3439 value.AppendString ("false");
3440 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003441 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003442 {
3443 if (err)
3444 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3445 return false;
3446 }
3447 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003448}
3449
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003450const ConstString
3451ProcessInstanceSettings::CreateInstanceName ()
3452{
3453 static int instance_count = 1;
3454 StreamString sstr;
3455
3456 sstr.Printf ("process_%d", instance_count);
3457 ++instance_count;
3458
3459 const ConstString ret_val (sstr.GetData());
3460 return ret_val;
3461}
3462
3463const ConstString &
3464ProcessInstanceSettings::RunArgsVarName ()
3465{
3466 static ConstString run_args_var_name ("run-args");
3467
3468 return run_args_var_name;
3469}
3470
3471const ConstString &
3472ProcessInstanceSettings::EnvVarsVarName ()
3473{
3474 static ConstString env_vars_var_name ("env-vars");
3475
3476 return env_vars_var_name;
3477}
3478
3479const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003480ProcessInstanceSettings::InheritHostEnvVarName ()
3481{
3482 static ConstString g_name ("inherit-env");
3483
3484 return g_name;
3485}
3486
3487const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003488ProcessInstanceSettings::InputPathVarName ()
3489{
3490 static ConstString input_path_var_name ("input-path");
3491
3492 return input_path_var_name;
3493}
3494
3495const ConstString &
3496ProcessInstanceSettings::OutputPathVarName ()
3497{
Caroline Tice49e27372010-09-07 18:35:40 +00003498 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003499
3500 return output_path_var_name;
3501}
3502
3503const ConstString &
3504ProcessInstanceSettings::ErrorPathVarName ()
3505{
Caroline Tice49e27372010-09-07 18:35:40 +00003506 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003507
3508 return error_path_var_name;
3509}
3510
3511const ConstString &
3512ProcessInstanceSettings::PluginVarName ()
3513{
3514 static ConstString plugin_var_name ("plugin");
3515
3516 return plugin_var_name;
3517}
3518
3519
3520const ConstString &
3521ProcessInstanceSettings::DisableASLRVarName ()
3522{
3523 static ConstString disable_aslr_var_name ("disable-aslr");
3524
3525 return disable_aslr_var_name;
3526}
3527
Caroline Ticef8da8632010-12-03 18:46:09 +00003528const ConstString &
3529ProcessInstanceSettings::DisableSTDIOVarName ()
3530{
3531 static ConstString disable_stdio_var_name ("disable-stdio");
3532
3533 return disable_stdio_var_name;
3534}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003535
3536//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003537// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003538//--------------------------------------------------
3539
3540SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003541Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003542{
3543 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3544 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3545};
3546
3547
3548lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003549Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003550{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003551 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3552 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3553 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003554};
3555
3556SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003557Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003558{
Greg Clayton85851dd2010-12-04 00:10:17 +00003559 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3560 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3561 { "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." },
3562 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00003563 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3564 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3565 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3566 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00003567 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3568 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3569 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003570};
3571
3572
Jim Ingham5aee1622010-08-09 23:31:02 +00003573