blob: 2a8382953fe923aaf6daa57ef09cb94ba27568e2 [file] [log] [blame]
Chris Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-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 Claytonfd119992011-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 Lattner24943d22010-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 Clayton54e7afa2010-07-09 20:39:50 +0000195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000196 {
Greg Clayton54e7afa2010-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 Lattner24943d22010-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 Clayton49ce6822010-10-31 03:01:06 +0000211 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000212 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000213 m_target (target),
Chris Lattner24943d22010-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 Clayton20d338f2010-11-18 05:57:03 +0000227 m_image_tokens (),
228 m_listener (listener),
229 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000230 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000231 m_unix_signals (),
Greg Clayton20d338f2010-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 Tice861efb32010-11-16 05:07:41 +0000236 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000237 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000239 m_stdout_data (),
240 m_memory_cache ()
Chris Lattner24943d22010-06-08 16:52:24 +0000241{
Caroline Tice1ebef442010-09-27 00:30:10 +0000242 UpdateInstanceName();
243
Greg Claytone005f2c2010-11-06 01:53:30 +0000244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000245 if (log)
246 log->Printf ("%p Process::Process()", this);
247
Greg Clayton49ce6822010-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 Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-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 Claytond8c62532010-10-07 04:19:01 +0000359 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000360 while (state != eStateInvalid)
361 {
Greg Claytond8c62532010-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 Lattner24943d22010-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 Ingham63e24d72010-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 Lattner24943d22010-06-08 16:52:24 +0000395StateType
396Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
397{
Greg Claytone005f2c2010-11-06 01:53:30 +0000398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Clayton36f63a92010-10-19 03:25:40 +0000404 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
405 this,
406 eBroadcastBitStateChanged,
407 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
409
Caroline Tice926060e2010-10-29 21:48:37 +0000410 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000422 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000423
424 if (log)
425 log->Printf ("Process::%s...", __FUNCTION__);
426
427 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000428 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
429 eBroadcastBitStateChanged);
Caroline Tice926060e2010-10-29 21:48:37 +0000430 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000451 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000475 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Clayton638351a2010-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 Clayton1f3dd642010-12-15 20:52:40 +0000514 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-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 Lattner24943d22010-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 Clayton58e844b2010-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 Lattner24943d22010-06-08 16:52:24 +0000563
Greg Clayton58e844b2010-12-08 05:08:21 +0000564 DidExit ();
565
566 SetPrivateState (eStateExited);
567 }
Chris Lattner24943d22010-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 Clayton63094e02010-06-23 01:19:29 +0000585 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000620 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +0000635 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-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 Claytonfd119992011-01-07 06:08:19 +0000651 m_memory_cache.Clear();
Chris Lattner24943d22010-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 Clayton0baa3942010-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 Inghamea9d4262010-11-05 19:25:48 +0000711 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000712 bool keep_in_memory = false;
Greg Clayton0baa3942010-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 Ingham360f53f2010-11-30 02:22:11 +0000718 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000719 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-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 Inghamea9d4262010-11-05 19:25:48 +0000779 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000780 bool keep_in_memory = false;
Greg Clayton0baa3942010-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 Ingham360f53f2010-11-30 02:22:11 +0000784 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000785 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-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 Lattner24943d22010-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 Ingham642036f2010-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 Lattner24943d22010-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 Wilson3fd1f362010-07-17 00:56:13 +0000939lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000940Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
941{
Greg Claytoneea26402010-09-14 23:36:40 +0000942 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00001021 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-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 Wilsonc2b98252011-01-12 04:20:03 +00001085 if (log && error.Fail())
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00001098 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-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)
1102 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
1103
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 Clayton54e7afa2010-07-09 20:39:50 +00001115 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001116 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-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 Clayton54e7afa2010-07-09 20:39:50 +00001145 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001146 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-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 Claytonfd119992011-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 Lattner24943d22010-06-08 16:52:24 +00001197
1198size_t
1199Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1200{
Greg Claytonfd119992011-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 Lattner24943d22010-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 Claytonf72fdee2010-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 Lattner24943d22010-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 Claytonfd119992011-01-07 06:08:19 +00001322#if defined (ENABLE_MEMORY_CACHING)
1323 m_memory_cache.Flush (addr, size);
1324#endif
1325
Chris Lattner24943d22010-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 Clayton54e7afa2010-07-09 20:39:50 +00001340 addr_t intersect_addr = 0;
1341 size_t intersect_size = 0;
1342 size_t opcode_offset = 0;
Chris Lattner24943d22010-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 Clayton452bf612010-08-31 18:35:14 +00001446 uint32_t launch_flags,
Chris Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +00001455 m_process_input_reader.reset();
Chris Lattner24943d22010-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 Claytond8c62532010-10-07 04:19:01 +00001467 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-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 Clayton53d68e72010-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 Clayton452bf612010-08-31 18:35:14 +00001497 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001498 stdin_path,
1499 stdout_path,
1500 stderr_path);
Chris Lattner24943d22010-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 Claytonc1d37752010-10-18 01:45:30 +00001548
1549 if (GetID() == LLDB_INVALID_PROCESS_ID)
1550 {
1551 error.SetErrorString("no process");
1552 }
1553
Chris Lattner24943d22010-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 Ingham7508e732010-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 Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +00001601 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001602
Jim Ingham7508e732010-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 Clayton54e7afa2010-07-09 20:39:50 +00001613 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001614 if (error.Success())
1615 {
Greg Claytond8c62532010-10-07 04:19:01 +00001616 SetPublicState (eStateAttaching);
1617
Greg Clayton54e7afa2010-07-09 20:39:50 +00001618 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +00001644 m_process_input_reader.reset();
Jim Ingham7508e732010-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 Inghamea294182010-08-17 21:54:19 +00001649 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001650 {
Jim Inghamea294182010-08-17 21:54:19 +00001651 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001652 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001653 {
1654 // Set the architecture on the target.
1655 GetTarget().SetArchitecture(attach_spec);
1656 }
Jim Ingham7508e732010-08-09 23:31:02 +00001657 }
Jim Inghamea294182010-08-17 21:54:19 +00001658
Greg Clayton54e7afa2010-07-09 20:39:50 +00001659 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001660 if (error.Success())
1661 {
Greg Claytond8c62532010-10-07 04:19:01 +00001662 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001663 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00001687 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Chen9c11d472010-12-02 20:53:05 +00001695 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-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 Clayton20d338f2010-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 Ingham3ae449a2010-11-17 02:32:00 +00001736 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001737 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001738 {
Greg Clayton20d338f2010-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 Ingham3ae449a2010-11-17 02:32:00 +00001745 if (caused_stop)
1746 {
Greg Clayton20d338f2010-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 Clayton20d338f2010-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 Ingham3ae449a2010-11-17 02:32:00 +00001775 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001776 DidHalt();
1777
Jim Ingham3ae449a2010-11-17 02:32:00 +00001778 }
Greg Clayton20d338f2010-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 Ingham360f53f2010-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 Clayton20d338f2010-11-18 05:57:03 +00001786 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001787 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001788
Chris Lattner24943d22010-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 Tice861efb32010-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 Lattner24943d22010-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 Clayton20d338f2010-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 Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00001878 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-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 Ingham5a47e8b2010-06-19 04:45:32 +00001940 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001941 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001942 {
Greg Clayton20d338f2010-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 Ingham3ae449a2010-11-17 02:32:00 +00001945 return true;
1946 }
1947 else
1948 {
Chris Lattner24943d22010-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 Chen028784b2010-10-14 00:54:32 +00001957 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001958 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001959 case eVoteNo:
1960 return_value = false;
1961 break;
1962 }
1963
1964 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001965 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00002002 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-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 Claytona875b642011-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 Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00002036 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-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 Claytonc607d862010-07-22 18:34:21 +00002065 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002066 }
2067 }
2068}
2069
2070void
2071Process::HandlePrivateEvent (EventSP &event_sp)
2072{
Greg Claytone005f2c2010-11-06 01:53:30 +00002073 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +00002086 if (StateIsRunningState (internal_state))
2087 PushProcessInputReader ();
2088 else
2089 PopProcessInputReader ();
Chris Lattner24943d22010-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 Lattner24943d22010-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 Claytone005f2c2010-11-06 01:53:30 +00002116 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-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 Ingham3ae449a2010-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 Lattner24943d22010-06-08 16:52:24 +00002147 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002148 continue;
Chris Lattner24943d22010-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 Clayton3b2c41c2010-10-18 04:14:23 +00002159 if (internal_state == eStateInvalid ||
2160 internal_state == eStateExited ||
2161 internal_state == eStateDetached )
Jim Ingham3ae449a2010-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 Lattner24943d22010-06-08 16:52:24 +00002167 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002168 }
Chris Lattner24943d22010-06-08 16:52:24 +00002169 }
2170
Caroline Tice926060e2010-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 Lattner24943d22010-06-08 16:52:24 +00002173 if (log)
2174 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2175
Greg Clayton8b4c16e2010-08-19 21:50:06 +00002176 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002177 return NULL;
2178}
2179
Chris Lattner24943d22010-06-08 16:52:24 +00002180//------------------------------------------------------------------
2181// Process Event Data
2182//------------------------------------------------------------------
2183
2184Process::ProcessEventData::ProcessEventData () :
2185 EventData (),
2186 m_process_sp (),
2187 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002188 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002189 m_update_state (false),
2190 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002191{
2192}
2193
2194Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2195 EventData (),
2196 m_process_sp (process_sp),
2197 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002198 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002199 m_update_state (false),
2200 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002201{
2202}
2203
2204Process::ProcessEventData::~ProcessEventData()
2205{
2206}
2207
2208const ConstString &
2209Process::ProcessEventData::GetFlavorString ()
2210{
2211 static ConstString g_flavor ("Process::ProcessEventData");
2212 return g_flavor;
2213}
2214
2215const ConstString &
2216Process::ProcessEventData::GetFlavor () const
2217{
2218 return ProcessEventData::GetFlavorString ();
2219}
2220
Chris Lattner24943d22010-06-08 16:52:24 +00002221void
2222Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2223{
2224 // This function gets called twice for each event, once when the event gets pulled
2225 // off of the private process event queue, and once when it gets pulled off of
2226 // the public event queue. m_update_state is used to distinguish these
2227 // two cases; it is false when we're just pulling it off for private handling,
2228 // and we don't want to do the breakpoint command handling then.
2229
2230 if (!m_update_state)
2231 return;
2232
2233 m_process_sp->SetPublicState (m_state);
2234
2235 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2236 if (m_state == eStateStopped && ! m_restarted)
2237 {
2238 int num_threads = m_process_sp->GetThreadList().GetSize();
2239 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002240
Chris Lattner24943d22010-06-08 16:52:24 +00002241 for (idx = 0; idx < num_threads; ++idx)
2242 {
2243 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2244
Jim Ingham6297a3a2010-10-20 00:39:53 +00002245 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2246 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002247 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002248 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002249 }
2250 }
Greg Clayton643ee732010-08-04 01:40:35 +00002251
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002252 // The stop action might restart the target. If it does, then we want to mark that in the
2253 // event so that whoever is receiving it will know to wait for the running event and reflect
2254 // that state appropriately.
2255
Chris Lattner24943d22010-06-08 16:52:24 +00002256 if (m_process_sp->GetPrivateState() == eStateRunning)
2257 SetRestarted(true);
2258 }
2259}
2260
2261void
2262Process::ProcessEventData::Dump (Stream *s) const
2263{
2264 if (m_process_sp)
2265 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2266
2267 s->Printf("state = %s", StateAsCString(GetState()));;
2268}
2269
2270const Process::ProcessEventData *
2271Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2272{
2273 if (event_ptr)
2274 {
2275 const EventData *event_data = event_ptr->GetData();
2276 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2277 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2278 }
2279 return NULL;
2280}
2281
2282ProcessSP
2283Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2284{
2285 ProcessSP process_sp;
2286 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2287 if (data)
2288 process_sp = data->GetProcessSP();
2289 return process_sp;
2290}
2291
2292StateType
2293Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2294{
2295 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2296 if (data == NULL)
2297 return eStateInvalid;
2298 else
2299 return data->GetState();
2300}
2301
2302bool
2303Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2304{
2305 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2306 if (data == NULL)
2307 return false;
2308 else
2309 return data->GetRestarted();
2310}
2311
2312void
2313Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2314{
2315 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2316 if (data != NULL)
2317 data->SetRestarted(new_value);
2318}
2319
2320bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002321Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2322{
2323 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2324 if (data == NULL)
2325 return false;
2326 else
2327 return data->GetInterrupted ();
2328}
2329
2330void
2331Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2332{
2333 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2334 if (data != NULL)
2335 data->SetInterrupted(new_value);
2336}
2337
2338bool
Chris Lattner24943d22010-06-08 16:52:24 +00002339Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2340{
2341 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2342 if (data)
2343 {
2344 data->SetUpdateStateOnRemoval();
2345 return true;
2346 }
2347 return false;
2348}
2349
Chris Lattner24943d22010-06-08 16:52:24 +00002350Target *
2351Process::CalculateTarget ()
2352{
2353 return &m_target;
2354}
2355
2356Process *
2357Process::CalculateProcess ()
2358{
2359 return this;
2360}
2361
2362Thread *
2363Process::CalculateThread ()
2364{
2365 return NULL;
2366}
2367
2368StackFrame *
2369Process::CalculateStackFrame ()
2370{
2371 return NULL;
2372}
2373
2374void
Greg Claytona830adb2010-10-04 01:05:56 +00002375Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002376{
2377 exe_ctx.target = &m_target;
2378 exe_ctx.process = this;
2379 exe_ctx.thread = NULL;
2380 exe_ctx.frame = NULL;
2381}
2382
2383lldb::ProcessSP
2384Process::GetSP ()
2385{
2386 return GetTarget().GetProcessSP();
2387}
2388
Jim Ingham7508e732010-08-09 23:31:02 +00002389uint32_t
2390Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2391{
2392 return 0;
2393}
2394
2395ArchSpec
2396Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2397{
2398 return Host::GetArchSpecForExistingProcess (pid);
2399}
2400
2401ArchSpec
2402Process::GetArchSpecForExistingProcess (const char *process_name)
2403{
2404 return Host::GetArchSpecForExistingProcess (process_name);
2405}
2406
Caroline Tice861efb32010-11-16 05:07:41 +00002407void
2408Process::AppendSTDOUT (const char * s, size_t len)
2409{
Greg Clayton20d338f2010-11-18 05:57:03 +00002410 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002411 m_stdout_data.append (s, len);
2412
Greg Claytonb3781332010-12-05 19:16:56 +00002413 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002414}
2415
2416void
2417Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2418{
2419 Process *process = (Process *) baton;
2420 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2421}
2422
2423size_t
2424Process::ProcessInputReaderCallback (void *baton,
2425 InputReader &reader,
2426 lldb::InputReaderAction notification,
2427 const char *bytes,
2428 size_t bytes_len)
2429{
2430 Process *process = (Process *) baton;
2431
2432 switch (notification)
2433 {
2434 case eInputReaderActivate:
2435 break;
2436
2437 case eInputReaderDeactivate:
2438 break;
2439
2440 case eInputReaderReactivate:
2441 break;
2442
2443 case eInputReaderGotToken:
2444 {
2445 Error error;
2446 process->PutSTDIN (bytes, bytes_len, error);
2447 }
2448 break;
2449
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002450 case eInputReaderInterrupt:
2451 process->Halt ();
2452 break;
2453
2454 case eInputReaderEndOfFile:
2455 process->AppendSTDOUT ("^D", 2);
2456 break;
2457
Caroline Tice861efb32010-11-16 05:07:41 +00002458 case eInputReaderDone:
2459 break;
2460
2461 }
2462
2463 return bytes_len;
2464}
2465
2466void
2467Process::ResetProcessInputReader ()
2468{
2469 m_process_input_reader.reset();
2470}
2471
2472void
2473Process::SetUpProcessInputReader (int file_descriptor)
2474{
2475 // First set up the Read Thread for reading/handling process I/O
2476
2477 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2478
2479 if (conn_ap.get())
2480 {
2481 m_stdio_communication.SetConnection (conn_ap.release());
2482 if (m_stdio_communication.IsConnected())
2483 {
2484 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2485 m_stdio_communication.StartReadThread();
2486
2487 // Now read thread is set up, set up input reader.
2488
2489 if (!m_process_input_reader.get())
2490 {
2491 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2492 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2493 this,
2494 eInputReaderGranularityByte,
2495 NULL,
2496 NULL,
2497 false));
2498
2499 if (err.Fail())
2500 m_process_input_reader.reset();
2501 }
2502 }
2503 }
2504}
2505
2506void
2507Process::PushProcessInputReader ()
2508{
2509 if (m_process_input_reader && !m_process_input_reader->IsActive())
2510 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2511}
2512
2513void
2514Process::PopProcessInputReader ()
2515{
2516 if (m_process_input_reader && m_process_input_reader->IsActive())
2517 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2518}
2519
Greg Clayton990de7b2010-11-18 23:32:35 +00002520
2521void
2522Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002523{
Greg Clayton990de7b2010-11-18 23:32:35 +00002524 UserSettingsControllerSP &usc = GetSettingsController();
2525 usc.reset (new SettingsController);
2526 UserSettingsController::InitializeSettingsController (usc,
2527 SettingsController::global_settings_table,
2528 SettingsController::instance_settings_table);
2529}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002530
Greg Clayton990de7b2010-11-18 23:32:35 +00002531void
2532Process::Terminate ()
2533{
2534 UserSettingsControllerSP &usc = GetSettingsController();
2535 UserSettingsController::FinalizeSettingsController (usc);
2536 usc.reset();
2537}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002538
Greg Clayton990de7b2010-11-18 23:32:35 +00002539UserSettingsControllerSP &
2540Process::GetSettingsController ()
2541{
2542 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002543 return g_settings_controller;
2544}
2545
Caroline Tice1ebef442010-09-27 00:30:10 +00002546void
2547Process::UpdateInstanceName ()
2548{
2549 ModuleSP module_sp = GetTarget().GetExecutableModule();
2550 if (module_sp)
2551 {
2552 StreamString sstr;
2553 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2554
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002555 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002556 sstr.GetData());
2557 }
2558}
2559
Greg Clayton427f2902010-12-14 02:59:59 +00002560ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002561Process::RunThreadPlan (ExecutionContext &exe_ctx,
2562 lldb::ThreadPlanSP &thread_plan_sp,
2563 bool stop_others,
2564 bool try_all_threads,
2565 bool discard_on_error,
2566 uint32_t single_thread_timeout_usec,
2567 Stream &errors)
2568{
2569 ExecutionResults return_value = eExecutionSetupError;
2570
2571 // Save this value for restoration of the execution context after we run
2572 uint32_t tid = exe_ctx.thread->GetIndexID();
2573
2574 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2575 // so we should arrange to reset them as well.
2576
2577 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2578 lldb::StackFrameSP selected_frame_sp;
2579
2580 uint32_t selected_tid;
2581 if (selected_thread_sp != NULL)
2582 {
2583 selected_tid = selected_thread_sp->GetIndexID();
2584 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2585 }
2586 else
2587 {
2588 selected_tid = LLDB_INVALID_THREAD_ID;
2589 }
2590
2591 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2592
2593 Listener listener("ClangFunction temporary listener");
2594 exe_ctx.process->HijackProcessEvents(&listener);
2595
2596 Error resume_error = exe_ctx.process->Resume ();
2597 if (!resume_error.Success())
2598 {
2599 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2600 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002601 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002602 }
2603
2604 // We need to call the function synchronously, so spin waiting for it to return.
2605 // If we get interrupted while executing, we're going to lose our context, and
2606 // won't be able to gather the result at this point.
2607 // We set the timeout AFTER the resume, since the resume takes some time and we
2608 // don't want to charge that to the timeout.
2609
2610 TimeValue* timeout_ptr = NULL;
2611 TimeValue real_timeout;
2612
2613 if (single_thread_timeout_usec != 0)
2614 {
2615 real_timeout = TimeValue::Now();
2616 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2617 timeout_ptr = &real_timeout;
2618 }
2619
2620 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2621 while (1)
2622 {
2623 lldb::EventSP event_sp;
2624 lldb::StateType stop_state = lldb::eStateInvalid;
2625 // Now wait for the process to stop again:
2626 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2627
2628 if (!got_event)
2629 {
2630 // Right now this is the only way to tell we've timed out...
2631 // We should interrupt the process here...
2632 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002633 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002634 if (try_all_threads)
2635 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2636 single_thread_timeout_usec);
2637 else
2638 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2639 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002640 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002641
2642 if (exe_ctx.process->Halt().Success())
2643 {
2644 timeout_ptr = NULL;
2645 if (log)
2646 log->Printf ("Halt succeeded.");
2647
2648 // Between the time that we got the timeout and the time we halted, but target
2649 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2650 // timeout to
2651 got_event = listener.WaitForEvent(NULL, event_sp);
2652
2653 if (got_event)
2654 {
2655 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2656 if (log)
2657 {
2658 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2659 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2660 log->Printf (" Event was the Halt interruption event.");
2661 }
2662
2663 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2664 {
2665 if (log)
2666 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002667 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002668 break;
2669 }
2670
2671 if (try_all_threads
2672 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2673 {
2674
2675 thread_plan_sp->SetStopOthers (false);
2676 if (log)
2677 log->Printf ("About to resume.");
2678
2679 exe_ctx.process->Resume();
2680 continue;
2681 }
2682 else
2683 {
2684 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002685 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002686 }
2687 }
2688 }
2689 }
2690
2691 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2692 if (log)
2693 log->Printf("Got event: %s.", StateAsCString(stop_state));
2694
2695 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2696 continue;
2697
2698 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2699 {
Greg Clayton427f2902010-12-14 02:59:59 +00002700 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002701 break;
2702 }
2703 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2704 {
Greg Clayton427f2902010-12-14 02:59:59 +00002705 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002706 break;
2707 }
2708 else
2709 {
2710 if (log)
2711 {
2712 StreamString s;
2713 event_sp->Dump (&s);
2714 StreamString ts;
2715
2716 const char *event_explanation;
2717
2718 do
2719 {
2720 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2721
2722 if (!event_data)
2723 {
2724 event_explanation = "<no event data>";
2725 break;
2726 }
2727
2728 Process *process = event_data->GetProcessSP().get();
2729
2730 if (!process)
2731 {
2732 event_explanation = "<no process>";
2733 break;
2734 }
2735
2736 ThreadList &thread_list = process->GetThreadList();
2737
2738 uint32_t num_threads = thread_list.GetSize();
2739 uint32_t thread_index;
2740
2741 ts.Printf("<%u threads> ", num_threads);
2742
2743 for (thread_index = 0;
2744 thread_index < num_threads;
2745 ++thread_index)
2746 {
2747 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2748
2749 if (!thread)
2750 {
2751 ts.Printf("<?> ");
2752 continue;
2753 }
2754
2755 ts.Printf("<");
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002756 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002757
2758 if (register_context)
2759 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2760 else
2761 ts.Printf("[ip unknown] ");
2762
2763 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2764 if (stop_info_sp)
2765 {
2766 const char *stop_desc = stop_info_sp->GetDescription();
2767 if (stop_desc)
2768 ts.PutCString (stop_desc);
2769 }
2770 ts.Printf(">");
2771 }
2772
2773 event_explanation = ts.GetData();
2774 } while (0);
2775
2776 if (log)
2777 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2778 }
2779
2780 if (discard_on_error && thread_plan_sp)
2781 {
2782 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2783 }
Greg Clayton427f2902010-12-14 02:59:59 +00002784 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002785 break;
2786 }
2787 }
2788
2789 if (exe_ctx.process)
2790 exe_ctx.process->RestoreProcessEvents ();
2791
2792 // Thread we ran the function in may have gone away because we ran the target
2793 // Check that it's still there.
2794 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2795 if (exe_ctx.thread)
2796 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2797
2798 // Also restore the current process'es selected frame & thread, since this function calling may
2799 // be done behind the user's back.
2800
2801 if (selected_tid != LLDB_INVALID_THREAD_ID)
2802 {
2803 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2804 {
2805 // We were able to restore the selected thread, now restore the frame:
2806 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2807 }
2808 }
2809
2810 return return_value;
2811}
2812
2813const char *
2814Process::ExecutionResultAsCString (ExecutionResults result)
2815{
2816 const char *result_name;
2817
2818 switch (result)
2819 {
Greg Clayton427f2902010-12-14 02:59:59 +00002820 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002821 result_name = "eExecutionCompleted";
2822 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002823 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002824 result_name = "eExecutionDiscarded";
2825 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002826 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002827 result_name = "eExecutionInterrupted";
2828 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002829 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002830 result_name = "eExecutionSetupError";
2831 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002832 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002833 result_name = "eExecutionTimedOut";
2834 break;
2835 }
2836 return result_name;
2837}
2838
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002839//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002840// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002841//--------------------------------------------------------------
2842
Greg Claytond0a5a232010-09-19 02:33:57 +00002843Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002844 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002845{
Greg Clayton638351a2010-12-04 00:10:17 +00002846 m_default_settings.reset (new ProcessInstanceSettings (*this,
2847 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002848 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002849}
2850
Greg Claytond0a5a232010-09-19 02:33:57 +00002851Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002852{
2853}
2854
2855lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002856Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002857{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002858 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2859 false,
2860 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002861 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2862 return new_settings_sp;
2863}
2864
2865//--------------------------------------------------------------
2866// class ProcessInstanceSettings
2867//--------------------------------------------------------------
2868
Greg Clayton638351a2010-12-04 00:10:17 +00002869ProcessInstanceSettings::ProcessInstanceSettings
2870(
2871 UserSettingsController &owner,
2872 bool live_instance,
2873 const char *name
2874) :
2875 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002876 m_run_args (),
2877 m_env_vars (),
2878 m_input_path (),
2879 m_output_path (),
2880 m_error_path (),
2881 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002882 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002883 m_disable_stdio (false),
2884 m_inherit_host_env (true),
2885 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002886{
Caroline Tice396704b2010-09-09 18:26:37 +00002887 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2888 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2889 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00002890 // This is true for CreateInstanceName() too.
2891
2892 if (GetInstanceName () == InstanceSettings::InvalidName())
2893 {
2894 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2895 m_owner.RegisterInstanceSettings (this);
2896 }
Caroline Tice396704b2010-09-09 18:26:37 +00002897
2898 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002899 {
2900 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2901 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002902 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002903 }
2904}
2905
2906ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002907 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002908 m_run_args (rhs.m_run_args),
2909 m_env_vars (rhs.m_env_vars),
2910 m_input_path (rhs.m_input_path),
2911 m_output_path (rhs.m_output_path),
2912 m_error_path (rhs.m_error_path),
2913 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00002914 m_disable_aslr (rhs.m_disable_aslr),
2915 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002916{
2917 if (m_instance_name != InstanceSettings::GetDefaultName())
2918 {
2919 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2920 CopyInstanceSettings (pending_settings,false);
2921 m_owner.RemovePendingSettings (m_instance_name);
2922 }
2923}
2924
2925ProcessInstanceSettings::~ProcessInstanceSettings ()
2926{
2927}
2928
2929ProcessInstanceSettings&
2930ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2931{
2932 if (this != &rhs)
2933 {
2934 m_run_args = rhs.m_run_args;
2935 m_env_vars = rhs.m_env_vars;
2936 m_input_path = rhs.m_input_path;
2937 m_output_path = rhs.m_output_path;
2938 m_error_path = rhs.m_error_path;
2939 m_plugin = rhs.m_plugin;
2940 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002941 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00002942 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002943 }
2944
2945 return *this;
2946}
2947
2948
2949void
2950ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2951 const char *index_value,
2952 const char *value,
2953 const ConstString &instance_name,
2954 const SettingEntry &entry,
2955 lldb::VarSetOperationType op,
2956 Error &err,
2957 bool pending)
2958{
2959 if (var_name == RunArgsVarName())
2960 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2961 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00002962 {
2963 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002964 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002965 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002966 else if (var_name == InputPathVarName())
2967 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2968 else if (var_name == OutputPathVarName())
2969 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2970 else if (var_name == ErrorPathVarName())
2971 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2972 else if (var_name == PluginVarName())
2973 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002974 else if (var_name == InheritHostEnvVarName())
2975 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002976 else if (var_name == DisableASLRVarName())
2977 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00002978 else if (var_name == DisableSTDIOVarName ())
2979 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002980}
2981
2982void
2983ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2984 bool pending)
2985{
2986 if (new_settings.get() == NULL)
2987 return;
2988
2989 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2990
2991 m_run_args = new_process_settings->m_run_args;
2992 m_env_vars = new_process_settings->m_env_vars;
2993 m_input_path = new_process_settings->m_input_path;
2994 m_output_path = new_process_settings->m_output_path;
2995 m_error_path = new_process_settings->m_error_path;
2996 m_plugin = new_process_settings->m_plugin;
2997 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002998 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002999}
3000
Caroline Ticebcb5b452010-09-20 21:37:42 +00003001bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003002ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3003 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003004 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003005 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003006{
3007 if (var_name == RunArgsVarName())
3008 {
3009 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003010 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003011 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3012 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003013 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003014 }
3015 else if (var_name == EnvVarsVarName())
3016 {
Greg Clayton638351a2010-12-04 00:10:17 +00003017 GetHostEnvironmentIfNeeded ();
3018
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003019 if (m_env_vars.size() > 0)
3020 {
3021 std::map<std::string, std::string>::iterator pos;
3022 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3023 {
3024 StreamString value_str;
3025 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3026 value.AppendString (value_str.GetData());
3027 }
3028 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003029 }
3030 else if (var_name == InputPathVarName())
3031 {
3032 value.AppendString (m_input_path.c_str());
3033 }
3034 else if (var_name == OutputPathVarName())
3035 {
3036 value.AppendString (m_output_path.c_str());
3037 }
3038 else if (var_name == ErrorPathVarName())
3039 {
3040 value.AppendString (m_error_path.c_str());
3041 }
3042 else if (var_name == PluginVarName())
3043 {
3044 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3045 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003046 else if (var_name == InheritHostEnvVarName())
3047 {
3048 if (m_inherit_host_env)
3049 value.AppendString ("true");
3050 else
3051 value.AppendString ("false");
3052 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003053 else if (var_name == DisableASLRVarName())
3054 {
3055 if (m_disable_aslr)
3056 value.AppendString ("true");
3057 else
3058 value.AppendString ("false");
3059 }
Caroline Ticebd666012010-12-03 18:46:09 +00003060 else if (var_name == DisableSTDIOVarName())
3061 {
3062 if (m_disable_stdio)
3063 value.AppendString ("true");
3064 else
3065 value.AppendString ("false");
3066 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003067 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003068 {
3069 if (err)
3070 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3071 return false;
3072 }
3073 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003074}
3075
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003076const ConstString
3077ProcessInstanceSettings::CreateInstanceName ()
3078{
3079 static int instance_count = 1;
3080 StreamString sstr;
3081
3082 sstr.Printf ("process_%d", instance_count);
3083 ++instance_count;
3084
3085 const ConstString ret_val (sstr.GetData());
3086 return ret_val;
3087}
3088
3089const ConstString &
3090ProcessInstanceSettings::RunArgsVarName ()
3091{
3092 static ConstString run_args_var_name ("run-args");
3093
3094 return run_args_var_name;
3095}
3096
3097const ConstString &
3098ProcessInstanceSettings::EnvVarsVarName ()
3099{
3100 static ConstString env_vars_var_name ("env-vars");
3101
3102 return env_vars_var_name;
3103}
3104
3105const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003106ProcessInstanceSettings::InheritHostEnvVarName ()
3107{
3108 static ConstString g_name ("inherit-env");
3109
3110 return g_name;
3111}
3112
3113const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003114ProcessInstanceSettings::InputPathVarName ()
3115{
3116 static ConstString input_path_var_name ("input-path");
3117
3118 return input_path_var_name;
3119}
3120
3121const ConstString &
3122ProcessInstanceSettings::OutputPathVarName ()
3123{
Caroline Tice87097232010-09-07 18:35:40 +00003124 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003125
3126 return output_path_var_name;
3127}
3128
3129const ConstString &
3130ProcessInstanceSettings::ErrorPathVarName ()
3131{
Caroline Tice87097232010-09-07 18:35:40 +00003132 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003133
3134 return error_path_var_name;
3135}
3136
3137const ConstString &
3138ProcessInstanceSettings::PluginVarName ()
3139{
3140 static ConstString plugin_var_name ("plugin");
3141
3142 return plugin_var_name;
3143}
3144
3145
3146const ConstString &
3147ProcessInstanceSettings::DisableASLRVarName ()
3148{
3149 static ConstString disable_aslr_var_name ("disable-aslr");
3150
3151 return disable_aslr_var_name;
3152}
3153
Caroline Ticebd666012010-12-03 18:46:09 +00003154const ConstString &
3155ProcessInstanceSettings::DisableSTDIOVarName ()
3156{
3157 static ConstString disable_stdio_var_name ("disable-stdio");
3158
3159 return disable_stdio_var_name;
3160}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003161
3162//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003163// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003164//--------------------------------------------------
3165
3166SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003167Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003168{
3169 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3170 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3171};
3172
3173
3174lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003175Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003176{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003177 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3178 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3179 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003180};
3181
3182SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003183Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003184{
Greg Clayton638351a2010-12-04 00:10:17 +00003185 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3186 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3187 { "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." },
3188 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3189 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3190 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3191 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3192 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3193 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3194 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3195 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003196};
3197
3198
Jim Ingham7508e732010-08-09 23:31:02 +00003199