blob: f0b79b99ff0466f5a37f37a96c31edc6e9e2e19b [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,
Greg Claytonde915be2011-01-23 05:56:20 +00001459 const char *stderr_path,
1460 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001461)
1462{
1463 Error error;
1464 m_target_triple.Clear();
1465 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001466 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001467
1468 Module *exe_module = m_target.GetExecutableModule().get();
1469 if (exe_module)
1470 {
1471 char exec_file_path[PATH_MAX];
1472 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1473 if (exe_module->GetFileSpec().Exists())
1474 {
1475 error = WillLaunch (exe_module);
1476 if (error.Success())
1477 {
Greg Claytond8c62532010-10-07 04:19:01 +00001478 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001479 // The args coming in should not contain the application name, the
1480 // lldb_private::Process class will add this in case the executable
1481 // gets resolved to a different file than was given on the command
1482 // line (like when an applicaiton bundle is specified and will
1483 // resolve to the contained exectuable file, or the file given was
1484 // a symlink or other file system link that resolves to a different
1485 // file).
1486
1487 // Get the resolved exectuable path
1488
1489 // Make a new argument vector
1490 std::vector<const char *> exec_path_plus_argv;
1491 // Append the resolved executable path
1492 exec_path_plus_argv.push_back (exec_file_path);
1493
1494 // Push all args if there are any
1495 if (argv)
1496 {
1497 for (int i = 0; argv[i]; ++i)
1498 exec_path_plus_argv.push_back(argv[i]);
1499 }
1500
1501 // Push a NULL to terminate the args.
1502 exec_path_plus_argv.push_back(NULL);
1503
1504 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001505 error = DoLaunch (exe_module,
1506 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1507 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001508 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001509 stdin_path,
1510 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001511 stderr_path,
1512 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001513
1514 if (error.Fail())
1515 {
1516 if (GetID() != LLDB_INVALID_PROCESS_ID)
1517 {
1518 SetID (LLDB_INVALID_PROCESS_ID);
1519 const char *error_string = error.AsCString();
1520 if (error_string == NULL)
1521 error_string = "launch failed";
1522 SetExitStatus (-1, error_string);
1523 }
1524 }
1525 else
1526 {
1527 EventSP event_sp;
1528 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1529
1530 if (state == eStateStopped || state == eStateCrashed)
1531 {
1532 DidLaunch ();
1533
1534 // This delays passing the stopped event to listeners till DidLaunch gets
1535 // a chance to complete...
1536 HandlePrivateEvent (event_sp);
1537 StartPrivateStateThread ();
1538 }
1539 else if (state == eStateExited)
1540 {
1541 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1542 // not likely to work, and return an invalid pid.
1543 HandlePrivateEvent (event_sp);
1544 }
1545 }
1546 }
1547 }
1548 else
1549 {
1550 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1551 }
1552 }
1553 return error;
1554}
1555
1556Error
1557Process::CompleteAttach ()
1558{
1559 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001560
1561 if (GetID() == LLDB_INVALID_PROCESS_ID)
1562 {
1563 error.SetErrorString("no process");
1564 }
1565
Chris Lattner24943d22010-06-08 16:52:24 +00001566 EventSP event_sp;
1567 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1568 if (state == eStateStopped || state == eStateCrashed)
1569 {
1570 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001571 // Figure out which one is the executable, and set that in our target:
1572 ModuleList &modules = GetTarget().GetImages();
1573
1574 size_t num_modules = modules.GetSize();
1575 for (int i = 0; i < num_modules; i++)
1576 {
1577 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1578 if (module_sp->IsExecutable())
1579 {
1580 ModuleSP exec_module = GetTarget().GetExecutableModule();
1581 if (!exec_module || exec_module != module_sp)
1582 {
1583
1584 GetTarget().SetExecutableModule (module_sp, false);
1585 }
1586 break;
1587 }
1588 }
Chris Lattner24943d22010-06-08 16:52:24 +00001589
1590 // This delays passing the stopped event to listeners till DidLaunch gets
1591 // a chance to complete...
1592 HandlePrivateEvent(event_sp);
1593 StartPrivateStateThread();
1594 }
1595 else
1596 {
1597 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1598 // not likely to work, and return an invalid pid.
1599 if (state == eStateExited)
1600 HandlePrivateEvent (event_sp);
1601 error.SetErrorStringWithFormat("invalid state after attach: %s",
1602 lldb_private::StateAsCString(state));
1603 }
1604 return error;
1605}
1606
1607Error
1608Process::Attach (lldb::pid_t attach_pid)
1609{
1610
1611 m_target_triple.Clear();
1612 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001613 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001614
Jim Ingham7508e732010-08-09 23:31:02 +00001615 // Find the process and its architecture. Make sure it matches the architecture
1616 // of the current Target, and if not adjust it.
1617
1618 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1619 if (attach_spec != GetTarget().GetArchitecture())
1620 {
1621 // Set the architecture on the target.
1622 GetTarget().SetArchitecture(attach_spec);
1623 }
1624
Greg Clayton54e7afa2010-07-09 20:39:50 +00001625 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001626 if (error.Success())
1627 {
Greg Claytond8c62532010-10-07 04:19:01 +00001628 SetPublicState (eStateAttaching);
1629
Greg Clayton54e7afa2010-07-09 20:39:50 +00001630 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001631 if (error.Success())
1632 {
1633 error = CompleteAttach();
1634 }
1635 else
1636 {
1637 if (GetID() != LLDB_INVALID_PROCESS_ID)
1638 {
1639 SetID (LLDB_INVALID_PROCESS_ID);
1640 const char *error_string = error.AsCString();
1641 if (error_string == NULL)
1642 error_string = "attach failed";
1643
1644 SetExitStatus(-1, error_string);
1645 }
1646 }
1647 }
1648 return error;
1649}
1650
1651Error
1652Process::Attach (const char *process_name, bool wait_for_launch)
1653{
1654 m_target_triple.Clear();
1655 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001656 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001657
1658 // Find the process and its architecture. Make sure it matches the architecture
1659 // of the current Target, and if not adjust it.
1660
Jim Inghamea294182010-08-17 21:54:19 +00001661 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001662 {
Jim Inghamea294182010-08-17 21:54:19 +00001663 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001664 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001665 {
1666 // Set the architecture on the target.
1667 GetTarget().SetArchitecture(attach_spec);
1668 }
Jim Ingham7508e732010-08-09 23:31:02 +00001669 }
Jim Inghamea294182010-08-17 21:54:19 +00001670
Greg Clayton54e7afa2010-07-09 20:39:50 +00001671 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001672 if (error.Success())
1673 {
Greg Claytond8c62532010-10-07 04:19:01 +00001674 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001675 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001676 if (error.Fail())
1677 {
1678 if (GetID() != LLDB_INVALID_PROCESS_ID)
1679 {
1680 SetID (LLDB_INVALID_PROCESS_ID);
1681 const char *error_string = error.AsCString();
1682 if (error_string == NULL)
1683 error_string = "attach failed";
1684
1685 SetExitStatus(-1, error_string);
1686 }
1687 }
1688 else
1689 {
1690 error = CompleteAttach();
1691 }
1692 }
1693 return error;
1694}
1695
1696Error
1697Process::Resume ()
1698{
Greg Claytone005f2c2010-11-06 01:53:30 +00001699 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001700 if (log)
1701 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1702
1703 Error error (WillResume());
1704 // Tell the process it is about to resume before the thread list
1705 if (error.Success())
1706 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001707 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001708 // can let all of our threads know that they are about to be
1709 // resumed. Threads will each be called with
1710 // Thread::WillResume(StateType) where StateType contains the state
1711 // that they are supposed to have when the process is resumed
1712 // (suspended/running/stepping). Threads should also check
1713 // their resume signal in lldb::Thread::GetResumeSignal()
1714 // to see if they are suppoed to start back up with a signal.
1715 if (m_thread_list.WillResume())
1716 {
1717 error = DoResume();
1718 if (error.Success())
1719 {
1720 DidResume();
1721 m_thread_list.DidResume();
1722 }
1723 }
1724 else
1725 {
1726 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1727 }
1728 }
1729 return error;
1730}
1731
1732Error
1733Process::Halt ()
1734{
1735 Error error (WillHalt());
1736
1737 if (error.Success())
1738 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001739
1740 bool caused_stop = false;
1741 EventSP event_sp;
1742
1743 // Pause our private state thread so we can ensure no one else eats
1744 // the stop event out from under us.
1745 PausePrivateStateThread();
1746
1747 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001748 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001749 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001750 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001751 // If "caused_stop" is true, then DoHalt stopped the process. If
1752 // "caused_stop" is false, the process was already stopped.
1753 // If the DoHalt caused the process to stop, then we want to catch
1754 // this event and set the interrupted bool to true before we pass
1755 // this along so clients know that the process was interrupted by
1756 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001757 if (caused_stop)
1758 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001759 // Wait for 2 seconds for the process to stop.
1760 TimeValue timeout_time;
1761 timeout_time = TimeValue::Now();
Greg Clayton72e1c782011-01-22 23:43:18 +00001762 timeout_time.OffsetWithSeconds(1);
Greg Clayton20d338f2010-11-18 05:57:03 +00001763 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1764
1765 if (state == eStateInvalid)
1766 {
1767 // We timeout out and didn't get a stop event...
1768 error.SetErrorString ("Halt timed out.");
1769 }
1770 else
1771 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001772 if (StateIsStoppedState (state))
1773 {
1774 // We caused the process to interrupt itself, so mark this
1775 // as such in the stop event so clients can tell an interrupted
1776 // process from a natural stop
1777 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1778 }
1779 else
1780 {
1781 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1782 if (log)
1783 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1784 error.SetErrorString ("Did not get stopped event after halt.");
1785 }
1786 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001787 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001788 DidHalt();
1789
Jim Ingham3ae449a2010-11-17 02:32:00 +00001790 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001791 // Resume our private state thread before we post the event (if any)
1792 ResumePrivateStateThread();
1793
1794 // Post any event we might have consumed. If all goes well, we will have
1795 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001796 // bool in the event. Post it to the private event queue and that will end up
1797 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001798 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001799 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001800
Chris Lattner24943d22010-06-08 16:52:24 +00001801 }
1802 return error;
1803}
1804
1805Error
1806Process::Detach ()
1807{
1808 Error error (WillDetach());
1809
1810 if (error.Success())
1811 {
1812 DisableAllBreakpointSites();
1813 error = DoDetach();
1814 if (error.Success())
1815 {
1816 DidDetach();
1817 StopPrivateStateThread();
1818 }
1819 }
1820 return error;
1821}
1822
1823Error
1824Process::Destroy ()
1825{
1826 Error error (WillDestroy());
1827 if (error.Success())
1828 {
1829 DisableAllBreakpointSites();
1830 error = DoDestroy();
1831 if (error.Success())
1832 {
1833 DidDestroy();
1834 StopPrivateStateThread();
1835 }
Caroline Tice861efb32010-11-16 05:07:41 +00001836 m_stdio_communication.StopReadThread();
1837 m_stdio_communication.Disconnect();
1838 if (m_process_input_reader && m_process_input_reader->IsActive())
1839 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1840 if (m_process_input_reader)
1841 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001842 }
1843 return error;
1844}
1845
1846Error
1847Process::Signal (int signal)
1848{
1849 Error error (WillSignal());
1850 if (error.Success())
1851 {
1852 error = DoSignal(signal);
1853 if (error.Success())
1854 DidSignal();
1855 }
1856 return error;
1857}
1858
1859UnixSignals &
1860Process::GetUnixSignals ()
1861{
1862 return m_unix_signals;
1863}
1864
1865Target &
1866Process::GetTarget ()
1867{
1868 return m_target;
1869}
1870
1871const Target &
1872Process::GetTarget () const
1873{
1874 return m_target;
1875}
1876
1877uint32_t
1878Process::GetAddressByteSize()
1879{
Greg Clayton20d338f2010-11-18 05:57:03 +00001880 if (m_addr_byte_size == 0)
1881 return m_target.GetArchitecture().GetAddressByteSize();
1882 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001883}
1884
1885bool
1886Process::ShouldBroadcastEvent (Event *event_ptr)
1887{
1888 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1889 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001890 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001891
1892 switch (state)
1893 {
1894 case eStateAttaching:
1895 case eStateLaunching:
1896 case eStateDetached:
1897 case eStateExited:
1898 case eStateUnloaded:
1899 // These events indicate changes in the state of the debugging session, always report them.
1900 return_value = true;
1901 break;
1902 case eStateInvalid:
1903 // We stopped for no apparent reason, don't report it.
1904 return_value = false;
1905 break;
1906 case eStateRunning:
1907 case eStateStepping:
1908 // If we've started the target running, we handle the cases where we
1909 // are already running and where there is a transition from stopped to
1910 // running differently.
1911 // running -> running: Automatically suppress extra running events
1912 // stopped -> running: Report except when there is one or more no votes
1913 // and no yes votes.
1914 SynchronouslyNotifyStateChanged (state);
1915 switch (m_public_state.GetValue())
1916 {
1917 case eStateRunning:
1918 case eStateStepping:
1919 // We always suppress multiple runnings with no PUBLIC stop in between.
1920 return_value = false;
1921 break;
1922 default:
1923 // TODO: make this work correctly. For now always report
1924 // run if we aren't running so we don't miss any runnning
1925 // events. If I run the lldb/test/thread/a.out file and
1926 // break at main.cpp:58, run and hit the breakpoints on
1927 // multiple threads, then somehow during the stepping over
1928 // of all breakpoints no run gets reported.
1929 return_value = true;
1930
1931 // This is a transition from stop to run.
1932 switch (m_thread_list.ShouldReportRun (event_ptr))
1933 {
1934 case eVoteYes:
1935 case eVoteNoOpinion:
1936 return_value = true;
1937 break;
1938 case eVoteNo:
1939 return_value = false;
1940 break;
1941 }
1942 break;
1943 }
1944 break;
1945 case eStateStopped:
1946 case eStateCrashed:
1947 case eStateSuspended:
1948 {
1949 // We've stopped. First see if we're going to restart the target.
1950 // If we are going to stop, then we always broadcast the event.
1951 // 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 +00001952 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001953 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001954 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001955 if (log)
1956 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001957 return true;
1958 }
1959 else
1960 {
Chris Lattner24943d22010-06-08 16:52:24 +00001961 RefreshStateAfterStop ();
1962
1963 if (m_thread_list.ShouldStop (event_ptr) == false)
1964 {
1965 switch (m_thread_list.ShouldReportStop (event_ptr))
1966 {
1967 case eVoteYes:
1968 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001969 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001970 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001971 case eVoteNo:
1972 return_value = false;
1973 break;
1974 }
1975
1976 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001977 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001978 Resume ();
1979 }
1980 else
1981 {
1982 return_value = true;
1983 SynchronouslyNotifyStateChanged (state);
1984 }
1985 }
1986 }
1987 }
1988
1989 if (log)
1990 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1991 return return_value;
1992}
1993
1994//------------------------------------------------------------------
1995// Thread Queries
1996//------------------------------------------------------------------
1997
1998ThreadList &
1999Process::GetThreadList ()
2000{
2001 return m_thread_list;
2002}
2003
2004const ThreadList &
2005Process::GetThreadList () const
2006{
2007 return m_thread_list;
2008}
2009
2010
2011bool
2012Process::StartPrivateStateThread ()
2013{
Greg Claytone005f2c2010-11-06 01:53:30 +00002014 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002015
2016 if (log)
2017 log->Printf ("Process::%s ( )", __FUNCTION__);
2018
2019 // Create a thread that watches our internal state and controls which
2020 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002021 char thread_name[1024];
2022 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2023 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002024 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2025}
2026
2027void
2028Process::PausePrivateStateThread ()
2029{
2030 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2031}
2032
2033void
2034Process::ResumePrivateStateThread ()
2035{
2036 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2037}
2038
2039void
2040Process::StopPrivateStateThread ()
2041{
2042 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2043}
2044
2045void
2046Process::ControlPrivateStateThread (uint32_t signal)
2047{
Greg Claytone005f2c2010-11-06 01:53:30 +00002048 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002049
2050 assert (signal == eBroadcastInternalStateControlStop ||
2051 signal == eBroadcastInternalStateControlPause ||
2052 signal == eBroadcastInternalStateControlResume);
2053
2054 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002055 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002056
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002057 // Signal the private state thread. First we should copy this is case the
2058 // thread starts exiting since the private state thread will NULL this out
2059 // when it exits
2060 const lldb::thread_t private_state_thread = m_private_state_thread;
2061 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner24943d22010-06-08 16:52:24 +00002062 {
2063 TimeValue timeout_time;
2064 bool timed_out;
2065
2066 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2067
2068 timeout_time = TimeValue::Now();
2069 timeout_time.OffsetWithSeconds(2);
2070 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2071 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2072
2073 if (signal == eBroadcastInternalStateControlStop)
2074 {
2075 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002076 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002077
2078 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002079 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002080 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002081 }
2082 }
2083}
2084
2085void
2086Process::HandlePrivateEvent (EventSP &event_sp)
2087{
Greg Claytone005f2c2010-11-06 01:53:30 +00002088 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002089 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2090 // See if we should broadcast this state to external clients?
2091 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2092 if (log)
2093 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2094
2095 if (should_broadcast)
2096 {
2097 if (log)
2098 {
2099 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2100 }
Caroline Tice861efb32010-11-16 05:07:41 +00002101 if (StateIsRunningState (internal_state))
2102 PushProcessInputReader ();
2103 else
2104 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002105 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2106 BroadcastEvent (event_sp);
2107 }
2108 else
2109 {
2110 if (log)
2111 {
2112 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2113 }
2114 }
2115}
2116
2117void *
2118Process::PrivateStateThread (void *arg)
2119{
2120 Process *proc = static_cast<Process*> (arg);
2121 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002122 return result;
2123}
2124
2125void *
2126Process::RunPrivateStateThread ()
2127{
2128 bool control_only = false;
2129 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2130
Greg Claytone005f2c2010-11-06 01:53:30 +00002131 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002132 if (log)
2133 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2134
2135 bool exit_now = false;
2136 while (!exit_now)
2137 {
2138 EventSP event_sp;
2139 WaitForEventsPrivate (NULL, event_sp, control_only);
2140 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2141 {
2142 switch (event_sp->GetType())
2143 {
2144 case eBroadcastInternalStateControlStop:
2145 exit_now = true;
2146 continue; // Go to next loop iteration so we exit without
2147 break; // doing any internal state managment below
2148
2149 case eBroadcastInternalStateControlPause:
2150 control_only = true;
2151 break;
2152
2153 case eBroadcastInternalStateControlResume:
2154 control_only = false;
2155 break;
2156 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002157
Jim Ingham3ae449a2010-11-17 02:32:00 +00002158 if (log)
2159 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2160
Chris Lattner24943d22010-06-08 16:52:24 +00002161 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002162 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002163 }
2164
2165
2166 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2167
2168 if (internal_state != eStateInvalid)
2169 {
2170 HandlePrivateEvent (event_sp);
2171 }
2172
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002173 if (internal_state == eStateInvalid ||
2174 internal_state == eStateExited ||
2175 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002176 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002177 if (log)
2178 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2179
Chris Lattner24943d22010-06-08 16:52:24 +00002180 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002181 }
Chris Lattner24943d22010-06-08 16:52:24 +00002182 }
2183
Caroline Tice926060e2010-10-29 21:48:37 +00002184 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002185 if (log)
2186 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2187
Greg Claytona4881d02011-01-22 07:12:45 +00002188 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2189 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002190 return NULL;
2191}
2192
Chris Lattner24943d22010-06-08 16:52:24 +00002193//------------------------------------------------------------------
2194// Process Event Data
2195//------------------------------------------------------------------
2196
2197Process::ProcessEventData::ProcessEventData () :
2198 EventData (),
2199 m_process_sp (),
2200 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002201 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002202 m_update_state (false),
2203 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002204{
2205}
2206
2207Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2208 EventData (),
2209 m_process_sp (process_sp),
2210 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002211 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002212 m_update_state (false),
2213 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002214{
2215}
2216
2217Process::ProcessEventData::~ProcessEventData()
2218{
2219}
2220
2221const ConstString &
2222Process::ProcessEventData::GetFlavorString ()
2223{
2224 static ConstString g_flavor ("Process::ProcessEventData");
2225 return g_flavor;
2226}
2227
2228const ConstString &
2229Process::ProcessEventData::GetFlavor () const
2230{
2231 return ProcessEventData::GetFlavorString ();
2232}
2233
Chris Lattner24943d22010-06-08 16:52:24 +00002234void
2235Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2236{
2237 // This function gets called twice for each event, once when the event gets pulled
2238 // off of the private process event queue, and once when it gets pulled off of
2239 // the public event queue. m_update_state is used to distinguish these
2240 // two cases; it is false when we're just pulling it off for private handling,
2241 // and we don't want to do the breakpoint command handling then.
2242
2243 if (!m_update_state)
2244 return;
2245
2246 m_process_sp->SetPublicState (m_state);
2247
2248 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2249 if (m_state == eStateStopped && ! m_restarted)
2250 {
2251 int num_threads = m_process_sp->GetThreadList().GetSize();
2252 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002253
Chris Lattner24943d22010-06-08 16:52:24 +00002254 for (idx = 0; idx < num_threads; ++idx)
2255 {
2256 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2257
Jim Ingham6297a3a2010-10-20 00:39:53 +00002258 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2259 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002260 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002261 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002262 }
2263 }
Greg Clayton643ee732010-08-04 01:40:35 +00002264
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002265 // The stop action might restart the target. If it does, then we want to mark that in the
2266 // event so that whoever is receiving it will know to wait for the running event and reflect
2267 // that state appropriately.
2268
Chris Lattner24943d22010-06-08 16:52:24 +00002269 if (m_process_sp->GetPrivateState() == eStateRunning)
2270 SetRestarted(true);
2271 }
2272}
2273
2274void
2275Process::ProcessEventData::Dump (Stream *s) const
2276{
2277 if (m_process_sp)
2278 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2279
2280 s->Printf("state = %s", StateAsCString(GetState()));;
2281}
2282
2283const Process::ProcessEventData *
2284Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2285{
2286 if (event_ptr)
2287 {
2288 const EventData *event_data = event_ptr->GetData();
2289 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2290 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2291 }
2292 return NULL;
2293}
2294
2295ProcessSP
2296Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2297{
2298 ProcessSP process_sp;
2299 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2300 if (data)
2301 process_sp = data->GetProcessSP();
2302 return process_sp;
2303}
2304
2305StateType
2306Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2307{
2308 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2309 if (data == NULL)
2310 return eStateInvalid;
2311 else
2312 return data->GetState();
2313}
2314
2315bool
2316Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2317{
2318 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2319 if (data == NULL)
2320 return false;
2321 else
2322 return data->GetRestarted();
2323}
2324
2325void
2326Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2327{
2328 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2329 if (data != NULL)
2330 data->SetRestarted(new_value);
2331}
2332
2333bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002334Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2335{
2336 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2337 if (data == NULL)
2338 return false;
2339 else
2340 return data->GetInterrupted ();
2341}
2342
2343void
2344Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2345{
2346 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2347 if (data != NULL)
2348 data->SetInterrupted(new_value);
2349}
2350
2351bool
Chris Lattner24943d22010-06-08 16:52:24 +00002352Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2353{
2354 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2355 if (data)
2356 {
2357 data->SetUpdateStateOnRemoval();
2358 return true;
2359 }
2360 return false;
2361}
2362
Chris Lattner24943d22010-06-08 16:52:24 +00002363Target *
2364Process::CalculateTarget ()
2365{
2366 return &m_target;
2367}
2368
2369Process *
2370Process::CalculateProcess ()
2371{
2372 return this;
2373}
2374
2375Thread *
2376Process::CalculateThread ()
2377{
2378 return NULL;
2379}
2380
2381StackFrame *
2382Process::CalculateStackFrame ()
2383{
2384 return NULL;
2385}
2386
2387void
Greg Claytona830adb2010-10-04 01:05:56 +00002388Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002389{
2390 exe_ctx.target = &m_target;
2391 exe_ctx.process = this;
2392 exe_ctx.thread = NULL;
2393 exe_ctx.frame = NULL;
2394}
2395
2396lldb::ProcessSP
2397Process::GetSP ()
2398{
2399 return GetTarget().GetProcessSP();
2400}
2401
Jim Ingham7508e732010-08-09 23:31:02 +00002402uint32_t
2403Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2404{
2405 return 0;
2406}
2407
2408ArchSpec
2409Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2410{
2411 return Host::GetArchSpecForExistingProcess (pid);
2412}
2413
2414ArchSpec
2415Process::GetArchSpecForExistingProcess (const char *process_name)
2416{
2417 return Host::GetArchSpecForExistingProcess (process_name);
2418}
2419
Caroline Tice861efb32010-11-16 05:07:41 +00002420void
2421Process::AppendSTDOUT (const char * s, size_t len)
2422{
Greg Clayton20d338f2010-11-18 05:57:03 +00002423 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002424 m_stdout_data.append (s, len);
2425
Greg Claytonb3781332010-12-05 19:16:56 +00002426 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002427}
2428
2429void
2430Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2431{
2432 Process *process = (Process *) baton;
2433 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2434}
2435
2436size_t
2437Process::ProcessInputReaderCallback (void *baton,
2438 InputReader &reader,
2439 lldb::InputReaderAction notification,
2440 const char *bytes,
2441 size_t bytes_len)
2442{
2443 Process *process = (Process *) baton;
2444
2445 switch (notification)
2446 {
2447 case eInputReaderActivate:
2448 break;
2449
2450 case eInputReaderDeactivate:
2451 break;
2452
2453 case eInputReaderReactivate:
2454 break;
2455
2456 case eInputReaderGotToken:
2457 {
2458 Error error;
2459 process->PutSTDIN (bytes, bytes_len, error);
2460 }
2461 break;
2462
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002463 case eInputReaderInterrupt:
2464 process->Halt ();
2465 break;
2466
2467 case eInputReaderEndOfFile:
2468 process->AppendSTDOUT ("^D", 2);
2469 break;
2470
Caroline Tice861efb32010-11-16 05:07:41 +00002471 case eInputReaderDone:
2472 break;
2473
2474 }
2475
2476 return bytes_len;
2477}
2478
2479void
2480Process::ResetProcessInputReader ()
2481{
2482 m_process_input_reader.reset();
2483}
2484
2485void
2486Process::SetUpProcessInputReader (int file_descriptor)
2487{
2488 // First set up the Read Thread for reading/handling process I/O
2489
2490 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2491
2492 if (conn_ap.get())
2493 {
2494 m_stdio_communication.SetConnection (conn_ap.release());
2495 if (m_stdio_communication.IsConnected())
2496 {
2497 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2498 m_stdio_communication.StartReadThread();
2499
2500 // Now read thread is set up, set up input reader.
2501
2502 if (!m_process_input_reader.get())
2503 {
2504 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2505 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2506 this,
2507 eInputReaderGranularityByte,
2508 NULL,
2509 NULL,
2510 false));
2511
2512 if (err.Fail())
2513 m_process_input_reader.reset();
2514 }
2515 }
2516 }
2517}
2518
2519void
2520Process::PushProcessInputReader ()
2521{
2522 if (m_process_input_reader && !m_process_input_reader->IsActive())
2523 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2524}
2525
2526void
2527Process::PopProcessInputReader ()
2528{
2529 if (m_process_input_reader && m_process_input_reader->IsActive())
2530 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2531}
2532
Greg Clayton990de7b2010-11-18 23:32:35 +00002533
2534void
2535Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002536{
Greg Clayton990de7b2010-11-18 23:32:35 +00002537 UserSettingsControllerSP &usc = GetSettingsController();
2538 usc.reset (new SettingsController);
2539 UserSettingsController::InitializeSettingsController (usc,
2540 SettingsController::global_settings_table,
2541 SettingsController::instance_settings_table);
2542}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002543
Greg Clayton990de7b2010-11-18 23:32:35 +00002544void
2545Process::Terminate ()
2546{
2547 UserSettingsControllerSP &usc = GetSettingsController();
2548 UserSettingsController::FinalizeSettingsController (usc);
2549 usc.reset();
2550}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002551
Greg Clayton990de7b2010-11-18 23:32:35 +00002552UserSettingsControllerSP &
2553Process::GetSettingsController ()
2554{
2555 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002556 return g_settings_controller;
2557}
2558
Caroline Tice1ebef442010-09-27 00:30:10 +00002559void
2560Process::UpdateInstanceName ()
2561{
2562 ModuleSP module_sp = GetTarget().GetExecutableModule();
2563 if (module_sp)
2564 {
2565 StreamString sstr;
2566 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2567
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002568 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002569 sstr.GetData());
2570 }
2571}
2572
Greg Clayton427f2902010-12-14 02:59:59 +00002573ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002574Process::RunThreadPlan (ExecutionContext &exe_ctx,
2575 lldb::ThreadPlanSP &thread_plan_sp,
2576 bool stop_others,
2577 bool try_all_threads,
2578 bool discard_on_error,
2579 uint32_t single_thread_timeout_usec,
2580 Stream &errors)
2581{
2582 ExecutionResults return_value = eExecutionSetupError;
2583
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002584 if (thread_plan_sp.get() == NULL)
2585 {
2586 errors.Printf("RunThreadPlan called with empty thread plan.");
2587 return lldb::eExecutionSetupError;
2588 }
2589
Jim Ingham360f53f2010-11-30 02:22:11 +00002590 // Save this value for restoration of the execution context after we run
2591 uint32_t tid = exe_ctx.thread->GetIndexID();
2592
2593 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2594 // so we should arrange to reset them as well.
2595
2596 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2597 lldb::StackFrameSP selected_frame_sp;
2598
2599 uint32_t selected_tid;
2600 if (selected_thread_sp != NULL)
2601 {
2602 selected_tid = selected_thread_sp->GetIndexID();
2603 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2604 }
2605 else
2606 {
2607 selected_tid = LLDB_INVALID_THREAD_ID;
2608 }
2609
2610 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2611
2612 Listener listener("ClangFunction temporary listener");
2613 exe_ctx.process->HijackProcessEvents(&listener);
2614
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002615 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2616 if (log)
2617 {
2618 StreamString s;
2619 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
2620 log->Printf ("Resuming thread 0x%x to run thread plan \"%s\".", tid, s.GetData());
2621 }
2622
Jim Ingham360f53f2010-11-30 02:22:11 +00002623 Error resume_error = exe_ctx.process->Resume ();
2624 if (!resume_error.Success())
2625 {
2626 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2627 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002628 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002629 }
2630
2631 // We need to call the function synchronously, so spin waiting for it to return.
2632 // If we get interrupted while executing, we're going to lose our context, and
2633 // won't be able to gather the result at this point.
2634 // We set the timeout AFTER the resume, since the resume takes some time and we
2635 // don't want to charge that to the timeout.
2636
2637 TimeValue* timeout_ptr = NULL;
2638 TimeValue real_timeout;
2639
2640 if (single_thread_timeout_usec != 0)
2641 {
2642 real_timeout = TimeValue::Now();
2643 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2644 timeout_ptr = &real_timeout;
2645 }
2646
Jim Ingham360f53f2010-11-30 02:22:11 +00002647 while (1)
2648 {
2649 lldb::EventSP event_sp;
2650 lldb::StateType stop_state = lldb::eStateInvalid;
2651 // Now wait for the process to stop again:
2652 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2653
2654 if (!got_event)
2655 {
2656 // Right now this is the only way to tell we've timed out...
2657 // We should interrupt the process here...
2658 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002659 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002660 if (try_all_threads)
2661 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2662 single_thread_timeout_usec);
2663 else
2664 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2665 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002666 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002667
Jim Inghamc556b462011-01-22 01:30:53 +00002668 Error halt_error = exe_ctx.process->Halt();
2669
2670 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002671 {
2672 timeout_ptr = NULL;
2673 if (log)
2674 log->Printf ("Halt succeeded.");
2675
2676 // Between the time that we got the timeout and the time we halted, but target
2677 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2678 // timeout to
2679 got_event = listener.WaitForEvent(NULL, event_sp);
2680
2681 if (got_event)
2682 {
2683 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2684 if (log)
2685 {
2686 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2687 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2688 log->Printf (" Event was the Halt interruption event.");
2689 }
2690
2691 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2692 {
2693 if (log)
2694 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002695 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002696 break;
2697 }
2698
2699 if (try_all_threads
2700 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2701 {
2702
2703 thread_plan_sp->SetStopOthers (false);
2704 if (log)
2705 log->Printf ("About to resume.");
2706
2707 exe_ctx.process->Resume();
2708 continue;
2709 }
2710 else
2711 {
2712 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002713 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002714 }
2715 }
2716 }
Jim Inghamc556b462011-01-22 01:30:53 +00002717 else
2718 {
2719
2720 if (log)
2721 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2722 halt_error.AsCString());
2723
2724 if (single_thread_timeout_usec != 0)
2725 {
2726 real_timeout = TimeValue::Now();
2727 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2728 timeout_ptr = &real_timeout;
2729 }
2730 continue;
2731 }
2732
Jim Ingham360f53f2010-11-30 02:22:11 +00002733 }
2734
2735 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2736 if (log)
2737 log->Printf("Got event: %s.", StateAsCString(stop_state));
2738
2739 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2740 continue;
2741
2742 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2743 {
Greg Clayton427f2902010-12-14 02:59:59 +00002744 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002745 break;
2746 }
2747 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2748 {
Greg Clayton427f2902010-12-14 02:59:59 +00002749 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002750 break;
2751 }
2752 else
2753 {
2754 if (log)
2755 {
2756 StreamString s;
Jim Inghamc556b462011-01-22 01:30:53 +00002757 if (event_sp)
2758 event_sp->Dump (&s);
2759 else
2760 {
2761 log->Printf ("Stop event that interrupted us is NULL.");
2762 }
2763
Jim Ingham360f53f2010-11-30 02:22:11 +00002764 StreamString ts;
2765
2766 const char *event_explanation;
2767
2768 do
2769 {
2770 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2771
2772 if (!event_data)
2773 {
2774 event_explanation = "<no event data>";
2775 break;
2776 }
2777
2778 Process *process = event_data->GetProcessSP().get();
2779
2780 if (!process)
2781 {
2782 event_explanation = "<no process>";
2783 break;
2784 }
2785
2786 ThreadList &thread_list = process->GetThreadList();
2787
2788 uint32_t num_threads = thread_list.GetSize();
2789 uint32_t thread_index;
2790
2791 ts.Printf("<%u threads> ", num_threads);
2792
2793 for (thread_index = 0;
2794 thread_index < num_threads;
2795 ++thread_index)
2796 {
2797 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2798
2799 if (!thread)
2800 {
2801 ts.Printf("<?> ");
2802 continue;
2803 }
2804
Jim Inghamc556b462011-01-22 01:30:53 +00002805 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002806 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002807
2808 if (register_context)
2809 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2810 else
2811 ts.Printf("[ip unknown] ");
2812
2813 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2814 if (stop_info_sp)
2815 {
2816 const char *stop_desc = stop_info_sp->GetDescription();
2817 if (stop_desc)
2818 ts.PutCString (stop_desc);
2819 }
2820 ts.Printf(">");
2821 }
2822
2823 event_explanation = ts.GetData();
2824 } while (0);
2825
Jim Inghamc556b462011-01-22 01:30:53 +00002826 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2827 if (!GetThreadList().ShouldStop(event_sp.get()))
2828 {
2829 if (log)
2830 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2831 s.GetData(), event_explanation);
2832 if (single_thread_timeout_usec != 0)
2833 {
2834 real_timeout = TimeValue::Now();
2835 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2836 timeout_ptr = &real_timeout;
2837 }
2838
2839 continue;
2840 }
2841 else
2842 {
2843 if (log)
2844 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2845 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002846 }
2847
2848 if (discard_on_error && thread_plan_sp)
2849 {
2850 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2851 }
Greg Clayton427f2902010-12-14 02:59:59 +00002852 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002853 break;
2854 }
2855 }
2856
2857 if (exe_ctx.process)
2858 exe_ctx.process->RestoreProcessEvents ();
2859
2860 // Thread we ran the function in may have gone away because we ran the target
2861 // Check that it's still there.
2862 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2863 if (exe_ctx.thread)
2864 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2865
2866 // Also restore the current process'es selected frame & thread, since this function calling may
2867 // be done behind the user's back.
2868
2869 if (selected_tid != LLDB_INVALID_THREAD_ID)
2870 {
2871 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2872 {
2873 // We were able to restore the selected thread, now restore the frame:
2874 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2875 }
2876 }
2877
2878 return return_value;
2879}
2880
2881const char *
2882Process::ExecutionResultAsCString (ExecutionResults result)
2883{
2884 const char *result_name;
2885
2886 switch (result)
2887 {
Greg Clayton427f2902010-12-14 02:59:59 +00002888 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002889 result_name = "eExecutionCompleted";
2890 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002891 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002892 result_name = "eExecutionDiscarded";
2893 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002894 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002895 result_name = "eExecutionInterrupted";
2896 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002897 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002898 result_name = "eExecutionSetupError";
2899 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002900 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002901 result_name = "eExecutionTimedOut";
2902 break;
2903 }
2904 return result_name;
2905}
2906
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002907//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002908// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002909//--------------------------------------------------------------
2910
Greg Claytond0a5a232010-09-19 02:33:57 +00002911Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002912 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002913{
Greg Clayton638351a2010-12-04 00:10:17 +00002914 m_default_settings.reset (new ProcessInstanceSettings (*this,
2915 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002916 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002917}
2918
Greg Claytond0a5a232010-09-19 02:33:57 +00002919Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002920{
2921}
2922
2923lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002924Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002925{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002926 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2927 false,
2928 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002929 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2930 return new_settings_sp;
2931}
2932
2933//--------------------------------------------------------------
2934// class ProcessInstanceSettings
2935//--------------------------------------------------------------
2936
Greg Clayton638351a2010-12-04 00:10:17 +00002937ProcessInstanceSettings::ProcessInstanceSettings
2938(
2939 UserSettingsController &owner,
2940 bool live_instance,
2941 const char *name
2942) :
2943 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002944 m_run_args (),
2945 m_env_vars (),
2946 m_input_path (),
2947 m_output_path (),
2948 m_error_path (),
2949 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002950 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002951 m_disable_stdio (false),
2952 m_inherit_host_env (true),
2953 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002954{
Caroline Tice396704b2010-09-09 18:26:37 +00002955 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2956 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2957 // 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 +00002958 // This is true for CreateInstanceName() too.
2959
2960 if (GetInstanceName () == InstanceSettings::InvalidName())
2961 {
2962 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2963 m_owner.RegisterInstanceSettings (this);
2964 }
Caroline Tice396704b2010-09-09 18:26:37 +00002965
2966 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002967 {
2968 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2969 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002970 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002971 }
2972}
2973
2974ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002975 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002976 m_run_args (rhs.m_run_args),
2977 m_env_vars (rhs.m_env_vars),
2978 m_input_path (rhs.m_input_path),
2979 m_output_path (rhs.m_output_path),
2980 m_error_path (rhs.m_error_path),
2981 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00002982 m_disable_aslr (rhs.m_disable_aslr),
2983 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002984{
2985 if (m_instance_name != InstanceSettings::GetDefaultName())
2986 {
2987 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2988 CopyInstanceSettings (pending_settings,false);
2989 m_owner.RemovePendingSettings (m_instance_name);
2990 }
2991}
2992
2993ProcessInstanceSettings::~ProcessInstanceSettings ()
2994{
2995}
2996
2997ProcessInstanceSettings&
2998ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2999{
3000 if (this != &rhs)
3001 {
3002 m_run_args = rhs.m_run_args;
3003 m_env_vars = rhs.m_env_vars;
3004 m_input_path = rhs.m_input_path;
3005 m_output_path = rhs.m_output_path;
3006 m_error_path = rhs.m_error_path;
3007 m_plugin = rhs.m_plugin;
3008 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003009 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003010 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003011 }
3012
3013 return *this;
3014}
3015
3016
3017void
3018ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3019 const char *index_value,
3020 const char *value,
3021 const ConstString &instance_name,
3022 const SettingEntry &entry,
3023 lldb::VarSetOperationType op,
3024 Error &err,
3025 bool pending)
3026{
3027 if (var_name == RunArgsVarName())
3028 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3029 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003030 {
3031 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003032 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003033 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003034 else if (var_name == InputPathVarName())
3035 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3036 else if (var_name == OutputPathVarName())
3037 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3038 else if (var_name == ErrorPathVarName())
3039 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3040 else if (var_name == PluginVarName())
3041 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003042 else if (var_name == InheritHostEnvVarName())
3043 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003044 else if (var_name == DisableASLRVarName())
3045 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003046 else if (var_name == DisableSTDIOVarName ())
3047 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003048}
3049
3050void
3051ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3052 bool pending)
3053{
3054 if (new_settings.get() == NULL)
3055 return;
3056
3057 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3058
3059 m_run_args = new_process_settings->m_run_args;
3060 m_env_vars = new_process_settings->m_env_vars;
3061 m_input_path = new_process_settings->m_input_path;
3062 m_output_path = new_process_settings->m_output_path;
3063 m_error_path = new_process_settings->m_error_path;
3064 m_plugin = new_process_settings->m_plugin;
3065 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003066 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003067}
3068
Caroline Ticebcb5b452010-09-20 21:37:42 +00003069bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003070ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3071 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003072 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003073 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003074{
3075 if (var_name == RunArgsVarName())
3076 {
3077 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003078 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003079 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3080 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003081 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003082 }
3083 else if (var_name == EnvVarsVarName())
3084 {
Greg Clayton638351a2010-12-04 00:10:17 +00003085 GetHostEnvironmentIfNeeded ();
3086
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003087 if (m_env_vars.size() > 0)
3088 {
3089 std::map<std::string, std::string>::iterator pos;
3090 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3091 {
3092 StreamString value_str;
3093 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3094 value.AppendString (value_str.GetData());
3095 }
3096 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003097 }
3098 else if (var_name == InputPathVarName())
3099 {
3100 value.AppendString (m_input_path.c_str());
3101 }
3102 else if (var_name == OutputPathVarName())
3103 {
3104 value.AppendString (m_output_path.c_str());
3105 }
3106 else if (var_name == ErrorPathVarName())
3107 {
3108 value.AppendString (m_error_path.c_str());
3109 }
3110 else if (var_name == PluginVarName())
3111 {
3112 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3113 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003114 else if (var_name == InheritHostEnvVarName())
3115 {
3116 if (m_inherit_host_env)
3117 value.AppendString ("true");
3118 else
3119 value.AppendString ("false");
3120 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003121 else if (var_name == DisableASLRVarName())
3122 {
3123 if (m_disable_aslr)
3124 value.AppendString ("true");
3125 else
3126 value.AppendString ("false");
3127 }
Caroline Ticebd666012010-12-03 18:46:09 +00003128 else if (var_name == DisableSTDIOVarName())
3129 {
3130 if (m_disable_stdio)
3131 value.AppendString ("true");
3132 else
3133 value.AppendString ("false");
3134 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003135 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003136 {
3137 if (err)
3138 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3139 return false;
3140 }
3141 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003142}
3143
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003144const ConstString
3145ProcessInstanceSettings::CreateInstanceName ()
3146{
3147 static int instance_count = 1;
3148 StreamString sstr;
3149
3150 sstr.Printf ("process_%d", instance_count);
3151 ++instance_count;
3152
3153 const ConstString ret_val (sstr.GetData());
3154 return ret_val;
3155}
3156
3157const ConstString &
3158ProcessInstanceSettings::RunArgsVarName ()
3159{
3160 static ConstString run_args_var_name ("run-args");
3161
3162 return run_args_var_name;
3163}
3164
3165const ConstString &
3166ProcessInstanceSettings::EnvVarsVarName ()
3167{
3168 static ConstString env_vars_var_name ("env-vars");
3169
3170 return env_vars_var_name;
3171}
3172
3173const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003174ProcessInstanceSettings::InheritHostEnvVarName ()
3175{
3176 static ConstString g_name ("inherit-env");
3177
3178 return g_name;
3179}
3180
3181const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003182ProcessInstanceSettings::InputPathVarName ()
3183{
3184 static ConstString input_path_var_name ("input-path");
3185
3186 return input_path_var_name;
3187}
3188
3189const ConstString &
3190ProcessInstanceSettings::OutputPathVarName ()
3191{
Caroline Tice87097232010-09-07 18:35:40 +00003192 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003193
3194 return output_path_var_name;
3195}
3196
3197const ConstString &
3198ProcessInstanceSettings::ErrorPathVarName ()
3199{
Caroline Tice87097232010-09-07 18:35:40 +00003200 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003201
3202 return error_path_var_name;
3203}
3204
3205const ConstString &
3206ProcessInstanceSettings::PluginVarName ()
3207{
3208 static ConstString plugin_var_name ("plugin");
3209
3210 return plugin_var_name;
3211}
3212
3213
3214const ConstString &
3215ProcessInstanceSettings::DisableASLRVarName ()
3216{
3217 static ConstString disable_aslr_var_name ("disable-aslr");
3218
3219 return disable_aslr_var_name;
3220}
3221
Caroline Ticebd666012010-12-03 18:46:09 +00003222const ConstString &
3223ProcessInstanceSettings::DisableSTDIOVarName ()
3224{
3225 static ConstString disable_stdio_var_name ("disable-stdio");
3226
3227 return disable_stdio_var_name;
3228}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003229
3230//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003231// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003232//--------------------------------------------------
3233
3234SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003235Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003236{
3237 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3238 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3239};
3240
3241
3242lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003243Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003244{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003245 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3246 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3247 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003248};
3249
3250SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003251Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003252{
Greg Clayton638351a2010-12-04 00:10:17 +00003253 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3254 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3255 { "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." },
3256 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003257 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3258 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3259 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3260 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003261 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3262 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3263 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003264};
3265
3266
Jim Ingham7508e732010-08-09 23:31:02 +00003267