blob: 32769c27fe2b24c40502cc70470bfa90aee8bc33 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham22777012010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
Greg Clayton58be07b2011-01-07 06:08:19 +000040
41//----------------------------------------------------------------------
42// MemoryCache constructor
43//----------------------------------------------------------------------
44Process::MemoryCache::MemoryCache() :
45 m_cache_line_byte_size (512),
46 m_cache_mutex (Mutex::eMutexTypeRecursive),
47 m_cache ()
48{
49}
50
51//----------------------------------------------------------------------
52// Destructor
53//----------------------------------------------------------------------
54Process::MemoryCache::~MemoryCache()
55{
56}
57
58void
59Process::MemoryCache::Clear()
60{
61 Mutex::Locker locker (m_cache_mutex);
62 m_cache.clear();
63}
64
65void
66Process::MemoryCache::Flush (addr_t addr, size_t size)
67{
68 if (size == 0)
69 return;
70
71 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
72 const addr_t end_addr = (addr + size - 1);
73 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
74 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
75
76 Mutex::Locker locker (m_cache_mutex);
77 if (m_cache.empty())
78 return;
79
80 assert ((flush_start_addr % cache_line_byte_size) == 0);
81
82 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
83 {
84 collection::iterator pos = m_cache.find (curr_addr);
85 if (pos != m_cache.end())
86 m_cache.erase(pos);
87 }
88}
89
90size_t
91Process::MemoryCache::Read
92(
93 Process *process,
94 addr_t addr,
95 void *dst,
96 size_t dst_len,
97 Error &error
98)
99{
100 size_t bytes_left = dst_len;
101 if (dst && bytes_left > 0)
102 {
103 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
104 uint8_t *dst_buf = (uint8_t *)dst;
105 addr_t curr_addr = addr - (addr % cache_line_byte_size);
106 addr_t cache_offset = addr - curr_addr;
107 Mutex::Locker locker (m_cache_mutex);
108
109 while (bytes_left > 0)
110 {
111 collection::const_iterator pos = m_cache.find (curr_addr);
112 collection::const_iterator end = m_cache.end ();
113
114 if (pos != end)
115 {
116 size_t curr_read_size = cache_line_byte_size - cache_offset;
117 if (curr_read_size > bytes_left)
118 curr_read_size = bytes_left;
119
120 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
121
122 bytes_left -= curr_read_size;
123 curr_addr += curr_read_size + cache_offset;
124 cache_offset = 0;
125
126 if (bytes_left > 0)
127 {
128 // Get sequential cache page hits
129 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
130 {
131 assert ((curr_addr % cache_line_byte_size) == 0);
132
133 if (pos->first != curr_addr)
134 break;
135
136 curr_read_size = pos->second->GetByteSize();
137 if (curr_read_size > bytes_left)
138 curr_read_size = bytes_left;
139
140 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
141
142 bytes_left -= curr_read_size;
143 curr_addr += curr_read_size;
144
145 // We have a cache page that succeeded to read some bytes
146 // but not an entire page. If this happens, we must cap
147 // off how much data we are able to read...
148 if (pos->second->GetByteSize() != cache_line_byte_size)
149 return dst_len - bytes_left;
150 }
151 }
152 }
153
154 // We need to read from the process
155
156 if (bytes_left > 0)
157 {
158 assert ((curr_addr % cache_line_byte_size) == 0);
159 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
160 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
161 data_buffer_heap_ap->GetBytes(),
162 data_buffer_heap_ap->GetByteSize(),
163 error);
164 if (process_bytes_read == 0)
165 return dst_len - bytes_left;
166
167 if (process_bytes_read != cache_line_byte_size)
168 data_buffer_heap_ap->SetByteSize (process_bytes_read);
169 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
170 // We have read data and put it into the cache, continue through the
171 // loop again to get the data out of the cache...
172 }
173 }
174 }
175
176 return dst_len - bytes_left;
177}
178
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000179Process*
180Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
181{
182 ProcessCreateInstance create_callback = NULL;
183 if (plugin_name)
184 {
185 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
186 if (create_callback)
187 {
188 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
189 if (debugger_ap->CanDebug(target))
190 return debugger_ap.release();
191 }
192 }
193 else
194 {
Greg Claytonc982c762010-07-09 20:39:50 +0000195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000196 {
Greg Claytonc982c762010-07-09 20:39:50 +0000197 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
198 if (debugger_ap->CanDebug(target))
199 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200 }
201 }
202 return NULL;
203}
204
205
206//----------------------------------------------------------------------
207// Process constructor
208//----------------------------------------------------------------------
209Process::Process(Target &target, Listener &listener) :
210 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000211 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000212 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214 m_public_state (eStateUnloaded),
215 m_private_state (eStateUnloaded),
216 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
217 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
218 m_private_state_listener ("lldb.process.internal_state_listener"),
219 m_private_state_control_wait(),
220 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
221 m_stop_id (0),
222 m_thread_index_id (0),
223 m_exit_status (-1),
224 m_exit_string (),
225 m_thread_list (this),
226 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000227 m_image_tokens (),
228 m_listener (listener),
229 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000230 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000231 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000232 m_target_triple (),
233 m_byte_order (eByteOrderHost),
234 m_addr_byte_size (0),
235 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000236 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000237 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000239 m_stdout_data (),
240 m_memory_cache ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000241{
Caroline Tice1559a462010-09-27 00:30:10 +0000242 UpdateInstanceName();
243
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 if (log)
246 log->Printf ("%p Process::Process()", this);
247
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000248 SetEventName (eBroadcastBitStateChanged, "state-changed");
249 SetEventName (eBroadcastBitInterrupt, "interrupt");
250 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
251 SetEventName (eBroadcastBitSTDERR, "stderr-available");
252
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253 listener.StartListeningForEvents (this,
254 eBroadcastBitStateChanged |
255 eBroadcastBitInterrupt |
256 eBroadcastBitSTDOUT |
257 eBroadcastBitSTDERR);
258
259 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
260 eBroadcastBitStateChanged);
261
262 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
263 eBroadcastInternalStateControlStop |
264 eBroadcastInternalStateControlPause |
265 eBroadcastInternalStateControlResume);
266}
267
268//----------------------------------------------------------------------
269// Destructor
270//----------------------------------------------------------------------
271Process::~Process()
272{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274 if (log)
275 log->Printf ("%p Process::~Process()", this);
276 StopPrivateStateThread();
277}
278
279void
280Process::Finalize()
281{
282 // Do any cleanup needed prior to being destructed... Subclasses
283 // that override this method should call this superclass method as well.
284}
285
286void
287Process::RegisterNotificationCallbacks (const Notifications& callbacks)
288{
289 m_notifications.push_back(callbacks);
290 if (callbacks.initialize != NULL)
291 callbacks.initialize (callbacks.baton, this);
292}
293
294bool
295Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
296{
297 std::vector<Notifications>::iterator pos, end = m_notifications.end();
298 for (pos = m_notifications.begin(); pos != end; ++pos)
299 {
300 if (pos->baton == callbacks.baton &&
301 pos->initialize == callbacks.initialize &&
302 pos->process_state_changed == callbacks.process_state_changed)
303 {
304 m_notifications.erase(pos);
305 return true;
306 }
307 }
308 return false;
309}
310
311void
312Process::SynchronouslyNotifyStateChanged (StateType state)
313{
314 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
315 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
316 {
317 if (notification_pos->process_state_changed)
318 notification_pos->process_state_changed (notification_pos->baton, this, state);
319 }
320}
321
322// FIXME: We need to do some work on events before the general Listener sees them.
323// For instance if we are continuing from a breakpoint, we need to ensure that we do
324// the little "insert real insn, step & stop" trick. But we can't do that when the
325// event is delivered by the broadcaster - since that is done on the thread that is
326// waiting for new events, so if we needed more than one event for our handling, we would
327// stall. So instead we do it when we fetch the event off of the queue.
328//
329
330StateType
331Process::GetNextEvent (EventSP &event_sp)
332{
333 StateType state = eStateInvalid;
334
335 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
336 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
337
338 return state;
339}
340
341
342StateType
343Process::WaitForProcessToStop (const TimeValue *timeout)
344{
345 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
346 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
347}
348
349
350StateType
351Process::WaitForState
352(
353 const TimeValue *timeout,
354 const StateType *match_states, const uint32_t num_match_states
355)
356{
357 EventSP event_sp;
358 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000359 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 while (state != eStateInvalid)
361 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000362 // If we are exited or detached, we won't ever get back to any
363 // other valid state...
364 if (state == eStateDetached || state == eStateExited)
365 return state;
366
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367 state = WaitForStateChangedEvents (timeout, event_sp);
368
369 for (i=0; i<num_match_states; ++i)
370 {
371 if (match_states[i] == state)
372 return state;
373 }
374 }
375 return state;
376}
377
Jim Ingham30f9b212010-10-11 23:53:14 +0000378bool
379Process::HijackProcessEvents (Listener *listener)
380{
381 if (listener != NULL)
382 {
383 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
384 }
385 else
386 return false;
387}
388
389void
390Process::RestoreProcessEvents ()
391{
392 RestoreBroadcaster();
393}
394
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395StateType
396Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
397{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399
400 if (log)
401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
402
403 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000404 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
405 this,
406 eBroadcastBitStateChanged,
407 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
409
Caroline Tice20ad3c42010-10-29 21:48:37 +0000410 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000411 if (log)
412 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
413 __FUNCTION__,
414 timeout,
415 StateAsCString(state));
416 return state;
417}
418
419Event *
420Process::PeekAtStateChangedEvents ()
421{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000422 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423
424 if (log)
425 log->Printf ("Process::%s...", __FUNCTION__);
426
427 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000428 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
429 eBroadcastBitStateChanged);
Caroline Tice20ad3c42010-10-29 21:48:37 +0000430 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000431 if (log)
432 {
433 if (event_ptr)
434 {
435 log->Printf ("Process::%s (event_ptr) => %s",
436 __FUNCTION__,
437 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
438 }
439 else
440 {
441 log->Printf ("Process::%s no events found",
442 __FUNCTION__);
443 }
444 }
445 return event_ptr;
446}
447
448StateType
449Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
450{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000451 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452
453 if (log)
454 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
455
456 StateType state = eStateInvalid;
457 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
458 &m_private_state_broadcaster,
459 eBroadcastBitStateChanged,
460 event_sp))
461 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
462
463 // This is a bit of a hack, but when we wait here we could very well return
464 // to the command-line, and that could disable the log, which would render the
465 // log we got above invalid.
466 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
467 if (log)
468 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
469 return state;
470}
471
472bool
473Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
474{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000475 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476
477 if (log)
478 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
479
480 if (control_only)
481 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
482 else
483 return m_private_state_listener.WaitForEvent(timeout, event_sp);
484}
485
486bool
487Process::IsRunning () const
488{
489 return StateIsRunningState (m_public_state.GetValue());
490}
491
492int
493Process::GetExitStatus ()
494{
495 if (m_public_state.GetValue() == eStateExited)
496 return m_exit_status;
497 return -1;
498}
499
Greg Clayton85851dd2010-12-04 00:10:17 +0000500
501void
502Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
503{
504 if (m_inherit_host_env && !m_got_host_env)
505 {
506 m_got_host_env = true;
507 StringList host_env;
508 const size_t host_env_count = Host::GetEnvironment (host_env);
509 for (size_t idx=0; idx<host_env_count; idx++)
510 {
511 const char *env_entry = host_env.GetStringAtIndex (idx);
512 if (env_entry)
513 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000514 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000515 if (equal_pos)
516 {
517 std::string key (env_entry, equal_pos - env_entry);
518 std::string value (equal_pos + 1);
519 if (m_env_vars.find (key) == m_env_vars.end())
520 m_env_vars[key] = value;
521 }
522 }
523 }
524 }
525}
526
527
528size_t
529Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
530{
531 GetHostEnvironmentIfNeeded ();
532
533 dictionary::const_iterator pos, end = m_env_vars.end();
534 for (pos = m_env_vars.begin(); pos != end; ++pos)
535 {
536 std::string env_var_equal_value (pos->first);
537 env_var_equal_value.append(1, '=');
538 env_var_equal_value.append (pos->second);
539 env.AppendArgument (env_var_equal_value.c_str());
540 }
541 return env.GetArgumentCount();
542}
543
544
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000545const char *
546Process::GetExitDescription ()
547{
548 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
549 return m_exit_string.c_str();
550 return NULL;
551}
552
553void
554Process::SetExitStatus (int status, const char *cstr)
555{
Greg Clayton10177aa2010-12-08 05:08:21 +0000556 if (m_private_state.GetValue() != eStateExited)
557 {
558 m_exit_status = status;
559 if (cstr)
560 m_exit_string = cstr;
561 else
562 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563
Greg Clayton10177aa2010-12-08 05:08:21 +0000564 DidExit ();
565
566 SetPrivateState (eStateExited);
567 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000568}
569
570// This static callback can be used to watch for local child processes on
571// the current host. The the child process exits, the process will be
572// found in the global target list (we want to be completely sure that the
573// lldb_private::Process doesn't go away before we can deliver the signal.
574bool
575Process::SetProcessExitStatus
576(
577 void *callback_baton,
578 lldb::pid_t pid,
579 int signo, // Zero for no signal
580 int exit_status // Exit value of process if signal is zero
581)
582{
583 if (signo == 0 || exit_status)
584 {
Greg Clayton66111032010-06-23 01:19:29 +0000585 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586 if (target_sp)
587 {
588 ProcessSP process_sp (target_sp->GetProcessSP());
589 if (process_sp)
590 {
591 const char *signal_cstr = NULL;
592 if (signo)
593 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
594
595 process_sp->SetExitStatus (exit_status, signal_cstr);
596 }
597 }
598 return true;
599 }
600 return false;
601}
602
603
604uint32_t
605Process::GetNextThreadIndexID ()
606{
607 return ++m_thread_index_id;
608}
609
610StateType
611Process::GetState()
612{
613 // If any other threads access this we will need a mutex for it
614 return m_public_state.GetValue ();
615}
616
617void
618Process::SetPublicState (StateType new_state)
619{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000620 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621 if (log)
622 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
623 m_public_state.SetValue (new_state);
624}
625
626StateType
627Process::GetPrivateState ()
628{
629 return m_private_state.GetValue();
630}
631
632void
633Process::SetPrivateState (StateType new_state)
634{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000635 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636 bool state_changed = false;
637
638 if (log)
639 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
640
641 Mutex::Locker locker(m_private_state.GetMutex());
642
643 const StateType old_state = m_private_state.GetValueNoLock ();
644 state_changed = old_state != new_state;
645 if (state_changed)
646 {
647 m_private_state.SetValueNoLock (new_state);
648 if (StateIsStoppedState(new_state))
649 {
650 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000651 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 if (log)
653 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
654 }
655 // Use our target to get a shared pointer to ourselves...
656 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
657 }
658 else
659 {
660 if (log)
661 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
662 }
663}
664
665
666uint32_t
667Process::GetStopID() const
668{
669 return m_stop_id;
670}
671
672addr_t
673Process::GetImageInfoAddress()
674{
675 return LLDB_INVALID_ADDRESS;
676}
677
Greg Clayton8f343b02010-11-04 01:54:29 +0000678//----------------------------------------------------------------------
679// LoadImage
680//
681// This function provides a default implementation that works for most
682// unix variants. Any Process subclasses that need to do shared library
683// loading differently should override LoadImage and UnloadImage and
684// do what is needed.
685//----------------------------------------------------------------------
686uint32_t
687Process::LoadImage (const FileSpec &image_spec, Error &error)
688{
689 DynamicLoader *loader = GetDynamicLoader();
690 if (loader)
691 {
692 error = loader->CanLoadImage();
693 if (error.Fail())
694 return LLDB_INVALID_IMAGE_TOKEN;
695 }
696
697 if (error.Success())
698 {
699 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
700 if (thread_sp == NULL)
701 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
702
703 if (thread_sp)
704 {
705 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
706
707 if (frame_sp)
708 {
709 ExecutionContext exe_ctx;
710 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000711 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000712 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000713 StreamString expr;
714 char path[PATH_MAX];
715 image_spec.GetPath(path, sizeof(path));
716 expr.Printf("dlopen (\"%s\", 2)", path);
717 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000718 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000719 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000720 if (result_valobj_sp->GetError().Success())
721 {
722 Scalar scalar;
723 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
724 {
725 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
726 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
727 {
728 uint32_t image_token = m_image_tokens.size();
729 m_image_tokens.push_back (image_ptr);
730 return image_token;
731 }
732 }
733 }
734 }
735 }
736 }
737 return LLDB_INVALID_IMAGE_TOKEN;
738}
739
740//----------------------------------------------------------------------
741// UnloadImage
742//
743// This function provides a default implementation that works for most
744// unix variants. Any Process subclasses that need to do shared library
745// loading differently should override LoadImage and UnloadImage and
746// do what is needed.
747//----------------------------------------------------------------------
748Error
749Process::UnloadImage (uint32_t image_token)
750{
751 Error error;
752 if (image_token < m_image_tokens.size())
753 {
754 const addr_t image_addr = m_image_tokens[image_token];
755 if (image_addr == LLDB_INVALID_ADDRESS)
756 {
757 error.SetErrorString("image already unloaded");
758 }
759 else
760 {
761 DynamicLoader *loader = GetDynamicLoader();
762 if (loader)
763 error = loader->CanLoadImage();
764
765 if (error.Success())
766 {
767 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
768 if (thread_sp == NULL)
769 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
770
771 if (thread_sp)
772 {
773 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
774
775 if (frame_sp)
776 {
777 ExecutionContext exe_ctx;
778 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000779 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000780 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000781 StreamString expr;
782 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
783 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000784 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000785 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000786 if (result_valobj_sp->GetError().Success())
787 {
788 Scalar scalar;
789 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
790 {
791 if (scalar.UInt(1))
792 {
793 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
794 }
795 else
796 {
797 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
798 }
799 }
800 }
801 else
802 {
803 error = result_valobj_sp->GetError();
804 }
805 }
806 }
807 }
808 }
809 }
810 else
811 {
812 error.SetErrorString("invalid image token");
813 }
814 return error;
815}
816
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817DynamicLoader *
818Process::GetDynamicLoader()
819{
820 return NULL;
821}
822
823const ABI *
824Process::GetABI()
825{
826 ConstString& triple = m_target_triple;
827
828 if (triple.IsEmpty())
829 return NULL;
830
831 if (m_abi_sp.get() == NULL)
832 {
833 m_abi_sp.reset(ABI::FindPlugin(triple));
834 }
835
836 return m_abi_sp.get();
837}
838
Jim Ingham22777012010-09-23 02:01:19 +0000839LanguageRuntime *
840Process::GetLanguageRuntime(lldb::LanguageType language)
841{
842 LanguageRuntimeCollection::iterator pos;
843 pos = m_language_runtimes.find (language);
844 if (pos == m_language_runtimes.end())
845 {
846 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
847
848 m_language_runtimes[language]
849 = runtime;
850 return runtime.get();
851 }
852 else
853 return (*pos).second.get();
854}
855
856CPPLanguageRuntime *
857Process::GetCPPLanguageRuntime ()
858{
859 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
860 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
861 return static_cast<CPPLanguageRuntime *> (runtime);
862 return NULL;
863}
864
865ObjCLanguageRuntime *
866Process::GetObjCLanguageRuntime ()
867{
868 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
869 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
870 return static_cast<ObjCLanguageRuntime *> (runtime);
871 return NULL;
872}
873
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874BreakpointSiteList &
875Process::GetBreakpointSiteList()
876{
877 return m_breakpoint_site_list;
878}
879
880const BreakpointSiteList &
881Process::GetBreakpointSiteList() const
882{
883 return m_breakpoint_site_list;
884}
885
886
887void
888Process::DisableAllBreakpointSites ()
889{
890 m_breakpoint_site_list.SetEnabledForAll (false);
891}
892
893Error
894Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
895{
896 Error error (DisableBreakpointSiteByID (break_id));
897
898 if (error.Success())
899 m_breakpoint_site_list.Remove(break_id);
900
901 return error;
902}
903
904Error
905Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
906{
907 Error error;
908 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
909 if (bp_site_sp)
910 {
911 if (bp_site_sp->IsEnabled())
912 error = DisableBreakpoint (bp_site_sp.get());
913 }
914 else
915 {
916 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
917 }
918
919 return error;
920}
921
922Error
923Process::EnableBreakpointSiteByID (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 = EnableBreakpoint (bp_site_sp.get());
931 }
932 else
933 {
934 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
935 }
936 return error;
937}
938
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000939lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
941{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000942 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943 if (load_addr != LLDB_INVALID_ADDRESS)
944 {
945 BreakpointSiteSP bp_site_sp;
946
947 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
948 // create a new breakpoint site and add it.
949
950 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
951
952 if (bp_site_sp)
953 {
954 bp_site_sp->AddOwner (owner);
955 owner->SetBreakpointSite (bp_site_sp);
956 return bp_site_sp->GetID();
957 }
958 else
959 {
960 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
961 if (bp_site_sp)
962 {
963 if (EnableBreakpoint (bp_site_sp.get()).Success())
964 {
965 owner->SetBreakpointSite (bp_site_sp);
966 return m_breakpoint_site_list.Add (bp_site_sp);
967 }
968 }
969 }
970 }
971 // We failed to enable the breakpoint
972 return LLDB_INVALID_BREAK_ID;
973
974}
975
976void
977Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
978{
979 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
980 if (num_owners == 0)
981 {
982 DisableBreakpoint(bp_site_sp.get());
983 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
984 }
985}
986
987
988size_t
989Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
990{
991 size_t bytes_removed = 0;
992 addr_t intersect_addr;
993 size_t intersect_size;
994 size_t opcode_offset;
995 size_t idx;
996 BreakpointSiteSP bp;
997
998 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
999 {
1000 if (bp->GetType() == BreakpointSite::eSoftware)
1001 {
1002 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1003 {
1004 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1005 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1006 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1007 size_t buf_offset = intersect_addr - bp_addr;
1008 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1009 }
1010 }
1011 }
1012 return bytes_removed;
1013}
1014
1015
1016Error
1017Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1018{
1019 Error error;
1020 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001021 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022 const addr_t bp_addr = bp_site->GetLoadAddress();
1023 if (log)
1024 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1025 if (bp_site->IsEnabled())
1026 {
1027 if (log)
1028 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1029 return error;
1030 }
1031
1032 if (bp_addr == LLDB_INVALID_ADDRESS)
1033 {
1034 error.SetErrorString("BreakpointSite contains an invalid load address.");
1035 return error;
1036 }
1037 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1038 // trap for the breakpoint site
1039 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1040
1041 if (bp_opcode_size == 0)
1042 {
1043 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1044 }
1045 else
1046 {
1047 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1048
1049 if (bp_opcode_bytes == NULL)
1050 {
1051 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1052 return error;
1053 }
1054
1055 // Save the original opcode by reading it
1056 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1057 {
1058 // Write a software breakpoint in place of the original opcode
1059 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1060 {
1061 uint8_t verify_bp_opcode_bytes[64];
1062 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1063 {
1064 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1065 {
1066 bp_site->SetEnabled(true);
1067 bp_site->SetType (BreakpointSite::eSoftware);
1068 if (log)
1069 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1070 bp_site->GetID(),
1071 (uint64_t)bp_addr);
1072 }
1073 else
1074 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1075 }
1076 else
1077 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1078 }
1079 else
1080 error.SetErrorString("Unable to write breakpoint trap to memory.");
1081 }
1082 else
1083 error.SetErrorString("Unable to read memory at breakpoint address.");
1084 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001085 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1087 bp_site->GetID(),
1088 (uint64_t)bp_addr,
1089 error.AsCString());
1090 return error;
1091}
1092
1093Error
1094Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1095{
1096 Error error;
1097 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001098 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 addr_t bp_addr = bp_site->GetLoadAddress();
1100 lldb::user_id_t breakID = bp_site->GetID();
1101 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001102 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103
1104 if (bp_site->IsHardware())
1105 {
1106 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1107 }
1108 else if (bp_site->IsEnabled())
1109 {
1110 const size_t break_op_size = bp_site->GetByteSize();
1111 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1112 if (break_op_size > 0)
1113 {
1114 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001115 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001116 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 bool break_op_found = false;
1118
1119 // Read the breakpoint opcode
1120 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1121 {
1122 bool verify = false;
1123 // Make sure we have the a breakpoint opcode exists at this address
1124 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1125 {
1126 break_op_found = true;
1127 // We found a valid breakpoint opcode at this address, now restore
1128 // the saved opcode.
1129 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1130 {
1131 verify = true;
1132 }
1133 else
1134 error.SetErrorString("Memory write failed when restoring original opcode.");
1135 }
1136 else
1137 {
1138 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1139 // Set verify to true and so we can check if the original opcode has already been restored
1140 verify = true;
1141 }
1142
1143 if (verify)
1144 {
Greg Claytonc982c762010-07-09 20:39:50 +00001145 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001146 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147 // Verify that our original opcode made it back to the inferior
1148 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1149 {
1150 // compare the memory we just read with the original opcode
1151 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1152 {
1153 // SUCCESS
1154 bp_site->SetEnabled(false);
1155 if (log)
1156 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1157 return error;
1158 }
1159 else
1160 {
1161 if (break_op_found)
1162 error.SetErrorString("Failed to restore original opcode.");
1163 }
1164 }
1165 else
1166 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1167 }
1168 }
1169 else
1170 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1171 }
1172 }
1173 else
1174 {
1175 if (log)
1176 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1177 return error;
1178 }
1179
1180 if (log)
1181 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1182 bp_site->GetID(),
1183 (uint64_t)bp_addr,
1184 error.AsCString());
1185 return error;
1186
1187}
1188
Greg Clayton58be07b2011-01-07 06:08:19 +00001189// Comment out line below to disable memory caching
1190#define ENABLE_MEMORY_CACHING
1191// Uncomment to verify memory caching works after making changes to caching code
1192//#define VERIFY_MEMORY_READS
1193
1194#if defined (ENABLE_MEMORY_CACHING)
1195
1196#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197
1198size_t
1199Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1200{
Greg Clayton58be07b2011-01-07 06:08:19 +00001201 // Memory caching is enabled, with debug verification
1202 if (buf && size)
1203 {
1204 // Uncomment the line below to make sure memory caching is working.
1205 // I ran this through the test suite and got no assertions, so I am
1206 // pretty confident this is working well. If any changes are made to
1207 // memory caching, uncomment the line below and test your changes!
1208
1209 // Verify all memory reads by using the cache first, then redundantly
1210 // reading the same memory from the inferior and comparing to make sure
1211 // everything is exactly the same.
1212 std::string verify_buf (size, '\0');
1213 assert (verify_buf.size() == size);
1214 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1215 Error verify_error;
1216 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1217 assert (cache_bytes_read == verify_bytes_read);
1218 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1219 assert (verify_error.Success() == error.Success());
1220 return cache_bytes_read;
1221 }
1222 return 0;
1223}
1224
1225#else // #if defined (VERIFY_MEMORY_READS)
1226
1227size_t
1228Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1229{
1230 // Memory caching enabled, no verification
1231 return m_memory_cache.Read (this, addr, buf, size, error);
1232}
1233
1234#endif // #else for #if defined (VERIFY_MEMORY_READS)
1235
1236#else // #if defined (ENABLE_MEMORY_CACHING)
1237
1238size_t
1239Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1240{
1241 // Memory caching is disabled
1242 return ReadMemoryFromInferior (addr, buf, size, error);
1243}
1244
1245#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1246
1247
1248size_t
1249Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1250{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001251 if (buf == NULL || size == 0)
1252 return 0;
1253
1254 size_t bytes_read = 0;
1255 uint8_t *bytes = (uint8_t *)buf;
1256
1257 while (bytes_read < size)
1258 {
1259 const size_t curr_size = size - bytes_read;
1260 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1261 bytes + bytes_read,
1262 curr_size,
1263 error);
1264 bytes_read += curr_bytes_read;
1265 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1266 break;
1267 }
1268
1269 // Replace any software breakpoint opcodes that fall into this range back
1270 // into "buf" before we return
1271 if (bytes_read > 0)
1272 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1273 return bytes_read;
1274}
1275
Greg Clayton58a4c462010-12-16 20:01:20 +00001276uint64_t
1277Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1278{
1279 if (integer_byte_size > sizeof(uint64_t))
1280 {
1281 error.SetErrorString ("unsupported integer size");
1282 }
1283 else
1284 {
1285 uint8_t tmp[sizeof(uint64_t)];
1286 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1287 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1288 {
1289 uint32_t offset = 0;
1290 return data.GetMaxU64 (&offset, integer_byte_size);
1291 }
1292 }
1293 // Any plug-in that doesn't return success a memory read with the number
1294 // of bytes that were requested should be setting the error
1295 assert (error.Fail());
1296 return 0;
1297}
1298
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299size_t
1300Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1301{
1302 size_t bytes_written = 0;
1303 const uint8_t *bytes = (const uint8_t *)buf;
1304
1305 while (bytes_written < size)
1306 {
1307 const size_t curr_size = size - bytes_written;
1308 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1309 bytes + bytes_written,
1310 curr_size,
1311 error);
1312 bytes_written += curr_bytes_written;
1313 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1314 break;
1315 }
1316 return bytes_written;
1317}
1318
1319size_t
1320Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1321{
Greg Clayton58be07b2011-01-07 06:08:19 +00001322#if defined (ENABLE_MEMORY_CACHING)
1323 m_memory_cache.Flush (addr, size);
1324#endif
1325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326 if (buf == NULL || size == 0)
1327 return 0;
1328 // We need to write any data that would go where any current software traps
1329 // (enabled software breakpoints) any software traps (breakpoints) that we
1330 // may have placed in our tasks memory.
1331
1332 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1333 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1334
1335 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1336 return DoWriteMemory(addr, buf, size, error);
1337
1338 BreakpointSiteList::collection::const_iterator pos;
1339 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001340 addr_t intersect_addr = 0;
1341 size_t intersect_size = 0;
1342 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 const uint8_t *ubuf = (const uint8_t *)buf;
1344
1345 for (pos = iter; pos != end; ++pos)
1346 {
1347 BreakpointSiteSP bp;
1348 bp = pos->second;
1349
1350 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1351 assert(addr <= intersect_addr && intersect_addr < addr + size);
1352 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1353 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1354
1355 // Check for bytes before this breakpoint
1356 const addr_t curr_addr = addr + bytes_written;
1357 if (intersect_addr > curr_addr)
1358 {
1359 // There are some bytes before this breakpoint that we need to
1360 // just write to memory
1361 size_t curr_size = intersect_addr - curr_addr;
1362 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1363 ubuf + bytes_written,
1364 curr_size,
1365 error);
1366 bytes_written += curr_bytes_written;
1367 if (curr_bytes_written != curr_size)
1368 {
1369 // We weren't able to write all of the requested bytes, we
1370 // are done looping and will return the number of bytes that
1371 // we have written so far.
1372 break;
1373 }
1374 }
1375
1376 // Now write any bytes that would cover up any software breakpoints
1377 // directly into the breakpoint opcode buffer
1378 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1379 bytes_written += intersect_size;
1380 }
1381
1382 // Write any remaining bytes after the last breakpoint if we have any left
1383 if (bytes_written < size)
1384 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1385 ubuf + bytes_written,
1386 size - bytes_written,
1387 error);
1388
1389 return bytes_written;
1390}
1391
1392addr_t
1393Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1394{
1395 // Fixme: we should track the blocks we've allocated, and clean them up...
1396 // We could even do our own allocator here if that ends up being more efficient.
1397 return DoAllocateMemory (size, permissions, error);
1398}
1399
1400Error
1401Process::DeallocateMemory (addr_t ptr)
1402{
1403 return DoDeallocateMemory (ptr);
1404}
1405
1406
1407Error
1408Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1409{
1410 Error error;
1411 error.SetErrorString("watchpoints are not supported");
1412 return error;
1413}
1414
1415Error
1416Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1417{
1418 Error error;
1419 error.SetErrorString("watchpoints are not supported");
1420 return error;
1421}
1422
1423StateType
1424Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1425{
1426 StateType state;
1427 // Now wait for the process to launch and return control to us, and then
1428 // call DidLaunch:
1429 while (1)
1430 {
1431 // FIXME: Might want to put a timeout in here:
1432 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1433 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1434 break;
1435 else
1436 HandlePrivateEvent (event_sp);
1437 }
1438 return state;
1439}
1440
1441Error
1442Process::Launch
1443(
1444 char const *argv[],
1445 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001446 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447 const char *stdin_path,
1448 const char *stdout_path,
1449 const char *stderr_path
1450)
1451{
1452 Error error;
1453 m_target_triple.Clear();
1454 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001455 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456
1457 Module *exe_module = m_target.GetExecutableModule().get();
1458 if (exe_module)
1459 {
1460 char exec_file_path[PATH_MAX];
1461 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1462 if (exe_module->GetFileSpec().Exists())
1463 {
1464 error = WillLaunch (exe_module);
1465 if (error.Success())
1466 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001467 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468 // The args coming in should not contain the application name, the
1469 // lldb_private::Process class will add this in case the executable
1470 // gets resolved to a different file than was given on the command
1471 // line (like when an applicaiton bundle is specified and will
1472 // resolve to the contained exectuable file, or the file given was
1473 // a symlink or other file system link that resolves to a different
1474 // file).
1475
1476 // Get the resolved exectuable path
1477
1478 // Make a new argument vector
1479 std::vector<const char *> exec_path_plus_argv;
1480 // Append the resolved executable path
1481 exec_path_plus_argv.push_back (exec_file_path);
1482
1483 // Push all args if there are any
1484 if (argv)
1485 {
1486 for (int i = 0; argv[i]; ++i)
1487 exec_path_plus_argv.push_back(argv[i]);
1488 }
1489
1490 // Push a NULL to terminate the args.
1491 exec_path_plus_argv.push_back(NULL);
1492
1493 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001494 error = DoLaunch (exe_module,
1495 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1496 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001497 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001498 stdin_path,
1499 stdout_path,
1500 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001501
1502 if (error.Fail())
1503 {
1504 if (GetID() != LLDB_INVALID_PROCESS_ID)
1505 {
1506 SetID (LLDB_INVALID_PROCESS_ID);
1507 const char *error_string = error.AsCString();
1508 if (error_string == NULL)
1509 error_string = "launch failed";
1510 SetExitStatus (-1, error_string);
1511 }
1512 }
1513 else
1514 {
1515 EventSP event_sp;
1516 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1517
1518 if (state == eStateStopped || state == eStateCrashed)
1519 {
1520 DidLaunch ();
1521
1522 // This delays passing the stopped event to listeners till DidLaunch gets
1523 // a chance to complete...
1524 HandlePrivateEvent (event_sp);
1525 StartPrivateStateThread ();
1526 }
1527 else if (state == eStateExited)
1528 {
1529 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1530 // not likely to work, and return an invalid pid.
1531 HandlePrivateEvent (event_sp);
1532 }
1533 }
1534 }
1535 }
1536 else
1537 {
1538 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1539 }
1540 }
1541 return error;
1542}
1543
1544Error
1545Process::CompleteAttach ()
1546{
1547 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001548
1549 if (GetID() == LLDB_INVALID_PROCESS_ID)
1550 {
1551 error.SetErrorString("no process");
1552 }
1553
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001554 EventSP event_sp;
1555 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1556 if (state == eStateStopped || state == eStateCrashed)
1557 {
1558 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001559 // Figure out which one is the executable, and set that in our target:
1560 ModuleList &modules = GetTarget().GetImages();
1561
1562 size_t num_modules = modules.GetSize();
1563 for (int i = 0; i < num_modules; i++)
1564 {
1565 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1566 if (module_sp->IsExecutable())
1567 {
1568 ModuleSP exec_module = GetTarget().GetExecutableModule();
1569 if (!exec_module || exec_module != module_sp)
1570 {
1571
1572 GetTarget().SetExecutableModule (module_sp, false);
1573 }
1574 break;
1575 }
1576 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001577
1578 // This delays passing the stopped event to listeners till DidLaunch gets
1579 // a chance to complete...
1580 HandlePrivateEvent(event_sp);
1581 StartPrivateStateThread();
1582 }
1583 else
1584 {
1585 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1586 // not likely to work, and return an invalid pid.
1587 if (state == eStateExited)
1588 HandlePrivateEvent (event_sp);
1589 error.SetErrorStringWithFormat("invalid state after attach: %s",
1590 lldb_private::StateAsCString(state));
1591 }
1592 return error;
1593}
1594
1595Error
1596Process::Attach (lldb::pid_t attach_pid)
1597{
1598
1599 m_target_triple.Clear();
1600 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001601 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001602
Jim Ingham5aee1622010-08-09 23:31:02 +00001603 // Find the process and its architecture. Make sure it matches the architecture
1604 // of the current Target, and if not adjust it.
1605
1606 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1607 if (attach_spec != GetTarget().GetArchitecture())
1608 {
1609 // Set the architecture on the target.
1610 GetTarget().SetArchitecture(attach_spec);
1611 }
1612
Greg Claytonc982c762010-07-09 20:39:50 +00001613 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614 if (error.Success())
1615 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001616 SetPublicState (eStateAttaching);
1617
Greg Claytonc982c762010-07-09 20:39:50 +00001618 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001619 if (error.Success())
1620 {
1621 error = CompleteAttach();
1622 }
1623 else
1624 {
1625 if (GetID() != LLDB_INVALID_PROCESS_ID)
1626 {
1627 SetID (LLDB_INVALID_PROCESS_ID);
1628 const char *error_string = error.AsCString();
1629 if (error_string == NULL)
1630 error_string = "attach failed";
1631
1632 SetExitStatus(-1, error_string);
1633 }
1634 }
1635 }
1636 return error;
1637}
1638
1639Error
1640Process::Attach (const char *process_name, bool wait_for_launch)
1641{
1642 m_target_triple.Clear();
1643 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001644 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001645
1646 // Find the process and its architecture. Make sure it matches the architecture
1647 // of the current Target, and if not adjust it.
1648
Jim Ingham2ecb7422010-08-17 21:54:19 +00001649 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001650 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001651 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001652 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001653 {
1654 // Set the architecture on the target.
1655 GetTarget().SetArchitecture(attach_spec);
1656 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001657 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001658
Greg Claytonc982c762010-07-09 20:39:50 +00001659 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660 if (error.Success())
1661 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001662 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001663 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 if (error.Fail())
1665 {
1666 if (GetID() != LLDB_INVALID_PROCESS_ID)
1667 {
1668 SetID (LLDB_INVALID_PROCESS_ID);
1669 const char *error_string = error.AsCString();
1670 if (error_string == NULL)
1671 error_string = "attach failed";
1672
1673 SetExitStatus(-1, error_string);
1674 }
1675 }
1676 else
1677 {
1678 error = CompleteAttach();
1679 }
1680 }
1681 return error;
1682}
1683
1684Error
1685Process::Resume ()
1686{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001687 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688 if (log)
1689 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1690
1691 Error error (WillResume());
1692 // Tell the process it is about to resume before the thread list
1693 if (error.Success())
1694 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001695 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001696 // can let all of our threads know that they are about to be
1697 // resumed. Threads will each be called with
1698 // Thread::WillResume(StateType) where StateType contains the state
1699 // that they are supposed to have when the process is resumed
1700 // (suspended/running/stepping). Threads should also check
1701 // their resume signal in lldb::Thread::GetResumeSignal()
1702 // to see if they are suppoed to start back up with a signal.
1703 if (m_thread_list.WillResume())
1704 {
1705 error = DoResume();
1706 if (error.Success())
1707 {
1708 DidResume();
1709 m_thread_list.DidResume();
1710 }
1711 }
1712 else
1713 {
1714 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1715 }
1716 }
1717 return error;
1718}
1719
1720Error
1721Process::Halt ()
1722{
1723 Error error (WillHalt());
1724
1725 if (error.Success())
1726 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001727
1728 bool caused_stop = false;
1729 EventSP event_sp;
1730
1731 // Pause our private state thread so we can ensure no one else eats
1732 // the stop event out from under us.
1733 PausePrivateStateThread();
1734
1735 // Ask the process subclass to actually halt our process
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001736 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001738 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001739 // If "caused_stop" is true, then DoHalt stopped the process. If
1740 // "caused_stop" is false, the process was already stopped.
1741 // If the DoHalt caused the process to stop, then we want to catch
1742 // this event and set the interrupted bool to true before we pass
1743 // this along so clients know that the process was interrupted by
1744 // a halt command.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001745 if (caused_stop)
1746 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001747 // Wait for 2 seconds for the process to stop.
1748 TimeValue timeout_time;
1749 timeout_time = TimeValue::Now();
1750 timeout_time.OffsetWithSeconds(2);
1751 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1752
1753 if (state == eStateInvalid)
1754 {
1755 // We timeout out and didn't get a stop event...
1756 error.SetErrorString ("Halt timed out.");
1757 }
1758 else
1759 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001760 if (StateIsStoppedState (state))
1761 {
1762 // We caused the process to interrupt itself, so mark this
1763 // as such in the stop event so clients can tell an interrupted
1764 // process from a natural stop
1765 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1766 }
1767 else
1768 {
1769 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1770 if (log)
1771 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1772 error.SetErrorString ("Did not get stopped event after halt.");
1773 }
1774 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001775 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001776 DidHalt();
1777
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001778 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001779 // Resume our private state thread before we post the event (if any)
1780 ResumePrivateStateThread();
1781
1782 // Post any event we might have consumed. If all goes well, we will have
1783 // stopped the process, intercepted the event and set the interrupted
Jim Inghamf48169b2010-11-30 02:22:11 +00001784 // bool in the event. Post it to the private event queue and that will end up
1785 // correctly setting the state.
Greg Clayton3af9ea52010-11-18 05:57:03 +00001786 if (event_sp)
Caroline Ticeefed6132010-11-19 20:47:54 +00001787 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789 }
1790 return error;
1791}
1792
1793Error
1794Process::Detach ()
1795{
1796 Error error (WillDetach());
1797
1798 if (error.Success())
1799 {
1800 DisableAllBreakpointSites();
1801 error = DoDetach();
1802 if (error.Success())
1803 {
1804 DidDetach();
1805 StopPrivateStateThread();
1806 }
1807 }
1808 return error;
1809}
1810
1811Error
1812Process::Destroy ()
1813{
1814 Error error (WillDestroy());
1815 if (error.Success())
1816 {
1817 DisableAllBreakpointSites();
1818 error = DoDestroy();
1819 if (error.Success())
1820 {
1821 DidDestroy();
1822 StopPrivateStateThread();
1823 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001824 m_stdio_communication.StopReadThread();
1825 m_stdio_communication.Disconnect();
1826 if (m_process_input_reader && m_process_input_reader->IsActive())
1827 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1828 if (m_process_input_reader)
1829 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 }
1831 return error;
1832}
1833
1834Error
1835Process::Signal (int signal)
1836{
1837 Error error (WillSignal());
1838 if (error.Success())
1839 {
1840 error = DoSignal(signal);
1841 if (error.Success())
1842 DidSignal();
1843 }
1844 return error;
1845}
1846
1847UnixSignals &
1848Process::GetUnixSignals ()
1849{
1850 return m_unix_signals;
1851}
1852
1853Target &
1854Process::GetTarget ()
1855{
1856 return m_target;
1857}
1858
1859const Target &
1860Process::GetTarget () const
1861{
1862 return m_target;
1863}
1864
1865uint32_t
1866Process::GetAddressByteSize()
1867{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001868 if (m_addr_byte_size == 0)
1869 return m_target.GetArchitecture().GetAddressByteSize();
1870 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871}
1872
1873bool
1874Process::ShouldBroadcastEvent (Event *event_ptr)
1875{
1876 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1877 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001878 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001879
1880 switch (state)
1881 {
1882 case eStateAttaching:
1883 case eStateLaunching:
1884 case eStateDetached:
1885 case eStateExited:
1886 case eStateUnloaded:
1887 // These events indicate changes in the state of the debugging session, always report them.
1888 return_value = true;
1889 break;
1890 case eStateInvalid:
1891 // We stopped for no apparent reason, don't report it.
1892 return_value = false;
1893 break;
1894 case eStateRunning:
1895 case eStateStepping:
1896 // If we've started the target running, we handle the cases where we
1897 // are already running and where there is a transition from stopped to
1898 // running differently.
1899 // running -> running: Automatically suppress extra running events
1900 // stopped -> running: Report except when there is one or more no votes
1901 // and no yes votes.
1902 SynchronouslyNotifyStateChanged (state);
1903 switch (m_public_state.GetValue())
1904 {
1905 case eStateRunning:
1906 case eStateStepping:
1907 // We always suppress multiple runnings with no PUBLIC stop in between.
1908 return_value = false;
1909 break;
1910 default:
1911 // TODO: make this work correctly. For now always report
1912 // run if we aren't running so we don't miss any runnning
1913 // events. If I run the lldb/test/thread/a.out file and
1914 // break at main.cpp:58, run and hit the breakpoints on
1915 // multiple threads, then somehow during the stepping over
1916 // of all breakpoints no run gets reported.
1917 return_value = true;
1918
1919 // This is a transition from stop to run.
1920 switch (m_thread_list.ShouldReportRun (event_ptr))
1921 {
1922 case eVoteYes:
1923 case eVoteNoOpinion:
1924 return_value = true;
1925 break;
1926 case eVoteNo:
1927 return_value = false;
1928 break;
1929 }
1930 break;
1931 }
1932 break;
1933 case eStateStopped:
1934 case eStateCrashed:
1935 case eStateSuspended:
1936 {
1937 // We've stopped. First see if we're going to restart the target.
1938 // If we are going to stop, then we always broadcast the event.
1939 // 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 +00001940 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001941 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001942 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001943 if (log)
1944 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001945 return true;
1946 }
1947 else
1948 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001949 RefreshStateAfterStop ();
1950
1951 if (m_thread_list.ShouldStop (event_ptr) == false)
1952 {
1953 switch (m_thread_list.ShouldReportStop (event_ptr))
1954 {
1955 case eVoteYes:
1956 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00001957 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959 case eVoteNo:
1960 return_value = false;
1961 break;
1962 }
1963
1964 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001965 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001966 Resume ();
1967 }
1968 else
1969 {
1970 return_value = true;
1971 SynchronouslyNotifyStateChanged (state);
1972 }
1973 }
1974 }
1975 }
1976
1977 if (log)
1978 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1979 return return_value;
1980}
1981
1982//------------------------------------------------------------------
1983// Thread Queries
1984//------------------------------------------------------------------
1985
1986ThreadList &
1987Process::GetThreadList ()
1988{
1989 return m_thread_list;
1990}
1991
1992const ThreadList &
1993Process::GetThreadList () const
1994{
1995 return m_thread_list;
1996}
1997
1998
1999bool
2000Process::StartPrivateStateThread ()
2001{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002002 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003
2004 if (log)
2005 log->Printf ("Process::%s ( )", __FUNCTION__);
2006
2007 // Create a thread that watches our internal state and controls which
2008 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002009 char thread_name[1024];
2010 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2011 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2013}
2014
2015void
2016Process::PausePrivateStateThread ()
2017{
2018 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2019}
2020
2021void
2022Process::ResumePrivateStateThread ()
2023{
2024 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2025}
2026
2027void
2028Process::StopPrivateStateThread ()
2029{
2030 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2031}
2032
2033void
2034Process::ControlPrivateStateThread (uint32_t signal)
2035{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002036 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002037
2038 assert (signal == eBroadcastInternalStateControlStop ||
2039 signal == eBroadcastInternalStateControlPause ||
2040 signal == eBroadcastInternalStateControlResume);
2041
2042 if (log)
2043 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
2044
2045 // Signal the private state thread
2046 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
2047 {
2048 TimeValue timeout_time;
2049 bool timed_out;
2050
2051 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2052
2053 timeout_time = TimeValue::Now();
2054 timeout_time.OffsetWithSeconds(2);
2055 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2056 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2057
2058 if (signal == eBroadcastInternalStateControlStop)
2059 {
2060 if (timed_out)
2061 Host::ThreadCancel (m_private_state_thread, NULL);
2062
2063 thread_result_t result = NULL;
2064 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002065 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 }
2067 }
2068}
2069
2070void
2071Process::HandlePrivateEvent (EventSP &event_sp)
2072{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002073 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2075 // See if we should broadcast this state to external clients?
2076 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2077 if (log)
2078 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2079
2080 if (should_broadcast)
2081 {
2082 if (log)
2083 {
2084 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2085 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002086 if (StateIsRunningState (internal_state))
2087 PushProcessInputReader ();
2088 else
2089 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2091 BroadcastEvent (event_sp);
2092 }
2093 else
2094 {
2095 if (log)
2096 {
2097 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2098 }
2099 }
2100}
2101
2102void *
2103Process::PrivateStateThread (void *arg)
2104{
2105 Process *proc = static_cast<Process*> (arg);
2106 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 return result;
2108}
2109
2110void *
2111Process::RunPrivateStateThread ()
2112{
2113 bool control_only = false;
2114 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2115
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002116 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 if (log)
2118 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2119
2120 bool exit_now = false;
2121 while (!exit_now)
2122 {
2123 EventSP event_sp;
2124 WaitForEventsPrivate (NULL, event_sp, control_only);
2125 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2126 {
2127 switch (event_sp->GetType())
2128 {
2129 case eBroadcastInternalStateControlStop:
2130 exit_now = true;
2131 continue; // Go to next loop iteration so we exit without
2132 break; // doing any internal state managment below
2133
2134 case eBroadcastInternalStateControlPause:
2135 control_only = true;
2136 break;
2137
2138 case eBroadcastInternalStateControlResume:
2139 control_only = false;
2140 break;
2141 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002142
2143 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
2144 if (log)
2145 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002148 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 }
2150
2151
2152 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2153
2154 if (internal_state != eStateInvalid)
2155 {
2156 HandlePrivateEvent (event_sp);
2157 }
2158
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002159 if (internal_state == eStateInvalid ||
2160 internal_state == eStateExited ||
2161 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002162 {
2163 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
2164 if (log)
2165 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2166
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002168 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169 }
2170
Caroline Tice20ad3c42010-10-29 21:48:37 +00002171 // Verify log is still enabled before attempting to write to it...
2172 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173 if (log)
2174 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2175
2176 return NULL;
2177}
2178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179//------------------------------------------------------------------
2180// Process Event Data
2181//------------------------------------------------------------------
2182
2183Process::ProcessEventData::ProcessEventData () :
2184 EventData (),
2185 m_process_sp (),
2186 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002187 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002188 m_update_state (false),
2189 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190{
2191}
2192
2193Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2194 EventData (),
2195 m_process_sp (process_sp),
2196 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002197 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002198 m_update_state (false),
2199 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200{
2201}
2202
2203Process::ProcessEventData::~ProcessEventData()
2204{
2205}
2206
2207const ConstString &
2208Process::ProcessEventData::GetFlavorString ()
2209{
2210 static ConstString g_flavor ("Process::ProcessEventData");
2211 return g_flavor;
2212}
2213
2214const ConstString &
2215Process::ProcessEventData::GetFlavor () const
2216{
2217 return ProcessEventData::GetFlavorString ();
2218}
2219
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220void
2221Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2222{
2223 // This function gets called twice for each event, once when the event gets pulled
2224 // off of the private process event queue, and once when it gets pulled off of
2225 // the public event queue. m_update_state is used to distinguish these
2226 // two cases; it is false when we're just pulling it off for private handling,
2227 // and we don't want to do the breakpoint command handling then.
2228
2229 if (!m_update_state)
2230 return;
2231
2232 m_process_sp->SetPublicState (m_state);
2233
2234 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2235 if (m_state == eStateStopped && ! m_restarted)
2236 {
2237 int num_threads = m_process_sp->GetThreadList().GetSize();
2238 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002239
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240 for (idx = 0; idx < num_threads; ++idx)
2241 {
2242 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2243
Jim Inghamb15bfc72010-10-20 00:39:53 +00002244 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2245 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002247 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 }
2249 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002250
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002251 // The stop action might restart the target. If it does, then we want to mark that in the
2252 // event so that whoever is receiving it will know to wait for the running event and reflect
2253 // that state appropriately.
2254
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002255 if (m_process_sp->GetPrivateState() == eStateRunning)
2256 SetRestarted(true);
2257 }
2258}
2259
2260void
2261Process::ProcessEventData::Dump (Stream *s) const
2262{
2263 if (m_process_sp)
2264 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2265
2266 s->Printf("state = %s", StateAsCString(GetState()));;
2267}
2268
2269const Process::ProcessEventData *
2270Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2271{
2272 if (event_ptr)
2273 {
2274 const EventData *event_data = event_ptr->GetData();
2275 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2276 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2277 }
2278 return NULL;
2279}
2280
2281ProcessSP
2282Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2283{
2284 ProcessSP process_sp;
2285 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2286 if (data)
2287 process_sp = data->GetProcessSP();
2288 return process_sp;
2289}
2290
2291StateType
2292Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2293{
2294 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2295 if (data == NULL)
2296 return eStateInvalid;
2297 else
2298 return data->GetState();
2299}
2300
2301bool
2302Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2303{
2304 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2305 if (data == NULL)
2306 return false;
2307 else
2308 return data->GetRestarted();
2309}
2310
2311void
2312Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2313{
2314 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2315 if (data != NULL)
2316 data->SetRestarted(new_value);
2317}
2318
2319bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002320Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2321{
2322 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2323 if (data == NULL)
2324 return false;
2325 else
2326 return data->GetInterrupted ();
2327}
2328
2329void
2330Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2331{
2332 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2333 if (data != NULL)
2334 data->SetInterrupted(new_value);
2335}
2336
2337bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2339{
2340 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2341 if (data)
2342 {
2343 data->SetUpdateStateOnRemoval();
2344 return true;
2345 }
2346 return false;
2347}
2348
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349Target *
2350Process::CalculateTarget ()
2351{
2352 return &m_target;
2353}
2354
2355Process *
2356Process::CalculateProcess ()
2357{
2358 return this;
2359}
2360
2361Thread *
2362Process::CalculateThread ()
2363{
2364 return NULL;
2365}
2366
2367StackFrame *
2368Process::CalculateStackFrame ()
2369{
2370 return NULL;
2371}
2372
2373void
Greg Clayton0603aa92010-10-04 01:05:56 +00002374Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375{
2376 exe_ctx.target = &m_target;
2377 exe_ctx.process = this;
2378 exe_ctx.thread = NULL;
2379 exe_ctx.frame = NULL;
2380}
2381
2382lldb::ProcessSP
2383Process::GetSP ()
2384{
2385 return GetTarget().GetProcessSP();
2386}
2387
Jim Ingham5aee1622010-08-09 23:31:02 +00002388uint32_t
2389Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2390{
2391 return 0;
2392}
2393
2394ArchSpec
2395Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2396{
2397 return Host::GetArchSpecForExistingProcess (pid);
2398}
2399
2400ArchSpec
2401Process::GetArchSpecForExistingProcess (const char *process_name)
2402{
2403 return Host::GetArchSpecForExistingProcess (process_name);
2404}
2405
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002406void
2407Process::AppendSTDOUT (const char * s, size_t len)
2408{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002409 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002410 m_stdout_data.append (s, len);
2411
Greg Claytona9ff3062010-12-05 19:16:56 +00002412 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002413}
2414
2415void
2416Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2417{
2418 Process *process = (Process *) baton;
2419 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2420}
2421
2422size_t
2423Process::ProcessInputReaderCallback (void *baton,
2424 InputReader &reader,
2425 lldb::InputReaderAction notification,
2426 const char *bytes,
2427 size_t bytes_len)
2428{
2429 Process *process = (Process *) baton;
2430
2431 switch (notification)
2432 {
2433 case eInputReaderActivate:
2434 break;
2435
2436 case eInputReaderDeactivate:
2437 break;
2438
2439 case eInputReaderReactivate:
2440 break;
2441
2442 case eInputReaderGotToken:
2443 {
2444 Error error;
2445 process->PutSTDIN (bytes, bytes_len, error);
2446 }
2447 break;
2448
Caroline Ticeefed6132010-11-19 20:47:54 +00002449 case eInputReaderInterrupt:
2450 process->Halt ();
2451 break;
2452
2453 case eInputReaderEndOfFile:
2454 process->AppendSTDOUT ("^D", 2);
2455 break;
2456
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002457 case eInputReaderDone:
2458 break;
2459
2460 }
2461
2462 return bytes_len;
2463}
2464
2465void
2466Process::ResetProcessInputReader ()
2467{
2468 m_process_input_reader.reset();
2469}
2470
2471void
2472Process::SetUpProcessInputReader (int file_descriptor)
2473{
2474 // First set up the Read Thread for reading/handling process I/O
2475
2476 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2477
2478 if (conn_ap.get())
2479 {
2480 m_stdio_communication.SetConnection (conn_ap.release());
2481 if (m_stdio_communication.IsConnected())
2482 {
2483 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2484 m_stdio_communication.StartReadThread();
2485
2486 // Now read thread is set up, set up input reader.
2487
2488 if (!m_process_input_reader.get())
2489 {
2490 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2491 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2492 this,
2493 eInputReaderGranularityByte,
2494 NULL,
2495 NULL,
2496 false));
2497
2498 if (err.Fail())
2499 m_process_input_reader.reset();
2500 }
2501 }
2502 }
2503}
2504
2505void
2506Process::PushProcessInputReader ()
2507{
2508 if (m_process_input_reader && !m_process_input_reader->IsActive())
2509 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2510}
2511
2512void
2513Process::PopProcessInputReader ()
2514{
2515 if (m_process_input_reader && m_process_input_reader->IsActive())
2516 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2517}
2518
Greg Clayton99d0faf2010-11-18 23:32:35 +00002519
2520void
2521Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002522{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002523 UserSettingsControllerSP &usc = GetSettingsController();
2524 usc.reset (new SettingsController);
2525 UserSettingsController::InitializeSettingsController (usc,
2526 SettingsController::global_settings_table,
2527 SettingsController::instance_settings_table);
2528}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002529
Greg Clayton99d0faf2010-11-18 23:32:35 +00002530void
2531Process::Terminate ()
2532{
2533 UserSettingsControllerSP &usc = GetSettingsController();
2534 UserSettingsController::FinalizeSettingsController (usc);
2535 usc.reset();
2536}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002537
Greg Clayton99d0faf2010-11-18 23:32:35 +00002538UserSettingsControllerSP &
2539Process::GetSettingsController ()
2540{
2541 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002542 return g_settings_controller;
2543}
2544
Caroline Tice1559a462010-09-27 00:30:10 +00002545void
2546Process::UpdateInstanceName ()
2547{
2548 ModuleSP module_sp = GetTarget().GetExecutableModule();
2549 if (module_sp)
2550 {
2551 StreamString sstr;
2552 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2553
Greg Claytondbe54502010-11-19 03:46:01 +00002554 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002555 sstr.GetData());
2556 }
2557}
2558
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002559ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002560Process::RunThreadPlan (ExecutionContext &exe_ctx,
2561 lldb::ThreadPlanSP &thread_plan_sp,
2562 bool stop_others,
2563 bool try_all_threads,
2564 bool discard_on_error,
2565 uint32_t single_thread_timeout_usec,
2566 Stream &errors)
2567{
2568 ExecutionResults return_value = eExecutionSetupError;
2569
Jim Ingham77787032011-01-20 02:03:18 +00002570 if (thread_plan_sp.get() == NULL)
2571 {
2572 errors.Printf("RunThreadPlan called with empty thread plan.");
2573 return lldb::eExecutionSetupError;
2574 }
2575
Jim Inghamf48169b2010-11-30 02:22:11 +00002576 // Save this value for restoration of the execution context after we run
2577 uint32_t tid = exe_ctx.thread->GetIndexID();
2578
2579 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2580 // so we should arrange to reset them as well.
2581
2582 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2583 lldb::StackFrameSP selected_frame_sp;
2584
2585 uint32_t selected_tid;
2586 if (selected_thread_sp != NULL)
2587 {
2588 selected_tid = selected_thread_sp->GetIndexID();
2589 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2590 }
2591 else
2592 {
2593 selected_tid = LLDB_INVALID_THREAD_ID;
2594 }
2595
2596 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2597
2598 Listener listener("ClangFunction temporary listener");
2599 exe_ctx.process->HijackProcessEvents(&listener);
2600
Jim Ingham77787032011-01-20 02:03:18 +00002601 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2602 if (log)
2603 {
2604 StreamString s;
2605 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
2606 log->Printf ("Resuming thread 0x%x to run thread plan \"%s\".", tid, s.GetData());
2607 }
2608
Jim Inghamf48169b2010-11-30 02:22:11 +00002609 Error resume_error = exe_ctx.process->Resume ();
2610 if (!resume_error.Success())
2611 {
2612 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2613 exe_ctx.process->RestoreProcessEvents();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002614 return lldb::eExecutionSetupError;
Jim Inghamf48169b2010-11-30 02:22:11 +00002615 }
2616
2617 // We need to call the function synchronously, so spin waiting for it to return.
2618 // If we get interrupted while executing, we're going to lose our context, and
2619 // won't be able to gather the result at this point.
2620 // We set the timeout AFTER the resume, since the resume takes some time and we
2621 // don't want to charge that to the timeout.
2622
2623 TimeValue* timeout_ptr = NULL;
2624 TimeValue real_timeout;
2625
2626 if (single_thread_timeout_usec != 0)
2627 {
2628 real_timeout = TimeValue::Now();
2629 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2630 timeout_ptr = &real_timeout;
2631 }
2632
Jim Inghamf48169b2010-11-30 02:22:11 +00002633 while (1)
2634 {
2635 lldb::EventSP event_sp;
2636 lldb::StateType stop_state = lldb::eStateInvalid;
2637 // Now wait for the process to stop again:
2638 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2639
2640 if (!got_event)
2641 {
2642 // Right now this is the only way to tell we've timed out...
2643 // We should interrupt the process here...
2644 // Not really sure what to do if Halt fails here...
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002645 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002646 if (try_all_threads)
2647 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2648 single_thread_timeout_usec);
2649 else
2650 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2651 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002652 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002653
2654 if (exe_ctx.process->Halt().Success())
2655 {
2656 timeout_ptr = NULL;
2657 if (log)
2658 log->Printf ("Halt succeeded.");
2659
2660 // Between the time that we got the timeout and the time we halted, but target
2661 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2662 // timeout to
2663 got_event = listener.WaitForEvent(NULL, event_sp);
2664
2665 if (got_event)
2666 {
2667 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2668 if (log)
2669 {
2670 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2671 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2672 log->Printf (" Event was the Halt interruption event.");
2673 }
2674
2675 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2676 {
2677 if (log)
2678 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002679 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002680 break;
2681 }
2682
2683 if (try_all_threads
2684 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2685 {
2686
2687 thread_plan_sp->SetStopOthers (false);
2688 if (log)
2689 log->Printf ("About to resume.");
2690
2691 exe_ctx.process->Resume();
2692 continue;
2693 }
2694 else
2695 {
2696 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002697 return lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002698 }
2699 }
2700 }
2701 }
2702
2703 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2704 if (log)
2705 log->Printf("Got event: %s.", StateAsCString(stop_state));
2706
2707 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2708 continue;
2709
2710 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2711 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002712 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002713 break;
2714 }
2715 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2716 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002717 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00002718 break;
2719 }
2720 else
2721 {
2722 if (log)
2723 {
2724 StreamString s;
2725 event_sp->Dump (&s);
2726 StreamString ts;
2727
2728 const char *event_explanation;
2729
2730 do
2731 {
2732 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2733
2734 if (!event_data)
2735 {
2736 event_explanation = "<no event data>";
2737 break;
2738 }
2739
2740 Process *process = event_data->GetProcessSP().get();
2741
2742 if (!process)
2743 {
2744 event_explanation = "<no process>";
2745 break;
2746 }
2747
2748 ThreadList &thread_list = process->GetThreadList();
2749
2750 uint32_t num_threads = thread_list.GetSize();
2751 uint32_t thread_index;
2752
2753 ts.Printf("<%u threads> ", num_threads);
2754
2755 for (thread_index = 0;
2756 thread_index < num_threads;
2757 ++thread_index)
2758 {
2759 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2760
2761 if (!thread)
2762 {
2763 ts.Printf("<?> ");
2764 continue;
2765 }
2766
2767 ts.Printf("<");
Greg Clayton5ccbd292011-01-06 22:15:06 +00002768 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Inghamf48169b2010-11-30 02:22:11 +00002769
2770 if (register_context)
2771 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2772 else
2773 ts.Printf("[ip unknown] ");
2774
2775 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2776 if (stop_info_sp)
2777 {
2778 const char *stop_desc = stop_info_sp->GetDescription();
2779 if (stop_desc)
2780 ts.PutCString (stop_desc);
2781 }
2782 ts.Printf(">");
2783 }
2784
2785 event_explanation = ts.GetData();
2786 } while (0);
2787
2788 if (log)
2789 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2790 }
2791
2792 if (discard_on_error && thread_plan_sp)
2793 {
2794 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2795 }
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002796 return_value = lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002797 break;
2798 }
2799 }
2800
2801 if (exe_ctx.process)
2802 exe_ctx.process->RestoreProcessEvents ();
2803
2804 // Thread we ran the function in may have gone away because we ran the target
2805 // Check that it's still there.
2806 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2807 if (exe_ctx.thread)
2808 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2809
2810 // Also restore the current process'es selected frame & thread, since this function calling may
2811 // be done behind the user's back.
2812
2813 if (selected_tid != LLDB_INVALID_THREAD_ID)
2814 {
2815 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2816 {
2817 // We were able to restore the selected thread, now restore the frame:
2818 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2819 }
2820 }
2821
2822 return return_value;
2823}
2824
2825const char *
2826Process::ExecutionResultAsCString (ExecutionResults result)
2827{
2828 const char *result_name;
2829
2830 switch (result)
2831 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002832 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002833 result_name = "eExecutionCompleted";
2834 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002835 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00002836 result_name = "eExecutionDiscarded";
2837 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002838 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002839 result_name = "eExecutionInterrupted";
2840 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002841 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00002842 result_name = "eExecutionSetupError";
2843 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002844 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00002845 result_name = "eExecutionTimedOut";
2846 break;
2847 }
2848 return result_name;
2849}
2850
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002851//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002852// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002853//--------------------------------------------------------------
2854
Greg Clayton1b654882010-09-19 02:33:57 +00002855Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002856 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002857{
Greg Clayton85851dd2010-12-04 00:10:17 +00002858 m_default_settings.reset (new ProcessInstanceSettings (*this,
2859 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002860 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002861}
2862
Greg Clayton1b654882010-09-19 02:33:57 +00002863Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002864{
2865}
2866
2867lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002868Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002869{
Greg Claytondbe54502010-11-19 03:46:01 +00002870 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2871 false,
2872 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002873 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2874 return new_settings_sp;
2875}
2876
2877//--------------------------------------------------------------
2878// class ProcessInstanceSettings
2879//--------------------------------------------------------------
2880
Greg Clayton85851dd2010-12-04 00:10:17 +00002881ProcessInstanceSettings::ProcessInstanceSettings
2882(
2883 UserSettingsController &owner,
2884 bool live_instance,
2885 const char *name
2886) :
2887 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002888 m_run_args (),
2889 m_env_vars (),
2890 m_input_path (),
2891 m_output_path (),
2892 m_error_path (),
2893 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00002894 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00002895 m_disable_stdio (false),
2896 m_inherit_host_env (true),
2897 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002898{
Caroline Ticef20e8232010-09-09 18:26:37 +00002899 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2900 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2901 // 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 +00002902 // This is true for CreateInstanceName() too.
2903
2904 if (GetInstanceName () == InstanceSettings::InvalidName())
2905 {
2906 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2907 m_owner.RegisterInstanceSettings (this);
2908 }
Caroline Ticef20e8232010-09-09 18:26:37 +00002909
2910 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002911 {
2912 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2913 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00002914 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002915 }
2916}
2917
2918ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00002919 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002920 m_run_args (rhs.m_run_args),
2921 m_env_vars (rhs.m_env_vars),
2922 m_input_path (rhs.m_input_path),
2923 m_output_path (rhs.m_output_path),
2924 m_error_path (rhs.m_error_path),
2925 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00002926 m_disable_aslr (rhs.m_disable_aslr),
2927 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002928{
2929 if (m_instance_name != InstanceSettings::GetDefaultName())
2930 {
2931 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2932 CopyInstanceSettings (pending_settings,false);
2933 m_owner.RemovePendingSettings (m_instance_name);
2934 }
2935}
2936
2937ProcessInstanceSettings::~ProcessInstanceSettings ()
2938{
2939}
2940
2941ProcessInstanceSettings&
2942ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2943{
2944 if (this != &rhs)
2945 {
2946 m_run_args = rhs.m_run_args;
2947 m_env_vars = rhs.m_env_vars;
2948 m_input_path = rhs.m_input_path;
2949 m_output_path = rhs.m_output_path;
2950 m_error_path = rhs.m_error_path;
2951 m_plugin = rhs.m_plugin;
2952 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00002953 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00002954 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002955 }
2956
2957 return *this;
2958}
2959
2960
2961void
2962ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2963 const char *index_value,
2964 const char *value,
2965 const ConstString &instance_name,
2966 const SettingEntry &entry,
2967 lldb::VarSetOperationType op,
2968 Error &err,
2969 bool pending)
2970{
2971 if (var_name == RunArgsVarName())
2972 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2973 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00002974 {
2975 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002976 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00002977 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002978 else if (var_name == InputPathVarName())
2979 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2980 else if (var_name == OutputPathVarName())
2981 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2982 else if (var_name == ErrorPathVarName())
2983 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2984 else if (var_name == PluginVarName())
2985 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00002986 else if (var_name == InheritHostEnvVarName())
2987 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002988 else if (var_name == DisableASLRVarName())
2989 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00002990 else if (var_name == DisableSTDIOVarName ())
2991 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002992}
2993
2994void
2995ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2996 bool pending)
2997{
2998 if (new_settings.get() == NULL)
2999 return;
3000
3001 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3002
3003 m_run_args = new_process_settings->m_run_args;
3004 m_env_vars = new_process_settings->m_env_vars;
3005 m_input_path = new_process_settings->m_input_path;
3006 m_output_path = new_process_settings->m_output_path;
3007 m_error_path = new_process_settings->m_error_path;
3008 m_plugin = new_process_settings->m_plugin;
3009 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003010 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003011}
3012
Caroline Tice12cecd72010-09-20 21:37:42 +00003013bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003014ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3015 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003016 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003017 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003018{
3019 if (var_name == RunArgsVarName())
3020 {
3021 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003022 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003023 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3024 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003025 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003026 }
3027 else if (var_name == EnvVarsVarName())
3028 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003029 GetHostEnvironmentIfNeeded ();
3030
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003031 if (m_env_vars.size() > 0)
3032 {
3033 std::map<std::string, std::string>::iterator pos;
3034 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3035 {
3036 StreamString value_str;
3037 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3038 value.AppendString (value_str.GetData());
3039 }
3040 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003041 }
3042 else if (var_name == InputPathVarName())
3043 {
3044 value.AppendString (m_input_path.c_str());
3045 }
3046 else if (var_name == OutputPathVarName())
3047 {
3048 value.AppendString (m_output_path.c_str());
3049 }
3050 else if (var_name == ErrorPathVarName())
3051 {
3052 value.AppendString (m_error_path.c_str());
3053 }
3054 else if (var_name == PluginVarName())
3055 {
3056 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3057 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003058 else if (var_name == InheritHostEnvVarName())
3059 {
3060 if (m_inherit_host_env)
3061 value.AppendString ("true");
3062 else
3063 value.AppendString ("false");
3064 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003065 else if (var_name == DisableASLRVarName())
3066 {
3067 if (m_disable_aslr)
3068 value.AppendString ("true");
3069 else
3070 value.AppendString ("false");
3071 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003072 else if (var_name == DisableSTDIOVarName())
3073 {
3074 if (m_disable_stdio)
3075 value.AppendString ("true");
3076 else
3077 value.AppendString ("false");
3078 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003079 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003080 {
3081 if (err)
3082 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3083 return false;
3084 }
3085 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003086}
3087
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003088const ConstString
3089ProcessInstanceSettings::CreateInstanceName ()
3090{
3091 static int instance_count = 1;
3092 StreamString sstr;
3093
3094 sstr.Printf ("process_%d", instance_count);
3095 ++instance_count;
3096
3097 const ConstString ret_val (sstr.GetData());
3098 return ret_val;
3099}
3100
3101const ConstString &
3102ProcessInstanceSettings::RunArgsVarName ()
3103{
3104 static ConstString run_args_var_name ("run-args");
3105
3106 return run_args_var_name;
3107}
3108
3109const ConstString &
3110ProcessInstanceSettings::EnvVarsVarName ()
3111{
3112 static ConstString env_vars_var_name ("env-vars");
3113
3114 return env_vars_var_name;
3115}
3116
3117const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003118ProcessInstanceSettings::InheritHostEnvVarName ()
3119{
3120 static ConstString g_name ("inherit-env");
3121
3122 return g_name;
3123}
3124
3125const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003126ProcessInstanceSettings::InputPathVarName ()
3127{
3128 static ConstString input_path_var_name ("input-path");
3129
3130 return input_path_var_name;
3131}
3132
3133const ConstString &
3134ProcessInstanceSettings::OutputPathVarName ()
3135{
Caroline Tice49e27372010-09-07 18:35:40 +00003136 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003137
3138 return output_path_var_name;
3139}
3140
3141const ConstString &
3142ProcessInstanceSettings::ErrorPathVarName ()
3143{
Caroline Tice49e27372010-09-07 18:35:40 +00003144 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003145
3146 return error_path_var_name;
3147}
3148
3149const ConstString &
3150ProcessInstanceSettings::PluginVarName ()
3151{
3152 static ConstString plugin_var_name ("plugin");
3153
3154 return plugin_var_name;
3155}
3156
3157
3158const ConstString &
3159ProcessInstanceSettings::DisableASLRVarName ()
3160{
3161 static ConstString disable_aslr_var_name ("disable-aslr");
3162
3163 return disable_aslr_var_name;
3164}
3165
Caroline Ticef8da8632010-12-03 18:46:09 +00003166const ConstString &
3167ProcessInstanceSettings::DisableSTDIOVarName ()
3168{
3169 static ConstString disable_stdio_var_name ("disable-stdio");
3170
3171 return disable_stdio_var_name;
3172}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003173
3174//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003175// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003176//--------------------------------------------------
3177
3178SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003179Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003180{
3181 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3182 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3183};
3184
3185
3186lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003187Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003188{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003189 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3190 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3191 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003192};
3193
3194SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003195Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003196{
Greg Clayton85851dd2010-12-04 00:10:17 +00003197 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3198 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3199 { "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." },
3200 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3201 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3202 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3203 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3204 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3205 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3206 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3207 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003208};
3209
3210
Jim Ingham5aee1622010-08-09 23:31:02 +00003211