blob: c3b9dfbdd234b0776b335fcb9457c2d7ebba04b8 [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
410 if (log)
411 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
412 __FUNCTION__,
413 timeout,
414 StateAsCString(state));
415 return state;
416}
417
418Event *
419Process::PeekAtStateChangedEvents ()
420{
Greg Claytone005f2c2010-11-06 01:53:30 +0000421 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000422
423 if (log)
424 log->Printf ("Process::%s...", __FUNCTION__);
425
426 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000427 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
428 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000429 if (log)
430 {
431 if (event_ptr)
432 {
433 log->Printf ("Process::%s (event_ptr) => %s",
434 __FUNCTION__,
435 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
436 }
437 else
438 {
439 log->Printf ("Process::%s no events found",
440 __FUNCTION__);
441 }
442 }
443 return event_ptr;
444}
445
446StateType
447Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
448{
Greg Claytone005f2c2010-11-06 01:53:30 +0000449 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000450
451 if (log)
452 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
453
454 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000455 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
456 &m_private_state_broadcaster,
457 eBroadcastBitStateChanged,
458 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000459 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
460
461 // This is a bit of a hack, but when we wait here we could very well return
462 // to the command-line, and that could disable the log, which would render the
463 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000464 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000465 {
466 if (state == eStateInvalid)
467 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
468 else
469 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
470 }
Chris Lattner24943d22010-06-08 16:52:24 +0000471 return state;
472}
473
474bool
475Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
476{
Greg Claytone005f2c2010-11-06 01:53:30 +0000477 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000478
479 if (log)
480 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
481
482 if (control_only)
483 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
484 else
485 return m_private_state_listener.WaitForEvent(timeout, event_sp);
486}
487
488bool
489Process::IsRunning () const
490{
491 return StateIsRunningState (m_public_state.GetValue());
492}
493
494int
495Process::GetExitStatus ()
496{
497 if (m_public_state.GetValue() == eStateExited)
498 return m_exit_status;
499 return -1;
500}
501
Greg Clayton638351a2010-12-04 00:10:17 +0000502
503void
504Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
505{
506 if (m_inherit_host_env && !m_got_host_env)
507 {
508 m_got_host_env = true;
509 StringList host_env;
510 const size_t host_env_count = Host::GetEnvironment (host_env);
511 for (size_t idx=0; idx<host_env_count; idx++)
512 {
513 const char *env_entry = host_env.GetStringAtIndex (idx);
514 if (env_entry)
515 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000516 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000517 if (equal_pos)
518 {
519 std::string key (env_entry, equal_pos - env_entry);
520 std::string value (equal_pos + 1);
521 if (m_env_vars.find (key) == m_env_vars.end())
522 m_env_vars[key] = value;
523 }
524 }
525 }
526 }
527}
528
529
530size_t
531Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
532{
533 GetHostEnvironmentIfNeeded ();
534
535 dictionary::const_iterator pos, end = m_env_vars.end();
536 for (pos = m_env_vars.begin(); pos != end; ++pos)
537 {
538 std::string env_var_equal_value (pos->first);
539 env_var_equal_value.append(1, '=');
540 env_var_equal_value.append (pos->second);
541 env.AppendArgument (env_var_equal_value.c_str());
542 }
543 return env.GetArgumentCount();
544}
545
546
Chris Lattner24943d22010-06-08 16:52:24 +0000547const char *
548Process::GetExitDescription ()
549{
550 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
551 return m_exit_string.c_str();
552 return NULL;
553}
554
Greg Clayton72e1c782011-01-22 23:43:18 +0000555bool
Chris Lattner24943d22010-06-08 16:52:24 +0000556Process::SetExitStatus (int status, const char *cstr)
557{
Greg Clayton72e1c782011-01-22 23:43:18 +0000558 // We were already in the exited state
559 if (m_private_state.GetValue() == eStateExited)
560 return false;
561
562 m_exit_status = status;
563 if (cstr)
564 m_exit_string = cstr;
565 else
566 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000567
Greg Clayton72e1c782011-01-22 23:43:18 +0000568 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +0000569
Greg Clayton72e1c782011-01-22 23:43:18 +0000570 SetPrivateState (eStateExited);
571 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000572}
573
574// This static callback can be used to watch for local child processes on
575// the current host. The the child process exits, the process will be
576// found in the global target list (we want to be completely sure that the
577// lldb_private::Process doesn't go away before we can deliver the signal.
578bool
579Process::SetProcessExitStatus
580(
581 void *callback_baton,
582 lldb::pid_t pid,
583 int signo, // Zero for no signal
584 int exit_status // Exit value of process if signal is zero
585)
586{
587 if (signo == 0 || exit_status)
588 {
Greg Clayton63094e02010-06-23 01:19:29 +0000589 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000590 if (target_sp)
591 {
592 ProcessSP process_sp (target_sp->GetProcessSP());
593 if (process_sp)
594 {
595 const char *signal_cstr = NULL;
596 if (signo)
597 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
598
599 process_sp->SetExitStatus (exit_status, signal_cstr);
600 }
601 }
602 return true;
603 }
604 return false;
605}
606
607
608uint32_t
609Process::GetNextThreadIndexID ()
610{
611 return ++m_thread_index_id;
612}
613
614StateType
615Process::GetState()
616{
617 // If any other threads access this we will need a mutex for it
618 return m_public_state.GetValue ();
619}
620
621void
622Process::SetPublicState (StateType new_state)
623{
Greg Claytone005f2c2010-11-06 01:53:30 +0000624 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000625 if (log)
626 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
627 m_public_state.SetValue (new_state);
628}
629
630StateType
631Process::GetPrivateState ()
632{
633 return m_private_state.GetValue();
634}
635
636void
637Process::SetPrivateState (StateType new_state)
638{
Greg Claytone005f2c2010-11-06 01:53:30 +0000639 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner24943d22010-06-08 16:52:24 +0000640 bool state_changed = false;
641
642 if (log)
643 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
644
645 Mutex::Locker locker(m_private_state.GetMutex());
646
647 const StateType old_state = m_private_state.GetValueNoLock ();
648 state_changed = old_state != new_state;
649 if (state_changed)
650 {
651 m_private_state.SetValueNoLock (new_state);
652 if (StateIsStoppedState(new_state))
653 {
654 m_stop_id++;
Greg Claytonfd119992011-01-07 06:08:19 +0000655 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000656 if (log)
657 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
658 }
659 // Use our target to get a shared pointer to ourselves...
660 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
661 }
662 else
663 {
664 if (log)
665 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
666 }
667}
668
669
670uint32_t
671Process::GetStopID() const
672{
673 return m_stop_id;
674}
675
676addr_t
677Process::GetImageInfoAddress()
678{
679 return LLDB_INVALID_ADDRESS;
680}
681
Greg Clayton0baa3942010-11-04 01:54:29 +0000682//----------------------------------------------------------------------
683// LoadImage
684//
685// This function provides a default implementation that works for most
686// unix variants. Any Process subclasses that need to do shared library
687// loading differently should override LoadImage and UnloadImage and
688// do what is needed.
689//----------------------------------------------------------------------
690uint32_t
691Process::LoadImage (const FileSpec &image_spec, Error &error)
692{
693 DynamicLoader *loader = GetDynamicLoader();
694 if (loader)
695 {
696 error = loader->CanLoadImage();
697 if (error.Fail())
698 return LLDB_INVALID_IMAGE_TOKEN;
699 }
700
701 if (error.Success())
702 {
703 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
704 if (thread_sp == NULL)
705 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
706
707 if (thread_sp)
708 {
709 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
710
711 if (frame_sp)
712 {
713 ExecutionContext exe_ctx;
714 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000715 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000716 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000717 StreamString expr;
718 char path[PATH_MAX];
719 image_spec.GetPath(path, sizeof(path));
720 expr.Printf("dlopen (\"%s\", 2)", path);
721 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000722 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000723 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000724 if (result_valobj_sp->GetError().Success())
725 {
726 Scalar scalar;
727 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
728 {
729 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
730 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
731 {
732 uint32_t image_token = m_image_tokens.size();
733 m_image_tokens.push_back (image_ptr);
734 return image_token;
735 }
736 }
737 }
738 }
739 }
740 }
741 return LLDB_INVALID_IMAGE_TOKEN;
742}
743
744//----------------------------------------------------------------------
745// UnloadImage
746//
747// This function provides a default implementation that works for most
748// unix variants. Any Process subclasses that need to do shared library
749// loading differently should override LoadImage and UnloadImage and
750// do what is needed.
751//----------------------------------------------------------------------
752Error
753Process::UnloadImage (uint32_t image_token)
754{
755 Error error;
756 if (image_token < m_image_tokens.size())
757 {
758 const addr_t image_addr = m_image_tokens[image_token];
759 if (image_addr == LLDB_INVALID_ADDRESS)
760 {
761 error.SetErrorString("image already unloaded");
762 }
763 else
764 {
765 DynamicLoader *loader = GetDynamicLoader();
766 if (loader)
767 error = loader->CanLoadImage();
768
769 if (error.Success())
770 {
771 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
772 if (thread_sp == NULL)
773 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
774
775 if (thread_sp)
776 {
777 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
778
779 if (frame_sp)
780 {
781 ExecutionContext exe_ctx;
782 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000783 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000784 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000785 StreamString expr;
786 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
787 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000788 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000789 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000790 if (result_valobj_sp->GetError().Success())
791 {
792 Scalar scalar;
793 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
794 {
795 if (scalar.UInt(1))
796 {
797 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
798 }
799 else
800 {
801 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
802 }
803 }
804 }
805 else
806 {
807 error = result_valobj_sp->GetError();
808 }
809 }
810 }
811 }
812 }
813 }
814 else
815 {
816 error.SetErrorString("invalid image token");
817 }
818 return error;
819}
820
Chris Lattner24943d22010-06-08 16:52:24 +0000821DynamicLoader *
822Process::GetDynamicLoader()
823{
824 return NULL;
825}
826
827const ABI *
828Process::GetABI()
829{
830 ConstString& triple = m_target_triple;
831
832 if (triple.IsEmpty())
833 return NULL;
834
835 if (m_abi_sp.get() == NULL)
836 {
837 m_abi_sp.reset(ABI::FindPlugin(triple));
838 }
839
840 return m_abi_sp.get();
841}
842
Jim Ingham642036f2010-09-23 02:01:19 +0000843LanguageRuntime *
844Process::GetLanguageRuntime(lldb::LanguageType language)
845{
846 LanguageRuntimeCollection::iterator pos;
847 pos = m_language_runtimes.find (language);
848 if (pos == m_language_runtimes.end())
849 {
850 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
851
852 m_language_runtimes[language]
853 = runtime;
854 return runtime.get();
855 }
856 else
857 return (*pos).second.get();
858}
859
860CPPLanguageRuntime *
861Process::GetCPPLanguageRuntime ()
862{
863 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
864 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
865 return static_cast<CPPLanguageRuntime *> (runtime);
866 return NULL;
867}
868
869ObjCLanguageRuntime *
870Process::GetObjCLanguageRuntime ()
871{
872 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
873 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
874 return static_cast<ObjCLanguageRuntime *> (runtime);
875 return NULL;
876}
877
Chris Lattner24943d22010-06-08 16:52:24 +0000878BreakpointSiteList &
879Process::GetBreakpointSiteList()
880{
881 return m_breakpoint_site_list;
882}
883
884const BreakpointSiteList &
885Process::GetBreakpointSiteList() const
886{
887 return m_breakpoint_site_list;
888}
889
890
891void
892Process::DisableAllBreakpointSites ()
893{
894 m_breakpoint_site_list.SetEnabledForAll (false);
895}
896
897Error
898Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
899{
900 Error error (DisableBreakpointSiteByID (break_id));
901
902 if (error.Success())
903 m_breakpoint_site_list.Remove(break_id);
904
905 return error;
906}
907
908Error
909Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
910{
911 Error error;
912 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
913 if (bp_site_sp)
914 {
915 if (bp_site_sp->IsEnabled())
916 error = DisableBreakpoint (bp_site_sp.get());
917 }
918 else
919 {
920 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
921 }
922
923 return error;
924}
925
926Error
927Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
928{
929 Error error;
930 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
931 if (bp_site_sp)
932 {
933 if (!bp_site_sp->IsEnabled())
934 error = EnableBreakpoint (bp_site_sp.get());
935 }
936 else
937 {
938 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
939 }
940 return error;
941}
942
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000943lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000944Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
945{
Greg Claytoneea26402010-09-14 23:36:40 +0000946 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000947 if (load_addr != LLDB_INVALID_ADDRESS)
948 {
949 BreakpointSiteSP bp_site_sp;
950
951 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
952 // create a new breakpoint site and add it.
953
954 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
955
956 if (bp_site_sp)
957 {
958 bp_site_sp->AddOwner (owner);
959 owner->SetBreakpointSite (bp_site_sp);
960 return bp_site_sp->GetID();
961 }
962 else
963 {
964 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
965 if (bp_site_sp)
966 {
967 if (EnableBreakpoint (bp_site_sp.get()).Success())
968 {
969 owner->SetBreakpointSite (bp_site_sp);
970 return m_breakpoint_site_list.Add (bp_site_sp);
971 }
972 }
973 }
974 }
975 // We failed to enable the breakpoint
976 return LLDB_INVALID_BREAK_ID;
977
978}
979
980void
981Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
982{
983 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
984 if (num_owners == 0)
985 {
986 DisableBreakpoint(bp_site_sp.get());
987 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
988 }
989}
990
991
992size_t
993Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
994{
995 size_t bytes_removed = 0;
996 addr_t intersect_addr;
997 size_t intersect_size;
998 size_t opcode_offset;
999 size_t idx;
1000 BreakpointSiteSP bp;
1001
1002 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1003 {
1004 if (bp->GetType() == BreakpointSite::eSoftware)
1005 {
1006 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1007 {
1008 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1009 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1010 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1011 size_t buf_offset = intersect_addr - bp_addr;
1012 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1013 }
1014 }
1015 }
1016 return bytes_removed;
1017}
1018
1019
1020Error
1021Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1022{
1023 Error error;
1024 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001025 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001026 const addr_t bp_addr = bp_site->GetLoadAddress();
1027 if (log)
1028 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1029 if (bp_site->IsEnabled())
1030 {
1031 if (log)
1032 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1033 return error;
1034 }
1035
1036 if (bp_addr == LLDB_INVALID_ADDRESS)
1037 {
1038 error.SetErrorString("BreakpointSite contains an invalid load address.");
1039 return error;
1040 }
1041 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1042 // trap for the breakpoint site
1043 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1044
1045 if (bp_opcode_size == 0)
1046 {
1047 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1048 }
1049 else
1050 {
1051 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1052
1053 if (bp_opcode_bytes == NULL)
1054 {
1055 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1056 return error;
1057 }
1058
1059 // Save the original opcode by reading it
1060 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1061 {
1062 // Write a software breakpoint in place of the original opcode
1063 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1064 {
1065 uint8_t verify_bp_opcode_bytes[64];
1066 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1067 {
1068 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1069 {
1070 bp_site->SetEnabled(true);
1071 bp_site->SetType (BreakpointSite::eSoftware);
1072 if (log)
1073 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1074 bp_site->GetID(),
1075 (uint64_t)bp_addr);
1076 }
1077 else
1078 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1079 }
1080 else
1081 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1082 }
1083 else
1084 error.SetErrorString("Unable to write breakpoint trap to memory.");
1085 }
1086 else
1087 error.SetErrorString("Unable to read memory at breakpoint address.");
1088 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001089 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001090 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1091 bp_site->GetID(),
1092 (uint64_t)bp_addr,
1093 error.AsCString());
1094 return error;
1095}
1096
1097Error
1098Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1099{
1100 Error error;
1101 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001102 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001103 addr_t bp_addr = bp_site->GetLoadAddress();
1104 lldb::user_id_t breakID = bp_site->GetID();
1105 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001106 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001107
1108 if (bp_site->IsHardware())
1109 {
1110 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1111 }
1112 else if (bp_site->IsEnabled())
1113 {
1114 const size_t break_op_size = bp_site->GetByteSize();
1115 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1116 if (break_op_size > 0)
1117 {
1118 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001119 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001120 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001121 bool break_op_found = false;
1122
1123 // Read the breakpoint opcode
1124 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1125 {
1126 bool verify = false;
1127 // Make sure we have the a breakpoint opcode exists at this address
1128 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1129 {
1130 break_op_found = true;
1131 // We found a valid breakpoint opcode at this address, now restore
1132 // the saved opcode.
1133 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1134 {
1135 verify = true;
1136 }
1137 else
1138 error.SetErrorString("Memory write failed when restoring original opcode.");
1139 }
1140 else
1141 {
1142 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1143 // Set verify to true and so we can check if the original opcode has already been restored
1144 verify = true;
1145 }
1146
1147 if (verify)
1148 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001149 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001150 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001151 // Verify that our original opcode made it back to the inferior
1152 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1153 {
1154 // compare the memory we just read with the original opcode
1155 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1156 {
1157 // SUCCESS
1158 bp_site->SetEnabled(false);
1159 if (log)
1160 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1161 return error;
1162 }
1163 else
1164 {
1165 if (break_op_found)
1166 error.SetErrorString("Failed to restore original opcode.");
1167 }
1168 }
1169 else
1170 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1171 }
1172 }
1173 else
1174 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1175 }
1176 }
1177 else
1178 {
1179 if (log)
1180 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1181 return error;
1182 }
1183
1184 if (log)
1185 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1186 bp_site->GetID(),
1187 (uint64_t)bp_addr,
1188 error.AsCString());
1189 return error;
1190
1191}
1192
Greg Claytonfd119992011-01-07 06:08:19 +00001193// Comment out line below to disable memory caching
1194#define ENABLE_MEMORY_CACHING
1195// Uncomment to verify memory caching works after making changes to caching code
1196//#define VERIFY_MEMORY_READS
1197
1198#if defined (ENABLE_MEMORY_CACHING)
1199
1200#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001201
1202size_t
1203Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1204{
Greg Claytonfd119992011-01-07 06:08:19 +00001205 // Memory caching is enabled, with debug verification
1206 if (buf && size)
1207 {
1208 // Uncomment the line below to make sure memory caching is working.
1209 // I ran this through the test suite and got no assertions, so I am
1210 // pretty confident this is working well. If any changes are made to
1211 // memory caching, uncomment the line below and test your changes!
1212
1213 // Verify all memory reads by using the cache first, then redundantly
1214 // reading the same memory from the inferior and comparing to make sure
1215 // everything is exactly the same.
1216 std::string verify_buf (size, '\0');
1217 assert (verify_buf.size() == size);
1218 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1219 Error verify_error;
1220 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1221 assert (cache_bytes_read == verify_bytes_read);
1222 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1223 assert (verify_error.Success() == error.Success());
1224 return cache_bytes_read;
1225 }
1226 return 0;
1227}
1228
1229#else // #if defined (VERIFY_MEMORY_READS)
1230
1231size_t
1232Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1233{
1234 // Memory caching enabled, no verification
1235 return m_memory_cache.Read (this, addr, buf, size, error);
1236}
1237
1238#endif // #else for #if defined (VERIFY_MEMORY_READS)
1239
1240#else // #if defined (ENABLE_MEMORY_CACHING)
1241
1242size_t
1243Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1244{
1245 // Memory caching is disabled
1246 return ReadMemoryFromInferior (addr, buf, size, error);
1247}
1248
1249#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1250
1251
1252size_t
1253Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1254{
Chris Lattner24943d22010-06-08 16:52:24 +00001255 if (buf == NULL || size == 0)
1256 return 0;
1257
1258 size_t bytes_read = 0;
1259 uint8_t *bytes = (uint8_t *)buf;
1260
1261 while (bytes_read < size)
1262 {
1263 const size_t curr_size = size - bytes_read;
1264 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1265 bytes + bytes_read,
1266 curr_size,
1267 error);
1268 bytes_read += curr_bytes_read;
1269 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1270 break;
1271 }
1272
1273 // Replace any software breakpoint opcodes that fall into this range back
1274 // into "buf" before we return
1275 if (bytes_read > 0)
1276 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1277 return bytes_read;
1278}
1279
Greg Claytonf72fdee2010-12-16 20:01:20 +00001280uint64_t
1281Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1282{
1283 if (integer_byte_size > sizeof(uint64_t))
1284 {
1285 error.SetErrorString ("unsupported integer size");
1286 }
1287 else
1288 {
1289 uint8_t tmp[sizeof(uint64_t)];
1290 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1291 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1292 {
1293 uint32_t offset = 0;
1294 return data.GetMaxU64 (&offset, integer_byte_size);
1295 }
1296 }
1297 // Any plug-in that doesn't return success a memory read with the number
1298 // of bytes that were requested should be setting the error
1299 assert (error.Fail());
1300 return 0;
1301}
1302
Chris Lattner24943d22010-06-08 16:52:24 +00001303size_t
1304Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1305{
1306 size_t bytes_written = 0;
1307 const uint8_t *bytes = (const uint8_t *)buf;
1308
1309 while (bytes_written < size)
1310 {
1311 const size_t curr_size = size - bytes_written;
1312 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1313 bytes + bytes_written,
1314 curr_size,
1315 error);
1316 bytes_written += curr_bytes_written;
1317 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1318 break;
1319 }
1320 return bytes_written;
1321}
1322
1323size_t
1324Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1325{
Greg Claytonfd119992011-01-07 06:08:19 +00001326#if defined (ENABLE_MEMORY_CACHING)
1327 m_memory_cache.Flush (addr, size);
1328#endif
1329
Chris Lattner24943d22010-06-08 16:52:24 +00001330 if (buf == NULL || size == 0)
1331 return 0;
1332 // We need to write any data that would go where any current software traps
1333 // (enabled software breakpoints) any software traps (breakpoints) that we
1334 // may have placed in our tasks memory.
1335
1336 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1337 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1338
1339 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1340 return DoWriteMemory(addr, buf, size, error);
1341
1342 BreakpointSiteList::collection::const_iterator pos;
1343 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001344 addr_t intersect_addr = 0;
1345 size_t intersect_size = 0;
1346 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001347 const uint8_t *ubuf = (const uint8_t *)buf;
1348
1349 for (pos = iter; pos != end; ++pos)
1350 {
1351 BreakpointSiteSP bp;
1352 bp = pos->second;
1353
1354 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1355 assert(addr <= intersect_addr && intersect_addr < addr + size);
1356 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1357 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1358
1359 // Check for bytes before this breakpoint
1360 const addr_t curr_addr = addr + bytes_written;
1361 if (intersect_addr > curr_addr)
1362 {
1363 // There are some bytes before this breakpoint that we need to
1364 // just write to memory
1365 size_t curr_size = intersect_addr - curr_addr;
1366 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1367 ubuf + bytes_written,
1368 curr_size,
1369 error);
1370 bytes_written += curr_bytes_written;
1371 if (curr_bytes_written != curr_size)
1372 {
1373 // We weren't able to write all of the requested bytes, we
1374 // are done looping and will return the number of bytes that
1375 // we have written so far.
1376 break;
1377 }
1378 }
1379
1380 // Now write any bytes that would cover up any software breakpoints
1381 // directly into the breakpoint opcode buffer
1382 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1383 bytes_written += intersect_size;
1384 }
1385
1386 // Write any remaining bytes after the last breakpoint if we have any left
1387 if (bytes_written < size)
1388 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1389 ubuf + bytes_written,
1390 size - bytes_written,
1391 error);
1392
1393 return bytes_written;
1394}
1395
1396addr_t
1397Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1398{
1399 // Fixme: we should track the blocks we've allocated, and clean them up...
1400 // We could even do our own allocator here if that ends up being more efficient.
1401 return DoAllocateMemory (size, permissions, error);
1402}
1403
1404Error
1405Process::DeallocateMemory (addr_t ptr)
1406{
1407 return DoDeallocateMemory (ptr);
1408}
1409
1410
1411Error
1412Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1413{
1414 Error error;
1415 error.SetErrorString("watchpoints are not supported");
1416 return error;
1417}
1418
1419Error
1420Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1421{
1422 Error error;
1423 error.SetErrorString("watchpoints are not supported");
1424 return error;
1425}
1426
1427StateType
1428Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1429{
1430 StateType state;
1431 // Now wait for the process to launch and return control to us, and then
1432 // call DidLaunch:
1433 while (1)
1434 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001435 event_sp.reset();
1436 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1437
1438 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001439 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001440
1441 // If state is invalid, then we timed out
1442 if (state == eStateInvalid)
1443 break;
1444
1445 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001446 HandlePrivateEvent (event_sp);
1447 }
1448 return state;
1449}
1450
1451Error
1452Process::Launch
1453(
1454 char const *argv[],
1455 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001456 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001457 const char *stdin_path,
1458 const char *stdout_path,
1459 const char *stderr_path
1460)
1461{
1462 Error error;
1463 m_target_triple.Clear();
1464 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001465 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001466
1467 Module *exe_module = m_target.GetExecutableModule().get();
1468 if (exe_module)
1469 {
1470 char exec_file_path[PATH_MAX];
1471 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1472 if (exe_module->GetFileSpec().Exists())
1473 {
1474 error = WillLaunch (exe_module);
1475 if (error.Success())
1476 {
Greg Claytond8c62532010-10-07 04:19:01 +00001477 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001478 // The args coming in should not contain the application name, the
1479 // lldb_private::Process class will add this in case the executable
1480 // gets resolved to a different file than was given on the command
1481 // line (like when an applicaiton bundle is specified and will
1482 // resolve to the contained exectuable file, or the file given was
1483 // a symlink or other file system link that resolves to a different
1484 // file).
1485
1486 // Get the resolved exectuable path
1487
1488 // Make a new argument vector
1489 std::vector<const char *> exec_path_plus_argv;
1490 // Append the resolved executable path
1491 exec_path_plus_argv.push_back (exec_file_path);
1492
1493 // Push all args if there are any
1494 if (argv)
1495 {
1496 for (int i = 0; argv[i]; ++i)
1497 exec_path_plus_argv.push_back(argv[i]);
1498 }
1499
1500 // Push a NULL to terminate the args.
1501 exec_path_plus_argv.push_back(NULL);
1502
1503 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001504 error = DoLaunch (exe_module,
1505 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1506 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001507 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001508 stdin_path,
1509 stdout_path,
1510 stderr_path);
Chris Lattner24943d22010-06-08 16:52:24 +00001511
1512 if (error.Fail())
1513 {
1514 if (GetID() != LLDB_INVALID_PROCESS_ID)
1515 {
1516 SetID (LLDB_INVALID_PROCESS_ID);
1517 const char *error_string = error.AsCString();
1518 if (error_string == NULL)
1519 error_string = "launch failed";
1520 SetExitStatus (-1, error_string);
1521 }
1522 }
1523 else
1524 {
1525 EventSP event_sp;
1526 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1527
1528 if (state == eStateStopped || state == eStateCrashed)
1529 {
1530 DidLaunch ();
1531
1532 // This delays passing the stopped event to listeners till DidLaunch gets
1533 // a chance to complete...
1534 HandlePrivateEvent (event_sp);
1535 StartPrivateStateThread ();
1536 }
1537 else if (state == eStateExited)
1538 {
1539 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1540 // not likely to work, and return an invalid pid.
1541 HandlePrivateEvent (event_sp);
1542 }
1543 }
1544 }
1545 }
1546 else
1547 {
1548 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1549 }
1550 }
1551 return error;
1552}
1553
1554Error
1555Process::CompleteAttach ()
1556{
1557 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001558
1559 if (GetID() == LLDB_INVALID_PROCESS_ID)
1560 {
1561 error.SetErrorString("no process");
1562 }
1563
Chris Lattner24943d22010-06-08 16:52:24 +00001564 EventSP event_sp;
1565 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1566 if (state == eStateStopped || state == eStateCrashed)
1567 {
1568 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001569 // Figure out which one is the executable, and set that in our target:
1570 ModuleList &modules = GetTarget().GetImages();
1571
1572 size_t num_modules = modules.GetSize();
1573 for (int i = 0; i < num_modules; i++)
1574 {
1575 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1576 if (module_sp->IsExecutable())
1577 {
1578 ModuleSP exec_module = GetTarget().GetExecutableModule();
1579 if (!exec_module || exec_module != module_sp)
1580 {
1581
1582 GetTarget().SetExecutableModule (module_sp, false);
1583 }
1584 break;
1585 }
1586 }
Chris Lattner24943d22010-06-08 16:52:24 +00001587
1588 // This delays passing the stopped event to listeners till DidLaunch gets
1589 // a chance to complete...
1590 HandlePrivateEvent(event_sp);
1591 StartPrivateStateThread();
1592 }
1593 else
1594 {
1595 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1596 // not likely to work, and return an invalid pid.
1597 if (state == eStateExited)
1598 HandlePrivateEvent (event_sp);
1599 error.SetErrorStringWithFormat("invalid state after attach: %s",
1600 lldb_private::StateAsCString(state));
1601 }
1602 return error;
1603}
1604
1605Error
1606Process::Attach (lldb::pid_t attach_pid)
1607{
1608
1609 m_target_triple.Clear();
1610 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001611 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001612
Jim Ingham7508e732010-08-09 23:31:02 +00001613 // Find the process and its architecture. Make sure it matches the architecture
1614 // of the current Target, and if not adjust it.
1615
1616 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1617 if (attach_spec != GetTarget().GetArchitecture())
1618 {
1619 // Set the architecture on the target.
1620 GetTarget().SetArchitecture(attach_spec);
1621 }
1622
Greg Clayton54e7afa2010-07-09 20:39:50 +00001623 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001624 if (error.Success())
1625 {
Greg Claytond8c62532010-10-07 04:19:01 +00001626 SetPublicState (eStateAttaching);
1627
Greg Clayton54e7afa2010-07-09 20:39:50 +00001628 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001629 if (error.Success())
1630 {
1631 error = CompleteAttach();
1632 }
1633 else
1634 {
1635 if (GetID() != LLDB_INVALID_PROCESS_ID)
1636 {
1637 SetID (LLDB_INVALID_PROCESS_ID);
1638 const char *error_string = error.AsCString();
1639 if (error_string == NULL)
1640 error_string = "attach failed";
1641
1642 SetExitStatus(-1, error_string);
1643 }
1644 }
1645 }
1646 return error;
1647}
1648
1649Error
1650Process::Attach (const char *process_name, bool wait_for_launch)
1651{
1652 m_target_triple.Clear();
1653 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001654 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001655
1656 // Find the process and its architecture. Make sure it matches the architecture
1657 // of the current Target, and if not adjust it.
1658
Jim Inghamea294182010-08-17 21:54:19 +00001659 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001660 {
Jim Inghamea294182010-08-17 21:54:19 +00001661 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001662 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001663 {
1664 // Set the architecture on the target.
1665 GetTarget().SetArchitecture(attach_spec);
1666 }
Jim Ingham7508e732010-08-09 23:31:02 +00001667 }
Jim Inghamea294182010-08-17 21:54:19 +00001668
Greg Clayton54e7afa2010-07-09 20:39:50 +00001669 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001670 if (error.Success())
1671 {
Greg Claytond8c62532010-10-07 04:19:01 +00001672 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001673 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001674 if (error.Fail())
1675 {
1676 if (GetID() != LLDB_INVALID_PROCESS_ID)
1677 {
1678 SetID (LLDB_INVALID_PROCESS_ID);
1679 const char *error_string = error.AsCString();
1680 if (error_string == NULL)
1681 error_string = "attach failed";
1682
1683 SetExitStatus(-1, error_string);
1684 }
1685 }
1686 else
1687 {
1688 error = CompleteAttach();
1689 }
1690 }
1691 return error;
1692}
1693
1694Error
1695Process::Resume ()
1696{
Greg Claytone005f2c2010-11-06 01:53:30 +00001697 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001698 if (log)
1699 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1700
1701 Error error (WillResume());
1702 // Tell the process it is about to resume before the thread list
1703 if (error.Success())
1704 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001705 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001706 // can let all of our threads know that they are about to be
1707 // resumed. Threads will each be called with
1708 // Thread::WillResume(StateType) where StateType contains the state
1709 // that they are supposed to have when the process is resumed
1710 // (suspended/running/stepping). Threads should also check
1711 // their resume signal in lldb::Thread::GetResumeSignal()
1712 // to see if they are suppoed to start back up with a signal.
1713 if (m_thread_list.WillResume())
1714 {
1715 error = DoResume();
1716 if (error.Success())
1717 {
1718 DidResume();
1719 m_thread_list.DidResume();
1720 }
1721 }
1722 else
1723 {
1724 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1725 }
1726 }
1727 return error;
1728}
1729
1730Error
1731Process::Halt ()
1732{
1733 Error error (WillHalt());
1734
1735 if (error.Success())
1736 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001737
1738 bool caused_stop = false;
1739 EventSP event_sp;
1740
1741 // Pause our private state thread so we can ensure no one else eats
1742 // the stop event out from under us.
1743 PausePrivateStateThread();
1744
1745 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001746 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001747 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001748 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001749 // If "caused_stop" is true, then DoHalt stopped the process. If
1750 // "caused_stop" is false, the process was already stopped.
1751 // If the DoHalt caused the process to stop, then we want to catch
1752 // this event and set the interrupted bool to true before we pass
1753 // this along so clients know that the process was interrupted by
1754 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001755 if (caused_stop)
1756 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001757 // Wait for 2 seconds for the process to stop.
1758 TimeValue timeout_time;
1759 timeout_time = TimeValue::Now();
Greg Clayton72e1c782011-01-22 23:43:18 +00001760 timeout_time.OffsetWithSeconds(1);
Greg Clayton20d338f2010-11-18 05:57:03 +00001761 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1762
1763 if (state == eStateInvalid)
1764 {
1765 // We timeout out and didn't get a stop event...
1766 error.SetErrorString ("Halt timed out.");
1767 }
1768 else
1769 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001770 if (StateIsStoppedState (state))
1771 {
1772 // We caused the process to interrupt itself, so mark this
1773 // as such in the stop event so clients can tell an interrupted
1774 // process from a natural stop
1775 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1776 }
1777 else
1778 {
1779 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1780 if (log)
1781 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1782 error.SetErrorString ("Did not get stopped event after halt.");
1783 }
1784 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001785 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001786 DidHalt();
1787
Jim Ingham3ae449a2010-11-17 02:32:00 +00001788 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001789 // Resume our private state thread before we post the event (if any)
1790 ResumePrivateStateThread();
1791
1792 // Post any event we might have consumed. If all goes well, we will have
1793 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001794 // bool in the event. Post it to the private event queue and that will end up
1795 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001796 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001797 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001798
Chris Lattner24943d22010-06-08 16:52:24 +00001799 }
1800 return error;
1801}
1802
1803Error
1804Process::Detach ()
1805{
1806 Error error (WillDetach());
1807
1808 if (error.Success())
1809 {
1810 DisableAllBreakpointSites();
1811 error = DoDetach();
1812 if (error.Success())
1813 {
1814 DidDetach();
1815 StopPrivateStateThread();
1816 }
1817 }
1818 return error;
1819}
1820
1821Error
1822Process::Destroy ()
1823{
1824 Error error (WillDestroy());
1825 if (error.Success())
1826 {
1827 DisableAllBreakpointSites();
1828 error = DoDestroy();
1829 if (error.Success())
1830 {
1831 DidDestroy();
1832 StopPrivateStateThread();
1833 }
Caroline Tice861efb32010-11-16 05:07:41 +00001834 m_stdio_communication.StopReadThread();
1835 m_stdio_communication.Disconnect();
1836 if (m_process_input_reader && m_process_input_reader->IsActive())
1837 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1838 if (m_process_input_reader)
1839 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001840 }
1841 return error;
1842}
1843
1844Error
1845Process::Signal (int signal)
1846{
1847 Error error (WillSignal());
1848 if (error.Success())
1849 {
1850 error = DoSignal(signal);
1851 if (error.Success())
1852 DidSignal();
1853 }
1854 return error;
1855}
1856
1857UnixSignals &
1858Process::GetUnixSignals ()
1859{
1860 return m_unix_signals;
1861}
1862
1863Target &
1864Process::GetTarget ()
1865{
1866 return m_target;
1867}
1868
1869const Target &
1870Process::GetTarget () const
1871{
1872 return m_target;
1873}
1874
1875uint32_t
1876Process::GetAddressByteSize()
1877{
Greg Clayton20d338f2010-11-18 05:57:03 +00001878 if (m_addr_byte_size == 0)
1879 return m_target.GetArchitecture().GetAddressByteSize();
1880 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001881}
1882
1883bool
1884Process::ShouldBroadcastEvent (Event *event_ptr)
1885{
1886 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1887 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001888 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001889
1890 switch (state)
1891 {
1892 case eStateAttaching:
1893 case eStateLaunching:
1894 case eStateDetached:
1895 case eStateExited:
1896 case eStateUnloaded:
1897 // These events indicate changes in the state of the debugging session, always report them.
1898 return_value = true;
1899 break;
1900 case eStateInvalid:
1901 // We stopped for no apparent reason, don't report it.
1902 return_value = false;
1903 break;
1904 case eStateRunning:
1905 case eStateStepping:
1906 // If we've started the target running, we handle the cases where we
1907 // are already running and where there is a transition from stopped to
1908 // running differently.
1909 // running -> running: Automatically suppress extra running events
1910 // stopped -> running: Report except when there is one or more no votes
1911 // and no yes votes.
1912 SynchronouslyNotifyStateChanged (state);
1913 switch (m_public_state.GetValue())
1914 {
1915 case eStateRunning:
1916 case eStateStepping:
1917 // We always suppress multiple runnings with no PUBLIC stop in between.
1918 return_value = false;
1919 break;
1920 default:
1921 // TODO: make this work correctly. For now always report
1922 // run if we aren't running so we don't miss any runnning
1923 // events. If I run the lldb/test/thread/a.out file and
1924 // break at main.cpp:58, run and hit the breakpoints on
1925 // multiple threads, then somehow during the stepping over
1926 // of all breakpoints no run gets reported.
1927 return_value = true;
1928
1929 // This is a transition from stop to run.
1930 switch (m_thread_list.ShouldReportRun (event_ptr))
1931 {
1932 case eVoteYes:
1933 case eVoteNoOpinion:
1934 return_value = true;
1935 break;
1936 case eVoteNo:
1937 return_value = false;
1938 break;
1939 }
1940 break;
1941 }
1942 break;
1943 case eStateStopped:
1944 case eStateCrashed:
1945 case eStateSuspended:
1946 {
1947 // We've stopped. First see if we're going to restart the target.
1948 // If we are going to stop, then we always broadcast the event.
1949 // 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 +00001950 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001951 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001952 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001953 if (log)
1954 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001955 return true;
1956 }
1957 else
1958 {
Chris Lattner24943d22010-06-08 16:52:24 +00001959 RefreshStateAfterStop ();
1960
1961 if (m_thread_list.ShouldStop (event_ptr) == false)
1962 {
1963 switch (m_thread_list.ShouldReportStop (event_ptr))
1964 {
1965 case eVoteYes:
1966 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001967 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001968 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001969 case eVoteNo:
1970 return_value = false;
1971 break;
1972 }
1973
1974 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001975 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001976 Resume ();
1977 }
1978 else
1979 {
1980 return_value = true;
1981 SynchronouslyNotifyStateChanged (state);
1982 }
1983 }
1984 }
1985 }
1986
1987 if (log)
1988 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1989 return return_value;
1990}
1991
1992//------------------------------------------------------------------
1993// Thread Queries
1994//------------------------------------------------------------------
1995
1996ThreadList &
1997Process::GetThreadList ()
1998{
1999 return m_thread_list;
2000}
2001
2002const ThreadList &
2003Process::GetThreadList () const
2004{
2005 return m_thread_list;
2006}
2007
2008
2009bool
2010Process::StartPrivateStateThread ()
2011{
Greg Claytone005f2c2010-11-06 01:53:30 +00002012 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002013
2014 if (log)
2015 log->Printf ("Process::%s ( )", __FUNCTION__);
2016
2017 // Create a thread that watches our internal state and controls which
2018 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002019 char thread_name[1024];
2020 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2021 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002022 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2023}
2024
2025void
2026Process::PausePrivateStateThread ()
2027{
2028 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2029}
2030
2031void
2032Process::ResumePrivateStateThread ()
2033{
2034 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2035}
2036
2037void
2038Process::StopPrivateStateThread ()
2039{
2040 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2041}
2042
2043void
2044Process::ControlPrivateStateThread (uint32_t signal)
2045{
Greg Claytone005f2c2010-11-06 01:53:30 +00002046 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002047
2048 assert (signal == eBroadcastInternalStateControlStop ||
2049 signal == eBroadcastInternalStateControlPause ||
2050 signal == eBroadcastInternalStateControlResume);
2051
2052 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002053 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002054
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002055 // Signal the private state thread. First we should copy this is case the
2056 // thread starts exiting since the private state thread will NULL this out
2057 // when it exits
2058 const lldb::thread_t private_state_thread = m_private_state_thread;
2059 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner24943d22010-06-08 16:52:24 +00002060 {
2061 TimeValue timeout_time;
2062 bool timed_out;
2063
2064 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2065
2066 timeout_time = TimeValue::Now();
2067 timeout_time.OffsetWithSeconds(2);
2068 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2069 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2070
2071 if (signal == eBroadcastInternalStateControlStop)
2072 {
2073 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002074 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002075
2076 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002077 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002078 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002079 }
2080 }
2081}
2082
2083void
2084Process::HandlePrivateEvent (EventSP &event_sp)
2085{
Greg Claytone005f2c2010-11-06 01:53:30 +00002086 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002087 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2088 // See if we should broadcast this state to external clients?
2089 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2090 if (log)
2091 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2092
2093 if (should_broadcast)
2094 {
2095 if (log)
2096 {
2097 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2098 }
Caroline Tice861efb32010-11-16 05:07:41 +00002099 if (StateIsRunningState (internal_state))
2100 PushProcessInputReader ();
2101 else
2102 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002103 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2104 BroadcastEvent (event_sp);
2105 }
2106 else
2107 {
2108 if (log)
2109 {
2110 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2111 }
2112 }
2113}
2114
2115void *
2116Process::PrivateStateThread (void *arg)
2117{
2118 Process *proc = static_cast<Process*> (arg);
2119 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002120 return result;
2121}
2122
2123void *
2124Process::RunPrivateStateThread ()
2125{
2126 bool control_only = false;
2127 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2128
Greg Claytone005f2c2010-11-06 01:53:30 +00002129 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002130 if (log)
2131 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2132
2133 bool exit_now = false;
2134 while (!exit_now)
2135 {
2136 EventSP event_sp;
2137 WaitForEventsPrivate (NULL, event_sp, control_only);
2138 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2139 {
2140 switch (event_sp->GetType())
2141 {
2142 case eBroadcastInternalStateControlStop:
2143 exit_now = true;
2144 continue; // Go to next loop iteration so we exit without
2145 break; // doing any internal state managment below
2146
2147 case eBroadcastInternalStateControlPause:
2148 control_only = true;
2149 break;
2150
2151 case eBroadcastInternalStateControlResume:
2152 control_only = false;
2153 break;
2154 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002155
Jim Ingham3ae449a2010-11-17 02:32:00 +00002156 if (log)
2157 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2158
Chris Lattner24943d22010-06-08 16:52:24 +00002159 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002160 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002161 }
2162
2163
2164 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2165
2166 if (internal_state != eStateInvalid)
2167 {
2168 HandlePrivateEvent (event_sp);
2169 }
2170
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002171 if (internal_state == eStateInvalid ||
2172 internal_state == eStateExited ||
2173 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002174 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002175 if (log)
2176 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2177
Chris Lattner24943d22010-06-08 16:52:24 +00002178 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002179 }
Chris Lattner24943d22010-06-08 16:52:24 +00002180 }
2181
Caroline Tice926060e2010-10-29 21:48:37 +00002182 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002183 if (log)
2184 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2185
Greg Claytona4881d02011-01-22 07:12:45 +00002186 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2187 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002188 return NULL;
2189}
2190
Chris Lattner24943d22010-06-08 16:52:24 +00002191//------------------------------------------------------------------
2192// Process Event Data
2193//------------------------------------------------------------------
2194
2195Process::ProcessEventData::ProcessEventData () :
2196 EventData (),
2197 m_process_sp (),
2198 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002199 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002200 m_update_state (false),
2201 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002202{
2203}
2204
2205Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2206 EventData (),
2207 m_process_sp (process_sp),
2208 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002209 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002210 m_update_state (false),
2211 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002212{
2213}
2214
2215Process::ProcessEventData::~ProcessEventData()
2216{
2217}
2218
2219const ConstString &
2220Process::ProcessEventData::GetFlavorString ()
2221{
2222 static ConstString g_flavor ("Process::ProcessEventData");
2223 return g_flavor;
2224}
2225
2226const ConstString &
2227Process::ProcessEventData::GetFlavor () const
2228{
2229 return ProcessEventData::GetFlavorString ();
2230}
2231
Chris Lattner24943d22010-06-08 16:52:24 +00002232void
2233Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2234{
2235 // This function gets called twice for each event, once when the event gets pulled
2236 // off of the private process event queue, and once when it gets pulled off of
2237 // the public event queue. m_update_state is used to distinguish these
2238 // two cases; it is false when we're just pulling it off for private handling,
2239 // and we don't want to do the breakpoint command handling then.
2240
2241 if (!m_update_state)
2242 return;
2243
2244 m_process_sp->SetPublicState (m_state);
2245
2246 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2247 if (m_state == eStateStopped && ! m_restarted)
2248 {
2249 int num_threads = m_process_sp->GetThreadList().GetSize();
2250 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002251
Chris Lattner24943d22010-06-08 16:52:24 +00002252 for (idx = 0; idx < num_threads; ++idx)
2253 {
2254 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2255
Jim Ingham6297a3a2010-10-20 00:39:53 +00002256 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2257 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002258 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002259 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002260 }
2261 }
Greg Clayton643ee732010-08-04 01:40:35 +00002262
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002263 // The stop action might restart the target. If it does, then we want to mark that in the
2264 // event so that whoever is receiving it will know to wait for the running event and reflect
2265 // that state appropriately.
2266
Chris Lattner24943d22010-06-08 16:52:24 +00002267 if (m_process_sp->GetPrivateState() == eStateRunning)
2268 SetRestarted(true);
2269 }
2270}
2271
2272void
2273Process::ProcessEventData::Dump (Stream *s) const
2274{
2275 if (m_process_sp)
2276 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2277
2278 s->Printf("state = %s", StateAsCString(GetState()));;
2279}
2280
2281const Process::ProcessEventData *
2282Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2283{
2284 if (event_ptr)
2285 {
2286 const EventData *event_data = event_ptr->GetData();
2287 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2288 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2289 }
2290 return NULL;
2291}
2292
2293ProcessSP
2294Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2295{
2296 ProcessSP process_sp;
2297 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2298 if (data)
2299 process_sp = data->GetProcessSP();
2300 return process_sp;
2301}
2302
2303StateType
2304Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2305{
2306 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2307 if (data == NULL)
2308 return eStateInvalid;
2309 else
2310 return data->GetState();
2311}
2312
2313bool
2314Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2315{
2316 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2317 if (data == NULL)
2318 return false;
2319 else
2320 return data->GetRestarted();
2321}
2322
2323void
2324Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2325{
2326 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2327 if (data != NULL)
2328 data->SetRestarted(new_value);
2329}
2330
2331bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002332Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2333{
2334 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2335 if (data == NULL)
2336 return false;
2337 else
2338 return data->GetInterrupted ();
2339}
2340
2341void
2342Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2343{
2344 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2345 if (data != NULL)
2346 data->SetInterrupted(new_value);
2347}
2348
2349bool
Chris Lattner24943d22010-06-08 16:52:24 +00002350Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2351{
2352 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2353 if (data)
2354 {
2355 data->SetUpdateStateOnRemoval();
2356 return true;
2357 }
2358 return false;
2359}
2360
Chris Lattner24943d22010-06-08 16:52:24 +00002361Target *
2362Process::CalculateTarget ()
2363{
2364 return &m_target;
2365}
2366
2367Process *
2368Process::CalculateProcess ()
2369{
2370 return this;
2371}
2372
2373Thread *
2374Process::CalculateThread ()
2375{
2376 return NULL;
2377}
2378
2379StackFrame *
2380Process::CalculateStackFrame ()
2381{
2382 return NULL;
2383}
2384
2385void
Greg Claytona830adb2010-10-04 01:05:56 +00002386Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002387{
2388 exe_ctx.target = &m_target;
2389 exe_ctx.process = this;
2390 exe_ctx.thread = NULL;
2391 exe_ctx.frame = NULL;
2392}
2393
2394lldb::ProcessSP
2395Process::GetSP ()
2396{
2397 return GetTarget().GetProcessSP();
2398}
2399
Jim Ingham7508e732010-08-09 23:31:02 +00002400uint32_t
2401Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2402{
2403 return 0;
2404}
2405
2406ArchSpec
2407Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2408{
2409 return Host::GetArchSpecForExistingProcess (pid);
2410}
2411
2412ArchSpec
2413Process::GetArchSpecForExistingProcess (const char *process_name)
2414{
2415 return Host::GetArchSpecForExistingProcess (process_name);
2416}
2417
Caroline Tice861efb32010-11-16 05:07:41 +00002418void
2419Process::AppendSTDOUT (const char * s, size_t len)
2420{
Greg Clayton20d338f2010-11-18 05:57:03 +00002421 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002422 m_stdout_data.append (s, len);
2423
Greg Claytonb3781332010-12-05 19:16:56 +00002424 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002425}
2426
2427void
2428Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2429{
2430 Process *process = (Process *) baton;
2431 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2432}
2433
2434size_t
2435Process::ProcessInputReaderCallback (void *baton,
2436 InputReader &reader,
2437 lldb::InputReaderAction notification,
2438 const char *bytes,
2439 size_t bytes_len)
2440{
2441 Process *process = (Process *) baton;
2442
2443 switch (notification)
2444 {
2445 case eInputReaderActivate:
2446 break;
2447
2448 case eInputReaderDeactivate:
2449 break;
2450
2451 case eInputReaderReactivate:
2452 break;
2453
2454 case eInputReaderGotToken:
2455 {
2456 Error error;
2457 process->PutSTDIN (bytes, bytes_len, error);
2458 }
2459 break;
2460
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002461 case eInputReaderInterrupt:
2462 process->Halt ();
2463 break;
2464
2465 case eInputReaderEndOfFile:
2466 process->AppendSTDOUT ("^D", 2);
2467 break;
2468
Caroline Tice861efb32010-11-16 05:07:41 +00002469 case eInputReaderDone:
2470 break;
2471
2472 }
2473
2474 return bytes_len;
2475}
2476
2477void
2478Process::ResetProcessInputReader ()
2479{
2480 m_process_input_reader.reset();
2481}
2482
2483void
2484Process::SetUpProcessInputReader (int file_descriptor)
2485{
2486 // First set up the Read Thread for reading/handling process I/O
2487
2488 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2489
2490 if (conn_ap.get())
2491 {
2492 m_stdio_communication.SetConnection (conn_ap.release());
2493 if (m_stdio_communication.IsConnected())
2494 {
2495 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2496 m_stdio_communication.StartReadThread();
2497
2498 // Now read thread is set up, set up input reader.
2499
2500 if (!m_process_input_reader.get())
2501 {
2502 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2503 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2504 this,
2505 eInputReaderGranularityByte,
2506 NULL,
2507 NULL,
2508 false));
2509
2510 if (err.Fail())
2511 m_process_input_reader.reset();
2512 }
2513 }
2514 }
2515}
2516
2517void
2518Process::PushProcessInputReader ()
2519{
2520 if (m_process_input_reader && !m_process_input_reader->IsActive())
2521 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2522}
2523
2524void
2525Process::PopProcessInputReader ()
2526{
2527 if (m_process_input_reader && m_process_input_reader->IsActive())
2528 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2529}
2530
Greg Clayton990de7b2010-11-18 23:32:35 +00002531
2532void
2533Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002534{
Greg Clayton990de7b2010-11-18 23:32:35 +00002535 UserSettingsControllerSP &usc = GetSettingsController();
2536 usc.reset (new SettingsController);
2537 UserSettingsController::InitializeSettingsController (usc,
2538 SettingsController::global_settings_table,
2539 SettingsController::instance_settings_table);
2540}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002541
Greg Clayton990de7b2010-11-18 23:32:35 +00002542void
2543Process::Terminate ()
2544{
2545 UserSettingsControllerSP &usc = GetSettingsController();
2546 UserSettingsController::FinalizeSettingsController (usc);
2547 usc.reset();
2548}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002549
Greg Clayton990de7b2010-11-18 23:32:35 +00002550UserSettingsControllerSP &
2551Process::GetSettingsController ()
2552{
2553 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002554 return g_settings_controller;
2555}
2556
Caroline Tice1ebef442010-09-27 00:30:10 +00002557void
2558Process::UpdateInstanceName ()
2559{
2560 ModuleSP module_sp = GetTarget().GetExecutableModule();
2561 if (module_sp)
2562 {
2563 StreamString sstr;
2564 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2565
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002566 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002567 sstr.GetData());
2568 }
2569}
2570
Greg Clayton427f2902010-12-14 02:59:59 +00002571ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002572Process::RunThreadPlan (ExecutionContext &exe_ctx,
2573 lldb::ThreadPlanSP &thread_plan_sp,
2574 bool stop_others,
2575 bool try_all_threads,
2576 bool discard_on_error,
2577 uint32_t single_thread_timeout_usec,
2578 Stream &errors)
2579{
2580 ExecutionResults return_value = eExecutionSetupError;
2581
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002582 if (thread_plan_sp.get() == NULL)
2583 {
2584 errors.Printf("RunThreadPlan called with empty thread plan.");
2585 return lldb::eExecutionSetupError;
2586 }
2587
Jim Ingham360f53f2010-11-30 02:22:11 +00002588 // Save this value for restoration of the execution context after we run
2589 uint32_t tid = exe_ctx.thread->GetIndexID();
2590
2591 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2592 // so we should arrange to reset them as well.
2593
2594 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2595 lldb::StackFrameSP selected_frame_sp;
2596
2597 uint32_t selected_tid;
2598 if (selected_thread_sp != NULL)
2599 {
2600 selected_tid = selected_thread_sp->GetIndexID();
2601 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2602 }
2603 else
2604 {
2605 selected_tid = LLDB_INVALID_THREAD_ID;
2606 }
2607
2608 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2609
2610 Listener listener("ClangFunction temporary listener");
2611 exe_ctx.process->HijackProcessEvents(&listener);
2612
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002613 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2614 if (log)
2615 {
2616 StreamString s;
2617 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
2618 log->Printf ("Resuming thread 0x%x to run thread plan \"%s\".", tid, s.GetData());
2619 }
2620
Jim Ingham360f53f2010-11-30 02:22:11 +00002621 Error resume_error = exe_ctx.process->Resume ();
2622 if (!resume_error.Success())
2623 {
2624 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2625 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002626 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002627 }
2628
2629 // We need to call the function synchronously, so spin waiting for it to return.
2630 // If we get interrupted while executing, we're going to lose our context, and
2631 // won't be able to gather the result at this point.
2632 // We set the timeout AFTER the resume, since the resume takes some time and we
2633 // don't want to charge that to the timeout.
2634
2635 TimeValue* timeout_ptr = NULL;
2636 TimeValue real_timeout;
2637
2638 if (single_thread_timeout_usec != 0)
2639 {
2640 real_timeout = TimeValue::Now();
2641 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2642 timeout_ptr = &real_timeout;
2643 }
2644
Jim Ingham360f53f2010-11-30 02:22:11 +00002645 while (1)
2646 {
2647 lldb::EventSP event_sp;
2648 lldb::StateType stop_state = lldb::eStateInvalid;
2649 // Now wait for the process to stop again:
2650 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2651
2652 if (!got_event)
2653 {
2654 // Right now this is the only way to tell we've timed out...
2655 // We should interrupt the process here...
2656 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002657 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002658 if (try_all_threads)
2659 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2660 single_thread_timeout_usec);
2661 else
2662 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2663 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002664 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002665
Jim Inghamc556b462011-01-22 01:30:53 +00002666 Error halt_error = exe_ctx.process->Halt();
2667
2668 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002669 {
2670 timeout_ptr = NULL;
2671 if (log)
2672 log->Printf ("Halt succeeded.");
2673
2674 // Between the time that we got the timeout and the time we halted, but target
2675 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2676 // timeout to
2677 got_event = listener.WaitForEvent(NULL, event_sp);
2678
2679 if (got_event)
2680 {
2681 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2682 if (log)
2683 {
2684 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2685 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2686 log->Printf (" Event was the Halt interruption event.");
2687 }
2688
2689 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2690 {
2691 if (log)
2692 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002693 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002694 break;
2695 }
2696
2697 if (try_all_threads
2698 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2699 {
2700
2701 thread_plan_sp->SetStopOthers (false);
2702 if (log)
2703 log->Printf ("About to resume.");
2704
2705 exe_ctx.process->Resume();
2706 continue;
2707 }
2708 else
2709 {
2710 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002711 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002712 }
2713 }
2714 }
Jim Inghamc556b462011-01-22 01:30:53 +00002715 else
2716 {
2717
2718 if (log)
2719 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2720 halt_error.AsCString());
2721
2722 if (single_thread_timeout_usec != 0)
2723 {
2724 real_timeout = TimeValue::Now();
2725 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2726 timeout_ptr = &real_timeout;
2727 }
2728 continue;
2729 }
2730
Jim Ingham360f53f2010-11-30 02:22:11 +00002731 }
2732
2733 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2734 if (log)
2735 log->Printf("Got event: %s.", StateAsCString(stop_state));
2736
2737 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2738 continue;
2739
2740 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2741 {
Greg Clayton427f2902010-12-14 02:59:59 +00002742 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002743 break;
2744 }
2745 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2746 {
Greg Clayton427f2902010-12-14 02:59:59 +00002747 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002748 break;
2749 }
2750 else
2751 {
2752 if (log)
2753 {
2754 StreamString s;
Jim Inghamc556b462011-01-22 01:30:53 +00002755 if (event_sp)
2756 event_sp->Dump (&s);
2757 else
2758 {
2759 log->Printf ("Stop event that interrupted us is NULL.");
2760 }
2761
Jim Ingham360f53f2010-11-30 02:22:11 +00002762 StreamString ts;
2763
2764 const char *event_explanation;
2765
2766 do
2767 {
2768 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2769
2770 if (!event_data)
2771 {
2772 event_explanation = "<no event data>";
2773 break;
2774 }
2775
2776 Process *process = event_data->GetProcessSP().get();
2777
2778 if (!process)
2779 {
2780 event_explanation = "<no process>";
2781 break;
2782 }
2783
2784 ThreadList &thread_list = process->GetThreadList();
2785
2786 uint32_t num_threads = thread_list.GetSize();
2787 uint32_t thread_index;
2788
2789 ts.Printf("<%u threads> ", num_threads);
2790
2791 for (thread_index = 0;
2792 thread_index < num_threads;
2793 ++thread_index)
2794 {
2795 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2796
2797 if (!thread)
2798 {
2799 ts.Printf("<?> ");
2800 continue;
2801 }
2802
Jim Inghamc556b462011-01-22 01:30:53 +00002803 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002804 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002805
2806 if (register_context)
2807 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2808 else
2809 ts.Printf("[ip unknown] ");
2810
2811 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2812 if (stop_info_sp)
2813 {
2814 const char *stop_desc = stop_info_sp->GetDescription();
2815 if (stop_desc)
2816 ts.PutCString (stop_desc);
2817 }
2818 ts.Printf(">");
2819 }
2820
2821 event_explanation = ts.GetData();
2822 } while (0);
2823
Jim Inghamc556b462011-01-22 01:30:53 +00002824 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2825 if (!GetThreadList().ShouldStop(event_sp.get()))
2826 {
2827 if (log)
2828 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2829 s.GetData(), event_explanation);
2830 if (single_thread_timeout_usec != 0)
2831 {
2832 real_timeout = TimeValue::Now();
2833 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2834 timeout_ptr = &real_timeout;
2835 }
2836
2837 continue;
2838 }
2839 else
2840 {
2841 if (log)
2842 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2843 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002844 }
2845
2846 if (discard_on_error && thread_plan_sp)
2847 {
2848 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2849 }
Greg Clayton427f2902010-12-14 02:59:59 +00002850 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002851 break;
2852 }
2853 }
2854
2855 if (exe_ctx.process)
2856 exe_ctx.process->RestoreProcessEvents ();
2857
2858 // Thread we ran the function in may have gone away because we ran the target
2859 // Check that it's still there.
2860 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2861 if (exe_ctx.thread)
2862 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2863
2864 // Also restore the current process'es selected frame & thread, since this function calling may
2865 // be done behind the user's back.
2866
2867 if (selected_tid != LLDB_INVALID_THREAD_ID)
2868 {
2869 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2870 {
2871 // We were able to restore the selected thread, now restore the frame:
2872 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2873 }
2874 }
2875
2876 return return_value;
2877}
2878
2879const char *
2880Process::ExecutionResultAsCString (ExecutionResults result)
2881{
2882 const char *result_name;
2883
2884 switch (result)
2885 {
Greg Clayton427f2902010-12-14 02:59:59 +00002886 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002887 result_name = "eExecutionCompleted";
2888 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002889 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002890 result_name = "eExecutionDiscarded";
2891 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002892 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002893 result_name = "eExecutionInterrupted";
2894 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002895 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002896 result_name = "eExecutionSetupError";
2897 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002898 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002899 result_name = "eExecutionTimedOut";
2900 break;
2901 }
2902 return result_name;
2903}
2904
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002905//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002906// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002907//--------------------------------------------------------------
2908
Greg Claytond0a5a232010-09-19 02:33:57 +00002909Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002910 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002911{
Greg Clayton638351a2010-12-04 00:10:17 +00002912 m_default_settings.reset (new ProcessInstanceSettings (*this,
2913 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002914 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002915}
2916
Greg Claytond0a5a232010-09-19 02:33:57 +00002917Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002918{
2919}
2920
2921lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002922Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002923{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002924 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2925 false,
2926 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002927 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2928 return new_settings_sp;
2929}
2930
2931//--------------------------------------------------------------
2932// class ProcessInstanceSettings
2933//--------------------------------------------------------------
2934
Greg Clayton638351a2010-12-04 00:10:17 +00002935ProcessInstanceSettings::ProcessInstanceSettings
2936(
2937 UserSettingsController &owner,
2938 bool live_instance,
2939 const char *name
2940) :
2941 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002942 m_run_args (),
2943 m_env_vars (),
2944 m_input_path (),
2945 m_output_path (),
2946 m_error_path (),
2947 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002948 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002949 m_disable_stdio (false),
2950 m_inherit_host_env (true),
2951 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002952{
Caroline Tice396704b2010-09-09 18:26:37 +00002953 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2954 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2955 // 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 +00002956 // This is true for CreateInstanceName() too.
2957
2958 if (GetInstanceName () == InstanceSettings::InvalidName())
2959 {
2960 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2961 m_owner.RegisterInstanceSettings (this);
2962 }
Caroline Tice396704b2010-09-09 18:26:37 +00002963
2964 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002965 {
2966 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2967 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002968 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002969 }
2970}
2971
2972ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002973 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002974 m_run_args (rhs.m_run_args),
2975 m_env_vars (rhs.m_env_vars),
2976 m_input_path (rhs.m_input_path),
2977 m_output_path (rhs.m_output_path),
2978 m_error_path (rhs.m_error_path),
2979 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00002980 m_disable_aslr (rhs.m_disable_aslr),
2981 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002982{
2983 if (m_instance_name != InstanceSettings::GetDefaultName())
2984 {
2985 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2986 CopyInstanceSettings (pending_settings,false);
2987 m_owner.RemovePendingSettings (m_instance_name);
2988 }
2989}
2990
2991ProcessInstanceSettings::~ProcessInstanceSettings ()
2992{
2993}
2994
2995ProcessInstanceSettings&
2996ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2997{
2998 if (this != &rhs)
2999 {
3000 m_run_args = rhs.m_run_args;
3001 m_env_vars = rhs.m_env_vars;
3002 m_input_path = rhs.m_input_path;
3003 m_output_path = rhs.m_output_path;
3004 m_error_path = rhs.m_error_path;
3005 m_plugin = rhs.m_plugin;
3006 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003007 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003008 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003009 }
3010
3011 return *this;
3012}
3013
3014
3015void
3016ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3017 const char *index_value,
3018 const char *value,
3019 const ConstString &instance_name,
3020 const SettingEntry &entry,
3021 lldb::VarSetOperationType op,
3022 Error &err,
3023 bool pending)
3024{
3025 if (var_name == RunArgsVarName())
3026 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3027 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003028 {
3029 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003030 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003031 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003032 else if (var_name == InputPathVarName())
3033 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3034 else if (var_name == OutputPathVarName())
3035 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3036 else if (var_name == ErrorPathVarName())
3037 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3038 else if (var_name == PluginVarName())
3039 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003040 else if (var_name == InheritHostEnvVarName())
3041 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003042 else if (var_name == DisableASLRVarName())
3043 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003044 else if (var_name == DisableSTDIOVarName ())
3045 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003046}
3047
3048void
3049ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3050 bool pending)
3051{
3052 if (new_settings.get() == NULL)
3053 return;
3054
3055 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3056
3057 m_run_args = new_process_settings->m_run_args;
3058 m_env_vars = new_process_settings->m_env_vars;
3059 m_input_path = new_process_settings->m_input_path;
3060 m_output_path = new_process_settings->m_output_path;
3061 m_error_path = new_process_settings->m_error_path;
3062 m_plugin = new_process_settings->m_plugin;
3063 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003064 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003065}
3066
Caroline Ticebcb5b452010-09-20 21:37:42 +00003067bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003068ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3069 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003070 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003071 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003072{
3073 if (var_name == RunArgsVarName())
3074 {
3075 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003076 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003077 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3078 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003079 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003080 }
3081 else if (var_name == EnvVarsVarName())
3082 {
Greg Clayton638351a2010-12-04 00:10:17 +00003083 GetHostEnvironmentIfNeeded ();
3084
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003085 if (m_env_vars.size() > 0)
3086 {
3087 std::map<std::string, std::string>::iterator pos;
3088 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3089 {
3090 StreamString value_str;
3091 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3092 value.AppendString (value_str.GetData());
3093 }
3094 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003095 }
3096 else if (var_name == InputPathVarName())
3097 {
3098 value.AppendString (m_input_path.c_str());
3099 }
3100 else if (var_name == OutputPathVarName())
3101 {
3102 value.AppendString (m_output_path.c_str());
3103 }
3104 else if (var_name == ErrorPathVarName())
3105 {
3106 value.AppendString (m_error_path.c_str());
3107 }
3108 else if (var_name == PluginVarName())
3109 {
3110 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3111 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003112 else if (var_name == InheritHostEnvVarName())
3113 {
3114 if (m_inherit_host_env)
3115 value.AppendString ("true");
3116 else
3117 value.AppendString ("false");
3118 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003119 else if (var_name == DisableASLRVarName())
3120 {
3121 if (m_disable_aslr)
3122 value.AppendString ("true");
3123 else
3124 value.AppendString ("false");
3125 }
Caroline Ticebd666012010-12-03 18:46:09 +00003126 else if (var_name == DisableSTDIOVarName())
3127 {
3128 if (m_disable_stdio)
3129 value.AppendString ("true");
3130 else
3131 value.AppendString ("false");
3132 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003133 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003134 {
3135 if (err)
3136 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3137 return false;
3138 }
3139 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003140}
3141
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003142const ConstString
3143ProcessInstanceSettings::CreateInstanceName ()
3144{
3145 static int instance_count = 1;
3146 StreamString sstr;
3147
3148 sstr.Printf ("process_%d", instance_count);
3149 ++instance_count;
3150
3151 const ConstString ret_val (sstr.GetData());
3152 return ret_val;
3153}
3154
3155const ConstString &
3156ProcessInstanceSettings::RunArgsVarName ()
3157{
3158 static ConstString run_args_var_name ("run-args");
3159
3160 return run_args_var_name;
3161}
3162
3163const ConstString &
3164ProcessInstanceSettings::EnvVarsVarName ()
3165{
3166 static ConstString env_vars_var_name ("env-vars");
3167
3168 return env_vars_var_name;
3169}
3170
3171const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003172ProcessInstanceSettings::InheritHostEnvVarName ()
3173{
3174 static ConstString g_name ("inherit-env");
3175
3176 return g_name;
3177}
3178
3179const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003180ProcessInstanceSettings::InputPathVarName ()
3181{
3182 static ConstString input_path_var_name ("input-path");
3183
3184 return input_path_var_name;
3185}
3186
3187const ConstString &
3188ProcessInstanceSettings::OutputPathVarName ()
3189{
Caroline Tice87097232010-09-07 18:35:40 +00003190 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003191
3192 return output_path_var_name;
3193}
3194
3195const ConstString &
3196ProcessInstanceSettings::ErrorPathVarName ()
3197{
Caroline Tice87097232010-09-07 18:35:40 +00003198 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003199
3200 return error_path_var_name;
3201}
3202
3203const ConstString &
3204ProcessInstanceSettings::PluginVarName ()
3205{
3206 static ConstString plugin_var_name ("plugin");
3207
3208 return plugin_var_name;
3209}
3210
3211
3212const ConstString &
3213ProcessInstanceSettings::DisableASLRVarName ()
3214{
3215 static ConstString disable_aslr_var_name ("disable-aslr");
3216
3217 return disable_aslr_var_name;
3218}
3219
Caroline Ticebd666012010-12-03 18:46:09 +00003220const ConstString &
3221ProcessInstanceSettings::DisableSTDIOVarName ()
3222{
3223 static ConstString disable_stdio_var_name ("disable-stdio");
3224
3225 return disable_stdio_var_name;
3226}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003227
3228//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003229// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003230//--------------------------------------------------
3231
3232SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003233Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003234{
3235 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3236 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3237};
3238
3239
3240lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003241Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003242{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003243 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3244 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3245 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003246};
3247
3248SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003249Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003250{
Greg Clayton638351a2010-12-04 00:10:17 +00003251 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3252 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3253 { "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." },
3254 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3255 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3256 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3257 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3258 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3259 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3260 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3261 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003262};
3263
3264
Jim Ingham7508e732010-08-09 23:31:02 +00003265