blob: 42e0cf7cd89c4927928868f8a31413b06712dd68 [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;
Greg Clayton0baa3942010-11-04 01:54:29 +0000712 StreamString expr;
713 char path[PATH_MAX];
714 image_spec.GetPath(path, sizeof(path));
715 expr.Printf("dlopen (\"%s\", 2)", path);
716 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000717 lldb::ValueObjectSP result_valobj_sp;
718 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000719 if (result_valobj_sp->GetError().Success())
720 {
721 Scalar scalar;
722 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
723 {
724 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
725 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
726 {
727 uint32_t image_token = m_image_tokens.size();
728 m_image_tokens.push_back (image_ptr);
729 return image_token;
730 }
731 }
732 }
733 }
734 }
735 }
736 return LLDB_INVALID_IMAGE_TOKEN;
737}
738
739//----------------------------------------------------------------------
740// UnloadImage
741//
742// This function provides a default implementation that works for most
743// unix variants. Any Process subclasses that need to do shared library
744// loading differently should override LoadImage and UnloadImage and
745// do what is needed.
746//----------------------------------------------------------------------
747Error
748Process::UnloadImage (uint32_t image_token)
749{
750 Error error;
751 if (image_token < m_image_tokens.size())
752 {
753 const addr_t image_addr = m_image_tokens[image_token];
754 if (image_addr == LLDB_INVALID_ADDRESS)
755 {
756 error.SetErrorString("image already unloaded");
757 }
758 else
759 {
760 DynamicLoader *loader = GetDynamicLoader();
761 if (loader)
762 error = loader->CanLoadImage();
763
764 if (error.Success())
765 {
766 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
767 if (thread_sp == NULL)
768 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
769
770 if (thread_sp)
771 {
772 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
773
774 if (frame_sp)
775 {
776 ExecutionContext exe_ctx;
777 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000778 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +0000779 StreamString expr;
780 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
781 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000782 lldb::ValueObjectSP result_valobj_sp;
783 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000784 if (result_valobj_sp->GetError().Success())
785 {
786 Scalar scalar;
787 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
788 {
789 if (scalar.UInt(1))
790 {
791 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
792 }
793 else
794 {
795 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
796 }
797 }
798 }
799 else
800 {
801 error = result_valobj_sp->GetError();
802 }
803 }
804 }
805 }
806 }
807 }
808 else
809 {
810 error.SetErrorString("invalid image token");
811 }
812 return error;
813}
814
Chris Lattner24943d22010-06-08 16:52:24 +0000815DynamicLoader *
816Process::GetDynamicLoader()
817{
818 return NULL;
819}
820
821const ABI *
822Process::GetABI()
823{
824 ConstString& triple = m_target_triple;
825
826 if (triple.IsEmpty())
827 return NULL;
828
829 if (m_abi_sp.get() == NULL)
830 {
831 m_abi_sp.reset(ABI::FindPlugin(triple));
832 }
833
834 return m_abi_sp.get();
835}
836
Jim Ingham642036f2010-09-23 02:01:19 +0000837LanguageRuntime *
838Process::GetLanguageRuntime(lldb::LanguageType language)
839{
840 LanguageRuntimeCollection::iterator pos;
841 pos = m_language_runtimes.find (language);
842 if (pos == m_language_runtimes.end())
843 {
844 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
845
846 m_language_runtimes[language]
847 = runtime;
848 return runtime.get();
849 }
850 else
851 return (*pos).second.get();
852}
853
854CPPLanguageRuntime *
855Process::GetCPPLanguageRuntime ()
856{
857 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
858 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
859 return static_cast<CPPLanguageRuntime *> (runtime);
860 return NULL;
861}
862
863ObjCLanguageRuntime *
864Process::GetObjCLanguageRuntime ()
865{
866 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
867 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
868 return static_cast<ObjCLanguageRuntime *> (runtime);
869 return NULL;
870}
871
Chris Lattner24943d22010-06-08 16:52:24 +0000872BreakpointSiteList &
873Process::GetBreakpointSiteList()
874{
875 return m_breakpoint_site_list;
876}
877
878const BreakpointSiteList &
879Process::GetBreakpointSiteList() const
880{
881 return m_breakpoint_site_list;
882}
883
884
885void
886Process::DisableAllBreakpointSites ()
887{
888 m_breakpoint_site_list.SetEnabledForAll (false);
889}
890
891Error
892Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
893{
894 Error error (DisableBreakpointSiteByID (break_id));
895
896 if (error.Success())
897 m_breakpoint_site_list.Remove(break_id);
898
899 return error;
900}
901
902Error
903Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
904{
905 Error error;
906 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
907 if (bp_site_sp)
908 {
909 if (bp_site_sp->IsEnabled())
910 error = DisableBreakpoint (bp_site_sp.get());
911 }
912 else
913 {
914 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
915 }
916
917 return error;
918}
919
920Error
921Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
922{
923 Error error;
924 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
925 if (bp_site_sp)
926 {
927 if (!bp_site_sp->IsEnabled())
928 error = EnableBreakpoint (bp_site_sp.get());
929 }
930 else
931 {
932 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
933 }
934 return error;
935}
936
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000937lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000938Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
939{
Greg Claytoneea26402010-09-14 23:36:40 +0000940 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000941 if (load_addr != LLDB_INVALID_ADDRESS)
942 {
943 BreakpointSiteSP bp_site_sp;
944
945 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
946 // create a new breakpoint site and add it.
947
948 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
949
950 if (bp_site_sp)
951 {
952 bp_site_sp->AddOwner (owner);
953 owner->SetBreakpointSite (bp_site_sp);
954 return bp_site_sp->GetID();
955 }
956 else
957 {
958 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
959 if (bp_site_sp)
960 {
961 if (EnableBreakpoint (bp_site_sp.get()).Success())
962 {
963 owner->SetBreakpointSite (bp_site_sp);
964 return m_breakpoint_site_list.Add (bp_site_sp);
965 }
966 }
967 }
968 }
969 // We failed to enable the breakpoint
970 return LLDB_INVALID_BREAK_ID;
971
972}
973
974void
975Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
976{
977 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
978 if (num_owners == 0)
979 {
980 DisableBreakpoint(bp_site_sp.get());
981 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
982 }
983}
984
985
986size_t
987Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
988{
989 size_t bytes_removed = 0;
990 addr_t intersect_addr;
991 size_t intersect_size;
992 size_t opcode_offset;
993 size_t idx;
994 BreakpointSiteSP bp;
995
996 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
997 {
998 if (bp->GetType() == BreakpointSite::eSoftware)
999 {
1000 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1001 {
1002 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1003 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1004 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1005 size_t buf_offset = intersect_addr - bp_addr;
1006 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1007 }
1008 }
1009 }
1010 return bytes_removed;
1011}
1012
1013
1014Error
1015Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1016{
1017 Error error;
1018 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001019 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001020 const addr_t bp_addr = bp_site->GetLoadAddress();
1021 if (log)
1022 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1023 if (bp_site->IsEnabled())
1024 {
1025 if (log)
1026 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1027 return error;
1028 }
1029
1030 if (bp_addr == LLDB_INVALID_ADDRESS)
1031 {
1032 error.SetErrorString("BreakpointSite contains an invalid load address.");
1033 return error;
1034 }
1035 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1036 // trap for the breakpoint site
1037 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1038
1039 if (bp_opcode_size == 0)
1040 {
1041 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1042 }
1043 else
1044 {
1045 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1046
1047 if (bp_opcode_bytes == NULL)
1048 {
1049 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1050 return error;
1051 }
1052
1053 // Save the original opcode by reading it
1054 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1055 {
1056 // Write a software breakpoint in place of the original opcode
1057 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1058 {
1059 uint8_t verify_bp_opcode_bytes[64];
1060 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1061 {
1062 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1063 {
1064 bp_site->SetEnabled(true);
1065 bp_site->SetType (BreakpointSite::eSoftware);
1066 if (log)
1067 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1068 bp_site->GetID(),
1069 (uint64_t)bp_addr);
1070 }
1071 else
1072 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1073 }
1074 else
1075 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1076 }
1077 else
1078 error.SetErrorString("Unable to write breakpoint trap to memory.");
1079 }
1080 else
1081 error.SetErrorString("Unable to read memory at breakpoint address.");
1082 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001083 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001084 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1085 bp_site->GetID(),
1086 (uint64_t)bp_addr,
1087 error.AsCString());
1088 return error;
1089}
1090
1091Error
1092Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1093{
1094 Error error;
1095 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001096 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001097 addr_t bp_addr = bp_site->GetLoadAddress();
1098 lldb::user_id_t breakID = bp_site->GetID();
1099 if (log)
1100 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
1101
1102 if (bp_site->IsHardware())
1103 {
1104 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1105 }
1106 else if (bp_site->IsEnabled())
1107 {
1108 const size_t break_op_size = bp_site->GetByteSize();
1109 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1110 if (break_op_size > 0)
1111 {
1112 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001113 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001114 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001115 bool break_op_found = false;
1116
1117 // Read the breakpoint opcode
1118 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1119 {
1120 bool verify = false;
1121 // Make sure we have the a breakpoint opcode exists at this address
1122 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1123 {
1124 break_op_found = true;
1125 // We found a valid breakpoint opcode at this address, now restore
1126 // the saved opcode.
1127 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1128 {
1129 verify = true;
1130 }
1131 else
1132 error.SetErrorString("Memory write failed when restoring original opcode.");
1133 }
1134 else
1135 {
1136 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1137 // Set verify to true and so we can check if the original opcode has already been restored
1138 verify = true;
1139 }
1140
1141 if (verify)
1142 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001143 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001144 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001145 // Verify that our original opcode made it back to the inferior
1146 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1147 {
1148 // compare the memory we just read with the original opcode
1149 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1150 {
1151 // SUCCESS
1152 bp_site->SetEnabled(false);
1153 if (log)
1154 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1155 return error;
1156 }
1157 else
1158 {
1159 if (break_op_found)
1160 error.SetErrorString("Failed to restore original opcode.");
1161 }
1162 }
1163 else
1164 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1165 }
1166 }
1167 else
1168 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1169 }
1170 }
1171 else
1172 {
1173 if (log)
1174 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1175 return error;
1176 }
1177
1178 if (log)
1179 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1180 bp_site->GetID(),
1181 (uint64_t)bp_addr,
1182 error.AsCString());
1183 return error;
1184
1185}
1186
Greg Claytonfd119992011-01-07 06:08:19 +00001187// Comment out line below to disable memory caching
1188#define ENABLE_MEMORY_CACHING
1189// Uncomment to verify memory caching works after making changes to caching code
1190//#define VERIFY_MEMORY_READS
1191
1192#if defined (ENABLE_MEMORY_CACHING)
1193
1194#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001195
1196size_t
1197Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1198{
Greg Claytonfd119992011-01-07 06:08:19 +00001199 // Memory caching is enabled, with debug verification
1200 if (buf && size)
1201 {
1202 // Uncomment the line below to make sure memory caching is working.
1203 // I ran this through the test suite and got no assertions, so I am
1204 // pretty confident this is working well. If any changes are made to
1205 // memory caching, uncomment the line below and test your changes!
1206
1207 // Verify all memory reads by using the cache first, then redundantly
1208 // reading the same memory from the inferior and comparing to make sure
1209 // everything is exactly the same.
1210 std::string verify_buf (size, '\0');
1211 assert (verify_buf.size() == size);
1212 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1213 Error verify_error;
1214 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1215 assert (cache_bytes_read == verify_bytes_read);
1216 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1217 assert (verify_error.Success() == error.Success());
1218 return cache_bytes_read;
1219 }
1220 return 0;
1221}
1222
1223#else // #if defined (VERIFY_MEMORY_READS)
1224
1225size_t
1226Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1227{
1228 // Memory caching enabled, no verification
1229 return m_memory_cache.Read (this, addr, buf, size, error);
1230}
1231
1232#endif // #else for #if defined (VERIFY_MEMORY_READS)
1233
1234#else // #if defined (ENABLE_MEMORY_CACHING)
1235
1236size_t
1237Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1238{
1239 // Memory caching is disabled
1240 return ReadMemoryFromInferior (addr, buf, size, error);
1241}
1242
1243#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1244
1245
1246size_t
1247Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1248{
Chris Lattner24943d22010-06-08 16:52:24 +00001249 if (buf == NULL || size == 0)
1250 return 0;
1251
1252 size_t bytes_read = 0;
1253 uint8_t *bytes = (uint8_t *)buf;
1254
1255 while (bytes_read < size)
1256 {
1257 const size_t curr_size = size - bytes_read;
1258 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1259 bytes + bytes_read,
1260 curr_size,
1261 error);
1262 bytes_read += curr_bytes_read;
1263 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1264 break;
1265 }
1266
1267 // Replace any software breakpoint opcodes that fall into this range back
1268 // into "buf" before we return
1269 if (bytes_read > 0)
1270 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1271 return bytes_read;
1272}
1273
Greg Claytonf72fdee2010-12-16 20:01:20 +00001274uint64_t
1275Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1276{
1277 if (integer_byte_size > sizeof(uint64_t))
1278 {
1279 error.SetErrorString ("unsupported integer size");
1280 }
1281 else
1282 {
1283 uint8_t tmp[sizeof(uint64_t)];
1284 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1285 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1286 {
1287 uint32_t offset = 0;
1288 return data.GetMaxU64 (&offset, integer_byte_size);
1289 }
1290 }
1291 // Any plug-in that doesn't return success a memory read with the number
1292 // of bytes that were requested should be setting the error
1293 assert (error.Fail());
1294 return 0;
1295}
1296
Chris Lattner24943d22010-06-08 16:52:24 +00001297size_t
1298Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1299{
1300 size_t bytes_written = 0;
1301 const uint8_t *bytes = (const uint8_t *)buf;
1302
1303 while (bytes_written < size)
1304 {
1305 const size_t curr_size = size - bytes_written;
1306 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1307 bytes + bytes_written,
1308 curr_size,
1309 error);
1310 bytes_written += curr_bytes_written;
1311 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1312 break;
1313 }
1314 return bytes_written;
1315}
1316
1317size_t
1318Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1319{
Greg Claytonfd119992011-01-07 06:08:19 +00001320#if defined (ENABLE_MEMORY_CACHING)
1321 m_memory_cache.Flush (addr, size);
1322#endif
1323
Chris Lattner24943d22010-06-08 16:52:24 +00001324 if (buf == NULL || size == 0)
1325 return 0;
1326 // We need to write any data that would go where any current software traps
1327 // (enabled software breakpoints) any software traps (breakpoints) that we
1328 // may have placed in our tasks memory.
1329
1330 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1331 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1332
1333 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1334 return DoWriteMemory(addr, buf, size, error);
1335
1336 BreakpointSiteList::collection::const_iterator pos;
1337 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001338 addr_t intersect_addr = 0;
1339 size_t intersect_size = 0;
1340 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001341 const uint8_t *ubuf = (const uint8_t *)buf;
1342
1343 for (pos = iter; pos != end; ++pos)
1344 {
1345 BreakpointSiteSP bp;
1346 bp = pos->second;
1347
1348 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1349 assert(addr <= intersect_addr && intersect_addr < addr + size);
1350 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1351 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1352
1353 // Check for bytes before this breakpoint
1354 const addr_t curr_addr = addr + bytes_written;
1355 if (intersect_addr > curr_addr)
1356 {
1357 // There are some bytes before this breakpoint that we need to
1358 // just write to memory
1359 size_t curr_size = intersect_addr - curr_addr;
1360 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1361 ubuf + bytes_written,
1362 curr_size,
1363 error);
1364 bytes_written += curr_bytes_written;
1365 if (curr_bytes_written != curr_size)
1366 {
1367 // We weren't able to write all of the requested bytes, we
1368 // are done looping and will return the number of bytes that
1369 // we have written so far.
1370 break;
1371 }
1372 }
1373
1374 // Now write any bytes that would cover up any software breakpoints
1375 // directly into the breakpoint opcode buffer
1376 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1377 bytes_written += intersect_size;
1378 }
1379
1380 // Write any remaining bytes after the last breakpoint if we have any left
1381 if (bytes_written < size)
1382 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1383 ubuf + bytes_written,
1384 size - bytes_written,
1385 error);
1386
1387 return bytes_written;
1388}
1389
1390addr_t
1391Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1392{
1393 // Fixme: we should track the blocks we've allocated, and clean them up...
1394 // We could even do our own allocator here if that ends up being more efficient.
1395 return DoAllocateMemory (size, permissions, error);
1396}
1397
1398Error
1399Process::DeallocateMemory (addr_t ptr)
1400{
1401 return DoDeallocateMemory (ptr);
1402}
1403
1404
1405Error
1406Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1407{
1408 Error error;
1409 error.SetErrorString("watchpoints are not supported");
1410 return error;
1411}
1412
1413Error
1414Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1415{
1416 Error error;
1417 error.SetErrorString("watchpoints are not supported");
1418 return error;
1419}
1420
1421StateType
1422Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1423{
1424 StateType state;
1425 // Now wait for the process to launch and return control to us, and then
1426 // call DidLaunch:
1427 while (1)
1428 {
1429 // FIXME: Might want to put a timeout in here:
1430 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1431 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1432 break;
1433 else
1434 HandlePrivateEvent (event_sp);
1435 }
1436 return state;
1437}
1438
1439Error
1440Process::Launch
1441(
1442 char const *argv[],
1443 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001444 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001445 const char *stdin_path,
1446 const char *stdout_path,
1447 const char *stderr_path
1448)
1449{
1450 Error error;
1451 m_target_triple.Clear();
1452 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001453 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001454
1455 Module *exe_module = m_target.GetExecutableModule().get();
1456 if (exe_module)
1457 {
1458 char exec_file_path[PATH_MAX];
1459 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1460 if (exe_module->GetFileSpec().Exists())
1461 {
1462 error = WillLaunch (exe_module);
1463 if (error.Success())
1464 {
Greg Claytond8c62532010-10-07 04:19:01 +00001465 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001466 // The args coming in should not contain the application name, the
1467 // lldb_private::Process class will add this in case the executable
1468 // gets resolved to a different file than was given on the command
1469 // line (like when an applicaiton bundle is specified and will
1470 // resolve to the contained exectuable file, or the file given was
1471 // a symlink or other file system link that resolves to a different
1472 // file).
1473
1474 // Get the resolved exectuable path
1475
1476 // Make a new argument vector
1477 std::vector<const char *> exec_path_plus_argv;
1478 // Append the resolved executable path
1479 exec_path_plus_argv.push_back (exec_file_path);
1480
1481 // Push all args if there are any
1482 if (argv)
1483 {
1484 for (int i = 0; argv[i]; ++i)
1485 exec_path_plus_argv.push_back(argv[i]);
1486 }
1487
1488 // Push a NULL to terminate the args.
1489 exec_path_plus_argv.push_back(NULL);
1490
1491 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001492 error = DoLaunch (exe_module,
1493 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1494 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001495 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001496 stdin_path,
1497 stdout_path,
1498 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001499
1500 if (error.Fail())
1501 {
1502 if (GetID() != LLDB_INVALID_PROCESS_ID)
1503 {
1504 SetID (LLDB_INVALID_PROCESS_ID);
1505 const char *error_string = error.AsCString();
1506 if (error_string == NULL)
1507 error_string = "launch failed";
1508 SetExitStatus (-1, error_string);
1509 }
1510 }
1511 else
1512 {
1513 EventSP event_sp;
1514 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1515
1516 if (state == eStateStopped || state == eStateCrashed)
1517 {
1518 DidLaunch ();
1519
1520 // This delays passing the stopped event to listeners till DidLaunch gets
1521 // a chance to complete...
1522 HandlePrivateEvent (event_sp);
1523 StartPrivateStateThread ();
1524 }
1525 else if (state == eStateExited)
1526 {
1527 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1528 // not likely to work, and return an invalid pid.
1529 HandlePrivateEvent (event_sp);
1530 }
1531 }
1532 }
1533 }
1534 else
1535 {
1536 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1537 }
1538 }
1539 return error;
1540}
1541
1542Error
1543Process::CompleteAttach ()
1544{
1545 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001546
1547 if (GetID() == LLDB_INVALID_PROCESS_ID)
1548 {
1549 error.SetErrorString("no process");
1550 }
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552 EventSP event_sp;
1553 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1554 if (state == eStateStopped || state == eStateCrashed)
1555 {
1556 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001557 // Figure out which one is the executable, and set that in our target:
1558 ModuleList &modules = GetTarget().GetImages();
1559
1560 size_t num_modules = modules.GetSize();
1561 for (int i = 0; i < num_modules; i++)
1562 {
1563 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1564 if (module_sp->IsExecutable())
1565 {
1566 ModuleSP exec_module = GetTarget().GetExecutableModule();
1567 if (!exec_module || exec_module != module_sp)
1568 {
1569
1570 GetTarget().SetExecutableModule (module_sp, false);
1571 }
1572 break;
1573 }
1574 }
Chris Lattner24943d22010-06-08 16:52:24 +00001575
1576 // This delays passing the stopped event to listeners till DidLaunch gets
1577 // a chance to complete...
1578 HandlePrivateEvent(event_sp);
1579 StartPrivateStateThread();
1580 }
1581 else
1582 {
1583 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1584 // not likely to work, and return an invalid pid.
1585 if (state == eStateExited)
1586 HandlePrivateEvent (event_sp);
1587 error.SetErrorStringWithFormat("invalid state after attach: %s",
1588 lldb_private::StateAsCString(state));
1589 }
1590 return error;
1591}
1592
1593Error
1594Process::Attach (lldb::pid_t attach_pid)
1595{
1596
1597 m_target_triple.Clear();
1598 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001599 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001600
Jim Ingham7508e732010-08-09 23:31:02 +00001601 // Find the process and its architecture. Make sure it matches the architecture
1602 // of the current Target, and if not adjust it.
1603
1604 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1605 if (attach_spec != GetTarget().GetArchitecture())
1606 {
1607 // Set the architecture on the target.
1608 GetTarget().SetArchitecture(attach_spec);
1609 }
1610
Greg Clayton54e7afa2010-07-09 20:39:50 +00001611 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001612 if (error.Success())
1613 {
Greg Claytond8c62532010-10-07 04:19:01 +00001614 SetPublicState (eStateAttaching);
1615
Greg Clayton54e7afa2010-07-09 20:39:50 +00001616 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001617 if (error.Success())
1618 {
1619 error = CompleteAttach();
1620 }
1621 else
1622 {
1623 if (GetID() != LLDB_INVALID_PROCESS_ID)
1624 {
1625 SetID (LLDB_INVALID_PROCESS_ID);
1626 const char *error_string = error.AsCString();
1627 if (error_string == NULL)
1628 error_string = "attach failed";
1629
1630 SetExitStatus(-1, error_string);
1631 }
1632 }
1633 }
1634 return error;
1635}
1636
1637Error
1638Process::Attach (const char *process_name, bool wait_for_launch)
1639{
1640 m_target_triple.Clear();
1641 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001642 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001643
1644 // Find the process and its architecture. Make sure it matches the architecture
1645 // of the current Target, and if not adjust it.
1646
Jim Inghamea294182010-08-17 21:54:19 +00001647 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001648 {
Jim Inghamea294182010-08-17 21:54:19 +00001649 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001650 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001651 {
1652 // Set the architecture on the target.
1653 GetTarget().SetArchitecture(attach_spec);
1654 }
Jim Ingham7508e732010-08-09 23:31:02 +00001655 }
Jim Inghamea294182010-08-17 21:54:19 +00001656
Greg Clayton54e7afa2010-07-09 20:39:50 +00001657 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001658 if (error.Success())
1659 {
Greg Claytond8c62532010-10-07 04:19:01 +00001660 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001661 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001662 if (error.Fail())
1663 {
1664 if (GetID() != LLDB_INVALID_PROCESS_ID)
1665 {
1666 SetID (LLDB_INVALID_PROCESS_ID);
1667 const char *error_string = error.AsCString();
1668 if (error_string == NULL)
1669 error_string = "attach failed";
1670
1671 SetExitStatus(-1, error_string);
1672 }
1673 }
1674 else
1675 {
1676 error = CompleteAttach();
1677 }
1678 }
1679 return error;
1680}
1681
1682Error
1683Process::Resume ()
1684{
Greg Claytone005f2c2010-11-06 01:53:30 +00001685 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001686 if (log)
1687 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1688
1689 Error error (WillResume());
1690 // Tell the process it is about to resume before the thread list
1691 if (error.Success())
1692 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001693 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001694 // can let all of our threads know that they are about to be
1695 // resumed. Threads will each be called with
1696 // Thread::WillResume(StateType) where StateType contains the state
1697 // that they are supposed to have when the process is resumed
1698 // (suspended/running/stepping). Threads should also check
1699 // their resume signal in lldb::Thread::GetResumeSignal()
1700 // to see if they are suppoed to start back up with a signal.
1701 if (m_thread_list.WillResume())
1702 {
1703 error = DoResume();
1704 if (error.Success())
1705 {
1706 DidResume();
1707 m_thread_list.DidResume();
1708 }
1709 }
1710 else
1711 {
1712 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1713 }
1714 }
1715 return error;
1716}
1717
1718Error
1719Process::Halt ()
1720{
1721 Error error (WillHalt());
1722
1723 if (error.Success())
1724 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001725
1726 bool caused_stop = false;
1727 EventSP event_sp;
1728
1729 // Pause our private state thread so we can ensure no one else eats
1730 // the stop event out from under us.
1731 PausePrivateStateThread();
1732
1733 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001734 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001735 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001736 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001737 // If "caused_stop" is true, then DoHalt stopped the process. If
1738 // "caused_stop" is false, the process was already stopped.
1739 // If the DoHalt caused the process to stop, then we want to catch
1740 // this event and set the interrupted bool to true before we pass
1741 // this along so clients know that the process was interrupted by
1742 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001743 if (caused_stop)
1744 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001745 // Wait for 2 seconds for the process to stop.
1746 TimeValue timeout_time;
1747 timeout_time = TimeValue::Now();
1748 timeout_time.OffsetWithSeconds(2);
1749 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1750
1751 if (state == eStateInvalid)
1752 {
1753 // We timeout out and didn't get a stop event...
1754 error.SetErrorString ("Halt timed out.");
1755 }
1756 else
1757 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001758 if (StateIsStoppedState (state))
1759 {
1760 // We caused the process to interrupt itself, so mark this
1761 // as such in the stop event so clients can tell an interrupted
1762 // process from a natural stop
1763 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1764 }
1765 else
1766 {
1767 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1768 if (log)
1769 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1770 error.SetErrorString ("Did not get stopped event after halt.");
1771 }
1772 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001773 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001774 DidHalt();
1775
Jim Ingham3ae449a2010-11-17 02:32:00 +00001776 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001777 // Resume our private state thread before we post the event (if any)
1778 ResumePrivateStateThread();
1779
1780 // Post any event we might have consumed. If all goes well, we will have
1781 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001782 // bool in the event. Post it to the private event queue and that will end up
1783 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001784 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001785 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001786
Chris Lattner24943d22010-06-08 16:52:24 +00001787 }
1788 return error;
1789}
1790
1791Error
1792Process::Detach ()
1793{
1794 Error error (WillDetach());
1795
1796 if (error.Success())
1797 {
1798 DisableAllBreakpointSites();
1799 error = DoDetach();
1800 if (error.Success())
1801 {
1802 DidDetach();
1803 StopPrivateStateThread();
1804 }
1805 }
1806 return error;
1807}
1808
1809Error
1810Process::Destroy ()
1811{
1812 Error error (WillDestroy());
1813 if (error.Success())
1814 {
1815 DisableAllBreakpointSites();
1816 error = DoDestroy();
1817 if (error.Success())
1818 {
1819 DidDestroy();
1820 StopPrivateStateThread();
1821 }
Caroline Tice861efb32010-11-16 05:07:41 +00001822 m_stdio_communication.StopReadThread();
1823 m_stdio_communication.Disconnect();
1824 if (m_process_input_reader && m_process_input_reader->IsActive())
1825 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1826 if (m_process_input_reader)
1827 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001828 }
1829 return error;
1830}
1831
1832Error
1833Process::Signal (int signal)
1834{
1835 Error error (WillSignal());
1836 if (error.Success())
1837 {
1838 error = DoSignal(signal);
1839 if (error.Success())
1840 DidSignal();
1841 }
1842 return error;
1843}
1844
1845UnixSignals &
1846Process::GetUnixSignals ()
1847{
1848 return m_unix_signals;
1849}
1850
1851Target &
1852Process::GetTarget ()
1853{
1854 return m_target;
1855}
1856
1857const Target &
1858Process::GetTarget () const
1859{
1860 return m_target;
1861}
1862
1863uint32_t
1864Process::GetAddressByteSize()
1865{
Greg Clayton20d338f2010-11-18 05:57:03 +00001866 if (m_addr_byte_size == 0)
1867 return m_target.GetArchitecture().GetAddressByteSize();
1868 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001869}
1870
1871bool
1872Process::ShouldBroadcastEvent (Event *event_ptr)
1873{
1874 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1875 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001876 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001877
1878 switch (state)
1879 {
1880 case eStateAttaching:
1881 case eStateLaunching:
1882 case eStateDetached:
1883 case eStateExited:
1884 case eStateUnloaded:
1885 // These events indicate changes in the state of the debugging session, always report them.
1886 return_value = true;
1887 break;
1888 case eStateInvalid:
1889 // We stopped for no apparent reason, don't report it.
1890 return_value = false;
1891 break;
1892 case eStateRunning:
1893 case eStateStepping:
1894 // If we've started the target running, we handle the cases where we
1895 // are already running and where there is a transition from stopped to
1896 // running differently.
1897 // running -> running: Automatically suppress extra running events
1898 // stopped -> running: Report except when there is one or more no votes
1899 // and no yes votes.
1900 SynchronouslyNotifyStateChanged (state);
1901 switch (m_public_state.GetValue())
1902 {
1903 case eStateRunning:
1904 case eStateStepping:
1905 // We always suppress multiple runnings with no PUBLIC stop in between.
1906 return_value = false;
1907 break;
1908 default:
1909 // TODO: make this work correctly. For now always report
1910 // run if we aren't running so we don't miss any runnning
1911 // events. If I run the lldb/test/thread/a.out file and
1912 // break at main.cpp:58, run and hit the breakpoints on
1913 // multiple threads, then somehow during the stepping over
1914 // of all breakpoints no run gets reported.
1915 return_value = true;
1916
1917 // This is a transition from stop to run.
1918 switch (m_thread_list.ShouldReportRun (event_ptr))
1919 {
1920 case eVoteYes:
1921 case eVoteNoOpinion:
1922 return_value = true;
1923 break;
1924 case eVoteNo:
1925 return_value = false;
1926 break;
1927 }
1928 break;
1929 }
1930 break;
1931 case eStateStopped:
1932 case eStateCrashed:
1933 case eStateSuspended:
1934 {
1935 // We've stopped. First see if we're going to restart the target.
1936 // If we are going to stop, then we always broadcast the event.
1937 // 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 +00001938 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001939 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001940 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001941 if (log)
1942 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001943 return true;
1944 }
1945 else
1946 {
Chris Lattner24943d22010-06-08 16:52:24 +00001947 RefreshStateAfterStop ();
1948
1949 if (m_thread_list.ShouldStop (event_ptr) == false)
1950 {
1951 switch (m_thread_list.ShouldReportStop (event_ptr))
1952 {
1953 case eVoteYes:
1954 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001955 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001956 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001957 case eVoteNo:
1958 return_value = false;
1959 break;
1960 }
1961
1962 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001963 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001964 Resume ();
1965 }
1966 else
1967 {
1968 return_value = true;
1969 SynchronouslyNotifyStateChanged (state);
1970 }
1971 }
1972 }
1973 }
1974
1975 if (log)
1976 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1977 return return_value;
1978}
1979
1980//------------------------------------------------------------------
1981// Thread Queries
1982//------------------------------------------------------------------
1983
1984ThreadList &
1985Process::GetThreadList ()
1986{
1987 return m_thread_list;
1988}
1989
1990const ThreadList &
1991Process::GetThreadList () const
1992{
1993 return m_thread_list;
1994}
1995
1996
1997bool
1998Process::StartPrivateStateThread ()
1999{
Greg Claytone005f2c2010-11-06 01:53:30 +00002000 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002001
2002 if (log)
2003 log->Printf ("Process::%s ( )", __FUNCTION__);
2004
2005 // Create a thread that watches our internal state and controls which
2006 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002007 char thread_name[1024];
2008 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2009 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002010 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2011}
2012
2013void
2014Process::PausePrivateStateThread ()
2015{
2016 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2017}
2018
2019void
2020Process::ResumePrivateStateThread ()
2021{
2022 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2023}
2024
2025void
2026Process::StopPrivateStateThread ()
2027{
2028 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2029}
2030
2031void
2032Process::ControlPrivateStateThread (uint32_t signal)
2033{
Greg Claytone005f2c2010-11-06 01:53:30 +00002034 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002035
2036 assert (signal == eBroadcastInternalStateControlStop ||
2037 signal == eBroadcastInternalStateControlPause ||
2038 signal == eBroadcastInternalStateControlResume);
2039
2040 if (log)
2041 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
2042
2043 // Signal the private state thread
2044 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
2045 {
2046 TimeValue timeout_time;
2047 bool timed_out;
2048
2049 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2050
2051 timeout_time = TimeValue::Now();
2052 timeout_time.OffsetWithSeconds(2);
2053 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2054 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2055
2056 if (signal == eBroadcastInternalStateControlStop)
2057 {
2058 if (timed_out)
2059 Host::ThreadCancel (m_private_state_thread, NULL);
2060
2061 thread_result_t result = NULL;
2062 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002063 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002064 }
2065 }
2066}
2067
2068void
2069Process::HandlePrivateEvent (EventSP &event_sp)
2070{
Greg Claytone005f2c2010-11-06 01:53:30 +00002071 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002072 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2073 // See if we should broadcast this state to external clients?
2074 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2075 if (log)
2076 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2077
2078 if (should_broadcast)
2079 {
2080 if (log)
2081 {
2082 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2083 }
Caroline Tice861efb32010-11-16 05:07:41 +00002084 if (StateIsRunningState (internal_state))
2085 PushProcessInputReader ();
2086 else
2087 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002088 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2089 BroadcastEvent (event_sp);
2090 }
2091 else
2092 {
2093 if (log)
2094 {
2095 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2096 }
2097 }
2098}
2099
2100void *
2101Process::PrivateStateThread (void *arg)
2102{
2103 Process *proc = static_cast<Process*> (arg);
2104 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002105 return result;
2106}
2107
2108void *
2109Process::RunPrivateStateThread ()
2110{
2111 bool control_only = false;
2112 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2113
Greg Claytone005f2c2010-11-06 01:53:30 +00002114 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002115 if (log)
2116 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2117
2118 bool exit_now = false;
2119 while (!exit_now)
2120 {
2121 EventSP event_sp;
2122 WaitForEventsPrivate (NULL, event_sp, control_only);
2123 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2124 {
2125 switch (event_sp->GetType())
2126 {
2127 case eBroadcastInternalStateControlStop:
2128 exit_now = true;
2129 continue; // Go to next loop iteration so we exit without
2130 break; // doing any internal state managment below
2131
2132 case eBroadcastInternalStateControlPause:
2133 control_only = true;
2134 break;
2135
2136 case eBroadcastInternalStateControlResume:
2137 control_only = false;
2138 break;
2139 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002140
2141 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
2142 if (log)
2143 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2144
Chris Lattner24943d22010-06-08 16:52:24 +00002145 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002146 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002147 }
2148
2149
2150 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2151
2152 if (internal_state != eStateInvalid)
2153 {
2154 HandlePrivateEvent (event_sp);
2155 }
2156
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002157 if (internal_state == eStateInvalid ||
2158 internal_state == eStateExited ||
2159 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002160 {
2161 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
2162 if (log)
2163 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2164
Chris Lattner24943d22010-06-08 16:52:24 +00002165 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002166 }
Chris Lattner24943d22010-06-08 16:52:24 +00002167 }
2168
Caroline Tice926060e2010-10-29 21:48:37 +00002169 // Verify log is still enabled before attempting to write to it...
2170 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Chris Lattner24943d22010-06-08 16:52:24 +00002171 if (log)
2172 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2173
Greg Clayton8b4c16e2010-08-19 21:50:06 +00002174 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002175 return NULL;
2176}
2177
Chris Lattner24943d22010-06-08 16:52:24 +00002178//------------------------------------------------------------------
2179// Process Event Data
2180//------------------------------------------------------------------
2181
2182Process::ProcessEventData::ProcessEventData () :
2183 EventData (),
2184 m_process_sp (),
2185 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002186 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002187 m_update_state (false),
2188 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002189{
2190}
2191
2192Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2193 EventData (),
2194 m_process_sp (process_sp),
2195 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002196 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002197 m_update_state (false),
2198 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002199{
2200}
2201
2202Process::ProcessEventData::~ProcessEventData()
2203{
2204}
2205
2206const ConstString &
2207Process::ProcessEventData::GetFlavorString ()
2208{
2209 static ConstString g_flavor ("Process::ProcessEventData");
2210 return g_flavor;
2211}
2212
2213const ConstString &
2214Process::ProcessEventData::GetFlavor () const
2215{
2216 return ProcessEventData::GetFlavorString ();
2217}
2218
Chris Lattner24943d22010-06-08 16:52:24 +00002219void
2220Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2221{
2222 // This function gets called twice for each event, once when the event gets pulled
2223 // off of the private process event queue, and once when it gets pulled off of
2224 // the public event queue. m_update_state is used to distinguish these
2225 // two cases; it is false when we're just pulling it off for private handling,
2226 // and we don't want to do the breakpoint command handling then.
2227
2228 if (!m_update_state)
2229 return;
2230
2231 m_process_sp->SetPublicState (m_state);
2232
2233 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2234 if (m_state == eStateStopped && ! m_restarted)
2235 {
2236 int num_threads = m_process_sp->GetThreadList().GetSize();
2237 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002238
Chris Lattner24943d22010-06-08 16:52:24 +00002239 for (idx = 0; idx < num_threads; ++idx)
2240 {
2241 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2242
Jim Ingham6297a3a2010-10-20 00:39:53 +00002243 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2244 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002245 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002246 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002247 }
2248 }
Greg Clayton643ee732010-08-04 01:40:35 +00002249
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002250 // The stop action might restart the target. If it does, then we want to mark that in the
2251 // event so that whoever is receiving it will know to wait for the running event and reflect
2252 // that state appropriately.
2253
Chris Lattner24943d22010-06-08 16:52:24 +00002254 if (m_process_sp->GetPrivateState() == eStateRunning)
2255 SetRestarted(true);
2256 }
2257}
2258
2259void
2260Process::ProcessEventData::Dump (Stream *s) const
2261{
2262 if (m_process_sp)
2263 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2264
2265 s->Printf("state = %s", StateAsCString(GetState()));;
2266}
2267
2268const Process::ProcessEventData *
2269Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2270{
2271 if (event_ptr)
2272 {
2273 const EventData *event_data = event_ptr->GetData();
2274 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2275 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2276 }
2277 return NULL;
2278}
2279
2280ProcessSP
2281Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2282{
2283 ProcessSP process_sp;
2284 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2285 if (data)
2286 process_sp = data->GetProcessSP();
2287 return process_sp;
2288}
2289
2290StateType
2291Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2292{
2293 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2294 if (data == NULL)
2295 return eStateInvalid;
2296 else
2297 return data->GetState();
2298}
2299
2300bool
2301Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2302{
2303 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2304 if (data == NULL)
2305 return false;
2306 else
2307 return data->GetRestarted();
2308}
2309
2310void
2311Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2312{
2313 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2314 if (data != NULL)
2315 data->SetRestarted(new_value);
2316}
2317
2318bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002319Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2320{
2321 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2322 if (data == NULL)
2323 return false;
2324 else
2325 return data->GetInterrupted ();
2326}
2327
2328void
2329Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2330{
2331 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2332 if (data != NULL)
2333 data->SetInterrupted(new_value);
2334}
2335
2336bool
Chris Lattner24943d22010-06-08 16:52:24 +00002337Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2338{
2339 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2340 if (data)
2341 {
2342 data->SetUpdateStateOnRemoval();
2343 return true;
2344 }
2345 return false;
2346}
2347
Chris Lattner24943d22010-06-08 16:52:24 +00002348Target *
2349Process::CalculateTarget ()
2350{
2351 return &m_target;
2352}
2353
2354Process *
2355Process::CalculateProcess ()
2356{
2357 return this;
2358}
2359
2360Thread *
2361Process::CalculateThread ()
2362{
2363 return NULL;
2364}
2365
2366StackFrame *
2367Process::CalculateStackFrame ()
2368{
2369 return NULL;
2370}
2371
2372void
Greg Claytona830adb2010-10-04 01:05:56 +00002373Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002374{
2375 exe_ctx.target = &m_target;
2376 exe_ctx.process = this;
2377 exe_ctx.thread = NULL;
2378 exe_ctx.frame = NULL;
2379}
2380
2381lldb::ProcessSP
2382Process::GetSP ()
2383{
2384 return GetTarget().GetProcessSP();
2385}
2386
Jim Ingham7508e732010-08-09 23:31:02 +00002387uint32_t
2388Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2389{
2390 return 0;
2391}
2392
2393ArchSpec
2394Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2395{
2396 return Host::GetArchSpecForExistingProcess (pid);
2397}
2398
2399ArchSpec
2400Process::GetArchSpecForExistingProcess (const char *process_name)
2401{
2402 return Host::GetArchSpecForExistingProcess (process_name);
2403}
2404
Caroline Tice861efb32010-11-16 05:07:41 +00002405void
2406Process::AppendSTDOUT (const char * s, size_t len)
2407{
Greg Clayton20d338f2010-11-18 05:57:03 +00002408 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002409 m_stdout_data.append (s, len);
2410
Greg Claytonb3781332010-12-05 19:16:56 +00002411 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002412}
2413
2414void
2415Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2416{
2417 Process *process = (Process *) baton;
2418 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2419}
2420
2421size_t
2422Process::ProcessInputReaderCallback (void *baton,
2423 InputReader &reader,
2424 lldb::InputReaderAction notification,
2425 const char *bytes,
2426 size_t bytes_len)
2427{
2428 Process *process = (Process *) baton;
2429
2430 switch (notification)
2431 {
2432 case eInputReaderActivate:
2433 break;
2434
2435 case eInputReaderDeactivate:
2436 break;
2437
2438 case eInputReaderReactivate:
2439 break;
2440
2441 case eInputReaderGotToken:
2442 {
2443 Error error;
2444 process->PutSTDIN (bytes, bytes_len, error);
2445 }
2446 break;
2447
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002448 case eInputReaderInterrupt:
2449 process->Halt ();
2450 break;
2451
2452 case eInputReaderEndOfFile:
2453 process->AppendSTDOUT ("^D", 2);
2454 break;
2455
Caroline Tice861efb32010-11-16 05:07:41 +00002456 case eInputReaderDone:
2457 break;
2458
2459 }
2460
2461 return bytes_len;
2462}
2463
2464void
2465Process::ResetProcessInputReader ()
2466{
2467 m_process_input_reader.reset();
2468}
2469
2470void
2471Process::SetUpProcessInputReader (int file_descriptor)
2472{
2473 // First set up the Read Thread for reading/handling process I/O
2474
2475 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2476
2477 if (conn_ap.get())
2478 {
2479 m_stdio_communication.SetConnection (conn_ap.release());
2480 if (m_stdio_communication.IsConnected())
2481 {
2482 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2483 m_stdio_communication.StartReadThread();
2484
2485 // Now read thread is set up, set up input reader.
2486
2487 if (!m_process_input_reader.get())
2488 {
2489 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2490 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2491 this,
2492 eInputReaderGranularityByte,
2493 NULL,
2494 NULL,
2495 false));
2496
2497 if (err.Fail())
2498 m_process_input_reader.reset();
2499 }
2500 }
2501 }
2502}
2503
2504void
2505Process::PushProcessInputReader ()
2506{
2507 if (m_process_input_reader && !m_process_input_reader->IsActive())
2508 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2509}
2510
2511void
2512Process::PopProcessInputReader ()
2513{
2514 if (m_process_input_reader && m_process_input_reader->IsActive())
2515 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2516}
2517
Greg Clayton990de7b2010-11-18 23:32:35 +00002518
2519void
2520Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002521{
Greg Clayton990de7b2010-11-18 23:32:35 +00002522 UserSettingsControllerSP &usc = GetSettingsController();
2523 usc.reset (new SettingsController);
2524 UserSettingsController::InitializeSettingsController (usc,
2525 SettingsController::global_settings_table,
2526 SettingsController::instance_settings_table);
2527}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002528
Greg Clayton990de7b2010-11-18 23:32:35 +00002529void
2530Process::Terminate ()
2531{
2532 UserSettingsControllerSP &usc = GetSettingsController();
2533 UserSettingsController::FinalizeSettingsController (usc);
2534 usc.reset();
2535}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002536
Greg Clayton990de7b2010-11-18 23:32:35 +00002537UserSettingsControllerSP &
2538Process::GetSettingsController ()
2539{
2540 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002541 return g_settings_controller;
2542}
2543
Caroline Tice1ebef442010-09-27 00:30:10 +00002544void
2545Process::UpdateInstanceName ()
2546{
2547 ModuleSP module_sp = GetTarget().GetExecutableModule();
2548 if (module_sp)
2549 {
2550 StreamString sstr;
2551 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2552
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002553 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002554 sstr.GetData());
2555 }
2556}
2557
Greg Clayton427f2902010-12-14 02:59:59 +00002558ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002559Process::RunThreadPlan (ExecutionContext &exe_ctx,
2560 lldb::ThreadPlanSP &thread_plan_sp,
2561 bool stop_others,
2562 bool try_all_threads,
2563 bool discard_on_error,
2564 uint32_t single_thread_timeout_usec,
2565 Stream &errors)
2566{
2567 ExecutionResults return_value = eExecutionSetupError;
2568
2569 // Save this value for restoration of the execution context after we run
2570 uint32_t tid = exe_ctx.thread->GetIndexID();
2571
2572 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2573 // so we should arrange to reset them as well.
2574
2575 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2576 lldb::StackFrameSP selected_frame_sp;
2577
2578 uint32_t selected_tid;
2579 if (selected_thread_sp != NULL)
2580 {
2581 selected_tid = selected_thread_sp->GetIndexID();
2582 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2583 }
2584 else
2585 {
2586 selected_tid = LLDB_INVALID_THREAD_ID;
2587 }
2588
2589 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2590
2591 Listener listener("ClangFunction temporary listener");
2592 exe_ctx.process->HijackProcessEvents(&listener);
2593
2594 Error resume_error = exe_ctx.process->Resume ();
2595 if (!resume_error.Success())
2596 {
2597 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2598 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002599 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002600 }
2601
2602 // We need to call the function synchronously, so spin waiting for it to return.
2603 // If we get interrupted while executing, we're going to lose our context, and
2604 // won't be able to gather the result at this point.
2605 // We set the timeout AFTER the resume, since the resume takes some time and we
2606 // don't want to charge that to the timeout.
2607
2608 TimeValue* timeout_ptr = NULL;
2609 TimeValue real_timeout;
2610
2611 if (single_thread_timeout_usec != 0)
2612 {
2613 real_timeout = TimeValue::Now();
2614 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2615 timeout_ptr = &real_timeout;
2616 }
2617
2618 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2619 while (1)
2620 {
2621 lldb::EventSP event_sp;
2622 lldb::StateType stop_state = lldb::eStateInvalid;
2623 // Now wait for the process to stop again:
2624 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2625
2626 if (!got_event)
2627 {
2628 // Right now this is the only way to tell we've timed out...
2629 // We should interrupt the process here...
2630 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002631 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002632 if (try_all_threads)
2633 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2634 single_thread_timeout_usec);
2635 else
2636 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2637 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002638 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002639
2640 if (exe_ctx.process->Halt().Success())
2641 {
2642 timeout_ptr = NULL;
2643 if (log)
2644 log->Printf ("Halt succeeded.");
2645
2646 // Between the time that we got the timeout and the time we halted, but target
2647 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2648 // timeout to
2649 got_event = listener.WaitForEvent(NULL, event_sp);
2650
2651 if (got_event)
2652 {
2653 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2654 if (log)
2655 {
2656 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2657 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2658 log->Printf (" Event was the Halt interruption event.");
2659 }
2660
2661 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2662 {
2663 if (log)
2664 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002665 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002666 break;
2667 }
2668
2669 if (try_all_threads
2670 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2671 {
2672
2673 thread_plan_sp->SetStopOthers (false);
2674 if (log)
2675 log->Printf ("About to resume.");
2676
2677 exe_ctx.process->Resume();
2678 continue;
2679 }
2680 else
2681 {
2682 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002683 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002684 }
2685 }
2686 }
2687 }
2688
2689 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2690 if (log)
2691 log->Printf("Got event: %s.", StateAsCString(stop_state));
2692
2693 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2694 continue;
2695
2696 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2697 {
Greg Clayton427f2902010-12-14 02:59:59 +00002698 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002699 break;
2700 }
2701 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2702 {
Greg Clayton427f2902010-12-14 02:59:59 +00002703 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002704 break;
2705 }
2706 else
2707 {
2708 if (log)
2709 {
2710 StreamString s;
2711 event_sp->Dump (&s);
2712 StreamString ts;
2713
2714 const char *event_explanation;
2715
2716 do
2717 {
2718 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2719
2720 if (!event_data)
2721 {
2722 event_explanation = "<no event data>";
2723 break;
2724 }
2725
2726 Process *process = event_data->GetProcessSP().get();
2727
2728 if (!process)
2729 {
2730 event_explanation = "<no process>";
2731 break;
2732 }
2733
2734 ThreadList &thread_list = process->GetThreadList();
2735
2736 uint32_t num_threads = thread_list.GetSize();
2737 uint32_t thread_index;
2738
2739 ts.Printf("<%u threads> ", num_threads);
2740
2741 for (thread_index = 0;
2742 thread_index < num_threads;
2743 ++thread_index)
2744 {
2745 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2746
2747 if (!thread)
2748 {
2749 ts.Printf("<?> ");
2750 continue;
2751 }
2752
2753 ts.Printf("<");
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002754 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002755
2756 if (register_context)
2757 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2758 else
2759 ts.Printf("[ip unknown] ");
2760
2761 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2762 if (stop_info_sp)
2763 {
2764 const char *stop_desc = stop_info_sp->GetDescription();
2765 if (stop_desc)
2766 ts.PutCString (stop_desc);
2767 }
2768 ts.Printf(">");
2769 }
2770
2771 event_explanation = ts.GetData();
2772 } while (0);
2773
2774 if (log)
2775 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2776 }
2777
2778 if (discard_on_error && thread_plan_sp)
2779 {
2780 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2781 }
Greg Clayton427f2902010-12-14 02:59:59 +00002782 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002783 break;
2784 }
2785 }
2786
2787 if (exe_ctx.process)
2788 exe_ctx.process->RestoreProcessEvents ();
2789
2790 // Thread we ran the function in may have gone away because we ran the target
2791 // Check that it's still there.
2792 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2793 if (exe_ctx.thread)
2794 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2795
2796 // Also restore the current process'es selected frame & thread, since this function calling may
2797 // be done behind the user's back.
2798
2799 if (selected_tid != LLDB_INVALID_THREAD_ID)
2800 {
2801 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2802 {
2803 // We were able to restore the selected thread, now restore the frame:
2804 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2805 }
2806 }
2807
2808 return return_value;
2809}
2810
2811const char *
2812Process::ExecutionResultAsCString (ExecutionResults result)
2813{
2814 const char *result_name;
2815
2816 switch (result)
2817 {
Greg Clayton427f2902010-12-14 02:59:59 +00002818 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002819 result_name = "eExecutionCompleted";
2820 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002821 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002822 result_name = "eExecutionDiscarded";
2823 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002824 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002825 result_name = "eExecutionInterrupted";
2826 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002827 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002828 result_name = "eExecutionSetupError";
2829 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002830 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002831 result_name = "eExecutionTimedOut";
2832 break;
2833 }
2834 return result_name;
2835}
2836
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002837//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002838// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002839//--------------------------------------------------------------
2840
Greg Claytond0a5a232010-09-19 02:33:57 +00002841Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002842 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002843{
Greg Clayton638351a2010-12-04 00:10:17 +00002844 m_default_settings.reset (new ProcessInstanceSettings (*this,
2845 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002846 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002847}
2848
Greg Claytond0a5a232010-09-19 02:33:57 +00002849Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002850{
2851}
2852
2853lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002854Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002855{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002856 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2857 false,
2858 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002859 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2860 return new_settings_sp;
2861}
2862
2863//--------------------------------------------------------------
2864// class ProcessInstanceSettings
2865//--------------------------------------------------------------
2866
Greg Clayton638351a2010-12-04 00:10:17 +00002867ProcessInstanceSettings::ProcessInstanceSettings
2868(
2869 UserSettingsController &owner,
2870 bool live_instance,
2871 const char *name
2872) :
2873 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002874 m_run_args (),
2875 m_env_vars (),
2876 m_input_path (),
2877 m_output_path (),
2878 m_error_path (),
2879 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002880 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002881 m_disable_stdio (false),
2882 m_inherit_host_env (true),
2883 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002884{
Caroline Tice396704b2010-09-09 18:26:37 +00002885 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2886 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2887 // 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 +00002888 // This is true for CreateInstanceName() too.
2889
2890 if (GetInstanceName () == InstanceSettings::InvalidName())
2891 {
2892 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2893 m_owner.RegisterInstanceSettings (this);
2894 }
Caroline Tice396704b2010-09-09 18:26:37 +00002895
2896 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002897 {
2898 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2899 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002900 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002901 }
2902}
2903
2904ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002905 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002906 m_run_args (rhs.m_run_args),
2907 m_env_vars (rhs.m_env_vars),
2908 m_input_path (rhs.m_input_path),
2909 m_output_path (rhs.m_output_path),
2910 m_error_path (rhs.m_error_path),
2911 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00002912 m_disable_aslr (rhs.m_disable_aslr),
2913 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002914{
2915 if (m_instance_name != InstanceSettings::GetDefaultName())
2916 {
2917 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2918 CopyInstanceSettings (pending_settings,false);
2919 m_owner.RemovePendingSettings (m_instance_name);
2920 }
2921}
2922
2923ProcessInstanceSettings::~ProcessInstanceSettings ()
2924{
2925}
2926
2927ProcessInstanceSettings&
2928ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2929{
2930 if (this != &rhs)
2931 {
2932 m_run_args = rhs.m_run_args;
2933 m_env_vars = rhs.m_env_vars;
2934 m_input_path = rhs.m_input_path;
2935 m_output_path = rhs.m_output_path;
2936 m_error_path = rhs.m_error_path;
2937 m_plugin = rhs.m_plugin;
2938 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002939 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00002940 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002941 }
2942
2943 return *this;
2944}
2945
2946
2947void
2948ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2949 const char *index_value,
2950 const char *value,
2951 const ConstString &instance_name,
2952 const SettingEntry &entry,
2953 lldb::VarSetOperationType op,
2954 Error &err,
2955 bool pending)
2956{
2957 if (var_name == RunArgsVarName())
2958 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2959 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00002960 {
2961 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002962 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002963 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002964 else if (var_name == InputPathVarName())
2965 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2966 else if (var_name == OutputPathVarName())
2967 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2968 else if (var_name == ErrorPathVarName())
2969 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2970 else if (var_name == PluginVarName())
2971 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00002972 else if (var_name == InheritHostEnvVarName())
2973 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002974 else if (var_name == DisableASLRVarName())
2975 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00002976 else if (var_name == DisableSTDIOVarName ())
2977 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002978}
2979
2980void
2981ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2982 bool pending)
2983{
2984 if (new_settings.get() == NULL)
2985 return;
2986
2987 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
2988
2989 m_run_args = new_process_settings->m_run_args;
2990 m_env_vars = new_process_settings->m_env_vars;
2991 m_input_path = new_process_settings->m_input_path;
2992 m_output_path = new_process_settings->m_output_path;
2993 m_error_path = new_process_settings->m_error_path;
2994 m_plugin = new_process_settings->m_plugin;
2995 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00002996 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002997}
2998
Caroline Ticebcb5b452010-09-20 21:37:42 +00002999bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003000ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3001 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003002 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003003 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003004{
3005 if (var_name == RunArgsVarName())
3006 {
3007 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003008 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003009 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3010 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003011 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003012 }
3013 else if (var_name == EnvVarsVarName())
3014 {
Greg Clayton638351a2010-12-04 00:10:17 +00003015 GetHostEnvironmentIfNeeded ();
3016
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003017 if (m_env_vars.size() > 0)
3018 {
3019 std::map<std::string, std::string>::iterator pos;
3020 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3021 {
3022 StreamString value_str;
3023 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3024 value.AppendString (value_str.GetData());
3025 }
3026 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003027 }
3028 else if (var_name == InputPathVarName())
3029 {
3030 value.AppendString (m_input_path.c_str());
3031 }
3032 else if (var_name == OutputPathVarName())
3033 {
3034 value.AppendString (m_output_path.c_str());
3035 }
3036 else if (var_name == ErrorPathVarName())
3037 {
3038 value.AppendString (m_error_path.c_str());
3039 }
3040 else if (var_name == PluginVarName())
3041 {
3042 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3043 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003044 else if (var_name == InheritHostEnvVarName())
3045 {
3046 if (m_inherit_host_env)
3047 value.AppendString ("true");
3048 else
3049 value.AppendString ("false");
3050 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003051 else if (var_name == DisableASLRVarName())
3052 {
3053 if (m_disable_aslr)
3054 value.AppendString ("true");
3055 else
3056 value.AppendString ("false");
3057 }
Caroline Ticebd666012010-12-03 18:46:09 +00003058 else if (var_name == DisableSTDIOVarName())
3059 {
3060 if (m_disable_stdio)
3061 value.AppendString ("true");
3062 else
3063 value.AppendString ("false");
3064 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003065 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003066 {
3067 if (err)
3068 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3069 return false;
3070 }
3071 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003072}
3073
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003074const ConstString
3075ProcessInstanceSettings::CreateInstanceName ()
3076{
3077 static int instance_count = 1;
3078 StreamString sstr;
3079
3080 sstr.Printf ("process_%d", instance_count);
3081 ++instance_count;
3082
3083 const ConstString ret_val (sstr.GetData());
3084 return ret_val;
3085}
3086
3087const ConstString &
3088ProcessInstanceSettings::RunArgsVarName ()
3089{
3090 static ConstString run_args_var_name ("run-args");
3091
3092 return run_args_var_name;
3093}
3094
3095const ConstString &
3096ProcessInstanceSettings::EnvVarsVarName ()
3097{
3098 static ConstString env_vars_var_name ("env-vars");
3099
3100 return env_vars_var_name;
3101}
3102
3103const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003104ProcessInstanceSettings::InheritHostEnvVarName ()
3105{
3106 static ConstString g_name ("inherit-env");
3107
3108 return g_name;
3109}
3110
3111const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003112ProcessInstanceSettings::InputPathVarName ()
3113{
3114 static ConstString input_path_var_name ("input-path");
3115
3116 return input_path_var_name;
3117}
3118
3119const ConstString &
3120ProcessInstanceSettings::OutputPathVarName ()
3121{
Caroline Tice87097232010-09-07 18:35:40 +00003122 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003123
3124 return output_path_var_name;
3125}
3126
3127const ConstString &
3128ProcessInstanceSettings::ErrorPathVarName ()
3129{
Caroline Tice87097232010-09-07 18:35:40 +00003130 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003131
3132 return error_path_var_name;
3133}
3134
3135const ConstString &
3136ProcessInstanceSettings::PluginVarName ()
3137{
3138 static ConstString plugin_var_name ("plugin");
3139
3140 return plugin_var_name;
3141}
3142
3143
3144const ConstString &
3145ProcessInstanceSettings::DisableASLRVarName ()
3146{
3147 static ConstString disable_aslr_var_name ("disable-aslr");
3148
3149 return disable_aslr_var_name;
3150}
3151
Caroline Ticebd666012010-12-03 18:46:09 +00003152const ConstString &
3153ProcessInstanceSettings::DisableSTDIOVarName ()
3154{
3155 static ConstString disable_stdio_var_name ("disable-stdio");
3156
3157 return disable_stdio_var_name;
3158}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003159
3160//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003161// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003162//--------------------------------------------------
3163
3164SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003165Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003166{
3167 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3168 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3169};
3170
3171
3172lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003173Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003174{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003175 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3176 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3177 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003178};
3179
3180SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003181Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003182{
Greg Clayton638351a2010-12-04 00:10:17 +00003183 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3184 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3185 { "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." },
3186 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3187 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3188 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3189 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3190 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3191 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3192 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3193 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003194};
3195
3196
Jim Ingham7508e732010-08-09 23:31:02 +00003197