blob: aa0170ca8366ff0f4dc1be1e83f9a4cef95920e7 [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.
Greg Clayton2860ba92011-01-23 19:58:49 +00001401 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1402 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1403 if (log)
1404 log->Printf("Process::AllocateMemory(size = %zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
1405 size,
1406 permissions & ePermissionsReadable ? 'r' : '-',
1407 permissions & ePermissionsWritable ? 'w' : '-',
1408 permissions & ePermissionsExecutable ? 'x' : '-',
1409 (uint64_t)allocated_addr,
1410 m_stop_id);
1411 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001412}
1413
1414Error
1415Process::DeallocateMemory (addr_t ptr)
1416{
Greg Clayton2860ba92011-01-23 19:58:49 +00001417 Error error(DoDeallocateMemory (ptr));
1418
1419 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1420 if (log)
1421 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1422 ptr,
1423 error.AsCString("SUCCESS"),
1424 m_stop_id);
1425 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001426}
1427
1428
1429Error
1430Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1431{
1432 Error error;
1433 error.SetErrorString("watchpoints are not supported");
1434 return error;
1435}
1436
1437Error
1438Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1439{
1440 Error error;
1441 error.SetErrorString("watchpoints are not supported");
1442 return error;
1443}
1444
1445StateType
1446Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1447{
1448 StateType state;
1449 // Now wait for the process to launch and return control to us, and then
1450 // call DidLaunch:
1451 while (1)
1452 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001453 event_sp.reset();
1454 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1455
1456 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001457 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001458
1459 // If state is invalid, then we timed out
1460 if (state == eStateInvalid)
1461 break;
1462
1463 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001464 HandlePrivateEvent (event_sp);
1465 }
1466 return state;
1467}
1468
1469Error
1470Process::Launch
1471(
1472 char const *argv[],
1473 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001474 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001475 const char *stdin_path,
1476 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001477 const char *stderr_path,
1478 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001479)
1480{
1481 Error error;
1482 m_target_triple.Clear();
1483 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001484 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001485
1486 Module *exe_module = m_target.GetExecutableModule().get();
1487 if (exe_module)
1488 {
1489 char exec_file_path[PATH_MAX];
1490 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1491 if (exe_module->GetFileSpec().Exists())
1492 {
1493 error = WillLaunch (exe_module);
1494 if (error.Success())
1495 {
Greg Claytond8c62532010-10-07 04:19:01 +00001496 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001497 // The args coming in should not contain the application name, the
1498 // lldb_private::Process class will add this in case the executable
1499 // gets resolved to a different file than was given on the command
1500 // line (like when an applicaiton bundle is specified and will
1501 // resolve to the contained exectuable file, or the file given was
1502 // a symlink or other file system link that resolves to a different
1503 // file).
1504
1505 // Get the resolved exectuable path
1506
1507 // Make a new argument vector
1508 std::vector<const char *> exec_path_plus_argv;
1509 // Append the resolved executable path
1510 exec_path_plus_argv.push_back (exec_file_path);
1511
1512 // Push all args if there are any
1513 if (argv)
1514 {
1515 for (int i = 0; argv[i]; ++i)
1516 exec_path_plus_argv.push_back(argv[i]);
1517 }
1518
1519 // Push a NULL to terminate the args.
1520 exec_path_plus_argv.push_back(NULL);
1521
1522 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001523 error = DoLaunch (exe_module,
1524 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1525 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001526 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001527 stdin_path,
1528 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001529 stderr_path,
1530 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001531
1532 if (error.Fail())
1533 {
1534 if (GetID() != LLDB_INVALID_PROCESS_ID)
1535 {
1536 SetID (LLDB_INVALID_PROCESS_ID);
1537 const char *error_string = error.AsCString();
1538 if (error_string == NULL)
1539 error_string = "launch failed";
1540 SetExitStatus (-1, error_string);
1541 }
1542 }
1543 else
1544 {
1545 EventSP event_sp;
1546 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1547
1548 if (state == eStateStopped || state == eStateCrashed)
1549 {
1550 DidLaunch ();
1551
1552 // This delays passing the stopped event to listeners till DidLaunch gets
1553 // a chance to complete...
1554 HandlePrivateEvent (event_sp);
1555 StartPrivateStateThread ();
1556 }
1557 else if (state == eStateExited)
1558 {
1559 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1560 // not likely to work, and return an invalid pid.
1561 HandlePrivateEvent (event_sp);
1562 }
1563 }
1564 }
1565 }
1566 else
1567 {
1568 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1569 }
1570 }
1571 return error;
1572}
1573
1574Error
1575Process::CompleteAttach ()
1576{
1577 Error error;
Greg Claytonc1d37752010-10-18 01:45:30 +00001578
1579 if (GetID() == LLDB_INVALID_PROCESS_ID)
1580 {
1581 error.SetErrorString("no process");
1582 }
1583
Chris Lattner24943d22010-06-08 16:52:24 +00001584 EventSP event_sp;
1585 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1586 if (state == eStateStopped || state == eStateCrashed)
1587 {
1588 DidAttach ();
Jim Ingham7508e732010-08-09 23:31:02 +00001589 // Figure out which one is the executable, and set that in our target:
1590 ModuleList &modules = GetTarget().GetImages();
1591
1592 size_t num_modules = modules.GetSize();
1593 for (int i = 0; i < num_modules; i++)
1594 {
1595 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1596 if (module_sp->IsExecutable())
1597 {
1598 ModuleSP exec_module = GetTarget().GetExecutableModule();
1599 if (!exec_module || exec_module != module_sp)
1600 {
1601
1602 GetTarget().SetExecutableModule (module_sp, false);
1603 }
1604 break;
1605 }
1606 }
Chris Lattner24943d22010-06-08 16:52:24 +00001607
1608 // This delays passing the stopped event to listeners till DidLaunch gets
1609 // a chance to complete...
1610 HandlePrivateEvent(event_sp);
1611 StartPrivateStateThread();
1612 }
1613 else
1614 {
1615 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1616 // not likely to work, and return an invalid pid.
1617 if (state == eStateExited)
1618 HandlePrivateEvent (event_sp);
1619 error.SetErrorStringWithFormat("invalid state after attach: %s",
1620 lldb_private::StateAsCString(state));
1621 }
1622 return error;
1623}
1624
1625Error
1626Process::Attach (lldb::pid_t attach_pid)
1627{
1628
1629 m_target_triple.Clear();
1630 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001631 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001632
Jim Ingham7508e732010-08-09 23:31:02 +00001633 // Find the process and its architecture. Make sure it matches the architecture
1634 // of the current Target, and if not adjust it.
1635
1636 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1637 if (attach_spec != GetTarget().GetArchitecture())
1638 {
1639 // Set the architecture on the target.
1640 GetTarget().SetArchitecture(attach_spec);
1641 }
1642
Greg Clayton54e7afa2010-07-09 20:39:50 +00001643 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001644 if (error.Success())
1645 {
Greg Claytond8c62532010-10-07 04:19:01 +00001646 SetPublicState (eStateAttaching);
1647
Greg Clayton54e7afa2010-07-09 20:39:50 +00001648 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001649 if (error.Success())
1650 {
1651 error = CompleteAttach();
1652 }
1653 else
1654 {
1655 if (GetID() != LLDB_INVALID_PROCESS_ID)
1656 {
1657 SetID (LLDB_INVALID_PROCESS_ID);
1658 const char *error_string = error.AsCString();
1659 if (error_string == NULL)
1660 error_string = "attach failed";
1661
1662 SetExitStatus(-1, error_string);
1663 }
1664 }
1665 }
1666 return error;
1667}
1668
1669Error
1670Process::Attach (const char *process_name, bool wait_for_launch)
1671{
1672 m_target_triple.Clear();
1673 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001674 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001675
1676 // Find the process and its architecture. Make sure it matches the architecture
1677 // of the current Target, and if not adjust it.
1678
Jim Inghamea294182010-08-17 21:54:19 +00001679 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001680 {
Jim Inghamea294182010-08-17 21:54:19 +00001681 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001682 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001683 {
1684 // Set the architecture on the target.
1685 GetTarget().SetArchitecture(attach_spec);
1686 }
Jim Ingham7508e732010-08-09 23:31:02 +00001687 }
Jim Inghamea294182010-08-17 21:54:19 +00001688
Greg Clayton54e7afa2010-07-09 20:39:50 +00001689 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001690 if (error.Success())
1691 {
Greg Claytond8c62532010-10-07 04:19:01 +00001692 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001693 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001694 if (error.Fail())
1695 {
1696 if (GetID() != LLDB_INVALID_PROCESS_ID)
1697 {
1698 SetID (LLDB_INVALID_PROCESS_ID);
1699 const char *error_string = error.AsCString();
1700 if (error_string == NULL)
1701 error_string = "attach failed";
1702
1703 SetExitStatus(-1, error_string);
1704 }
1705 }
1706 else
1707 {
1708 error = CompleteAttach();
1709 }
1710 }
1711 return error;
1712}
1713
1714Error
1715Process::Resume ()
1716{
Greg Claytone005f2c2010-11-06 01:53:30 +00001717 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001718 if (log)
1719 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1720
1721 Error error (WillResume());
1722 // Tell the process it is about to resume before the thread list
1723 if (error.Success())
1724 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001725 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001726 // can let all of our threads know that they are about to be
1727 // resumed. Threads will each be called with
1728 // Thread::WillResume(StateType) where StateType contains the state
1729 // that they are supposed to have when the process is resumed
1730 // (suspended/running/stepping). Threads should also check
1731 // their resume signal in lldb::Thread::GetResumeSignal()
1732 // to see if they are suppoed to start back up with a signal.
1733 if (m_thread_list.WillResume())
1734 {
1735 error = DoResume();
1736 if (error.Success())
1737 {
1738 DidResume();
1739 m_thread_list.DidResume();
1740 }
1741 }
1742 else
1743 {
1744 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1745 }
1746 }
1747 return error;
1748}
1749
1750Error
1751Process::Halt ()
1752{
1753 Error error (WillHalt());
1754
1755 if (error.Success())
1756 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001757
1758 bool caused_stop = false;
1759 EventSP event_sp;
1760
1761 // Pause our private state thread so we can ensure no one else eats
1762 // the stop event out from under us.
1763 PausePrivateStateThread();
1764
1765 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001766 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001767 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001768 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001769 // If "caused_stop" is true, then DoHalt stopped the process. If
1770 // "caused_stop" is false, the process was already stopped.
1771 // If the DoHalt caused the process to stop, then we want to catch
1772 // this event and set the interrupted bool to true before we pass
1773 // this along so clients know that the process was interrupted by
1774 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001775 if (caused_stop)
1776 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001777 // Wait for 2 seconds for the process to stop.
1778 TimeValue timeout_time;
1779 timeout_time = TimeValue::Now();
Greg Clayton72e1c782011-01-22 23:43:18 +00001780 timeout_time.OffsetWithSeconds(1);
Greg Clayton20d338f2010-11-18 05:57:03 +00001781 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1782
1783 if (state == eStateInvalid)
1784 {
1785 // We timeout out and didn't get a stop event...
1786 error.SetErrorString ("Halt timed out.");
1787 }
1788 else
1789 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001790 if (StateIsStoppedState (state))
1791 {
1792 // We caused the process to interrupt itself, so mark this
1793 // as such in the stop event so clients can tell an interrupted
1794 // process from a natural stop
1795 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1796 }
1797 else
1798 {
1799 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1800 if (log)
1801 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1802 error.SetErrorString ("Did not get stopped event after halt.");
1803 }
1804 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001805 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001806 DidHalt();
1807
Jim Ingham3ae449a2010-11-17 02:32:00 +00001808 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001809 // Resume our private state thread before we post the event (if any)
1810 ResumePrivateStateThread();
1811
1812 // Post any event we might have consumed. If all goes well, we will have
1813 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001814 // bool in the event. Post it to the private event queue and that will end up
1815 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001816 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001817 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001818
Chris Lattner24943d22010-06-08 16:52:24 +00001819 }
1820 return error;
1821}
1822
1823Error
1824Process::Detach ()
1825{
1826 Error error (WillDetach());
1827
1828 if (error.Success())
1829 {
1830 DisableAllBreakpointSites();
1831 error = DoDetach();
1832 if (error.Success())
1833 {
1834 DidDetach();
1835 StopPrivateStateThread();
1836 }
1837 }
1838 return error;
1839}
1840
1841Error
1842Process::Destroy ()
1843{
1844 Error error (WillDestroy());
1845 if (error.Success())
1846 {
1847 DisableAllBreakpointSites();
1848 error = DoDestroy();
1849 if (error.Success())
1850 {
1851 DidDestroy();
1852 StopPrivateStateThread();
1853 }
Caroline Tice861efb32010-11-16 05:07:41 +00001854 m_stdio_communication.StopReadThread();
1855 m_stdio_communication.Disconnect();
1856 if (m_process_input_reader && m_process_input_reader->IsActive())
1857 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1858 if (m_process_input_reader)
1859 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001860 }
1861 return error;
1862}
1863
1864Error
1865Process::Signal (int signal)
1866{
1867 Error error (WillSignal());
1868 if (error.Success())
1869 {
1870 error = DoSignal(signal);
1871 if (error.Success())
1872 DidSignal();
1873 }
1874 return error;
1875}
1876
1877UnixSignals &
1878Process::GetUnixSignals ()
1879{
1880 return m_unix_signals;
1881}
1882
1883Target &
1884Process::GetTarget ()
1885{
1886 return m_target;
1887}
1888
1889const Target &
1890Process::GetTarget () const
1891{
1892 return m_target;
1893}
1894
1895uint32_t
1896Process::GetAddressByteSize()
1897{
Greg Clayton20d338f2010-11-18 05:57:03 +00001898 if (m_addr_byte_size == 0)
1899 return m_target.GetArchitecture().GetAddressByteSize();
1900 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001901}
1902
1903bool
1904Process::ShouldBroadcastEvent (Event *event_ptr)
1905{
1906 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1907 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001908 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001909
1910 switch (state)
1911 {
1912 case eStateAttaching:
1913 case eStateLaunching:
1914 case eStateDetached:
1915 case eStateExited:
1916 case eStateUnloaded:
1917 // These events indicate changes in the state of the debugging session, always report them.
1918 return_value = true;
1919 break;
1920 case eStateInvalid:
1921 // We stopped for no apparent reason, don't report it.
1922 return_value = false;
1923 break;
1924 case eStateRunning:
1925 case eStateStepping:
1926 // If we've started the target running, we handle the cases where we
1927 // are already running and where there is a transition from stopped to
1928 // running differently.
1929 // running -> running: Automatically suppress extra running events
1930 // stopped -> running: Report except when there is one or more no votes
1931 // and no yes votes.
1932 SynchronouslyNotifyStateChanged (state);
1933 switch (m_public_state.GetValue())
1934 {
1935 case eStateRunning:
1936 case eStateStepping:
1937 // We always suppress multiple runnings with no PUBLIC stop in between.
1938 return_value = false;
1939 break;
1940 default:
1941 // TODO: make this work correctly. For now always report
1942 // run if we aren't running so we don't miss any runnning
1943 // events. If I run the lldb/test/thread/a.out file and
1944 // break at main.cpp:58, run and hit the breakpoints on
1945 // multiple threads, then somehow during the stepping over
1946 // of all breakpoints no run gets reported.
1947 return_value = true;
1948
1949 // This is a transition from stop to run.
1950 switch (m_thread_list.ShouldReportRun (event_ptr))
1951 {
1952 case eVoteYes:
1953 case eVoteNoOpinion:
1954 return_value = true;
1955 break;
1956 case eVoteNo:
1957 return_value = false;
1958 break;
1959 }
1960 break;
1961 }
1962 break;
1963 case eStateStopped:
1964 case eStateCrashed:
1965 case eStateSuspended:
1966 {
1967 // We've stopped. First see if we're going to restart the target.
1968 // If we are going to stop, then we always broadcast the event.
1969 // 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 +00001970 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001971 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001972 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001973 if (log)
1974 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001975 return true;
1976 }
1977 else
1978 {
Chris Lattner24943d22010-06-08 16:52:24 +00001979 RefreshStateAfterStop ();
1980
1981 if (m_thread_list.ShouldStop (event_ptr) == false)
1982 {
1983 switch (m_thread_list.ShouldReportStop (event_ptr))
1984 {
1985 case eVoteYes:
1986 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001987 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001988 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001989 case eVoteNo:
1990 return_value = false;
1991 break;
1992 }
1993
1994 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00001995 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00001996 Resume ();
1997 }
1998 else
1999 {
2000 return_value = true;
2001 SynchronouslyNotifyStateChanged (state);
2002 }
2003 }
2004 }
2005 }
2006
2007 if (log)
2008 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2009 return return_value;
2010}
2011
2012//------------------------------------------------------------------
2013// Thread Queries
2014//------------------------------------------------------------------
2015
2016ThreadList &
2017Process::GetThreadList ()
2018{
2019 return m_thread_list;
2020}
2021
2022const ThreadList &
2023Process::GetThreadList () const
2024{
2025 return m_thread_list;
2026}
2027
2028
2029bool
2030Process::StartPrivateStateThread ()
2031{
Greg Claytone005f2c2010-11-06 01:53:30 +00002032 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002033
2034 if (log)
2035 log->Printf ("Process::%s ( )", __FUNCTION__);
2036
2037 // Create a thread that watches our internal state and controls which
2038 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002039 char thread_name[1024];
2040 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2041 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002042 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2043}
2044
2045void
2046Process::PausePrivateStateThread ()
2047{
2048 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2049}
2050
2051void
2052Process::ResumePrivateStateThread ()
2053{
2054 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2055}
2056
2057void
2058Process::StopPrivateStateThread ()
2059{
2060 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2061}
2062
2063void
2064Process::ControlPrivateStateThread (uint32_t signal)
2065{
Greg Claytone005f2c2010-11-06 01:53:30 +00002066 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002067
2068 assert (signal == eBroadcastInternalStateControlStop ||
2069 signal == eBroadcastInternalStateControlPause ||
2070 signal == eBroadcastInternalStateControlResume);
2071
2072 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002073 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002074
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002075 // Signal the private state thread. First we should copy this is case the
2076 // thread starts exiting since the private state thread will NULL this out
2077 // when it exits
2078 const lldb::thread_t private_state_thread = m_private_state_thread;
2079 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner24943d22010-06-08 16:52:24 +00002080 {
2081 TimeValue timeout_time;
2082 bool timed_out;
2083
2084 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2085
2086 timeout_time = TimeValue::Now();
2087 timeout_time.OffsetWithSeconds(2);
2088 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2089 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2090
2091 if (signal == eBroadcastInternalStateControlStop)
2092 {
2093 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002094 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002095
2096 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002097 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002098 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002099 }
2100 }
2101}
2102
2103void
2104Process::HandlePrivateEvent (EventSP &event_sp)
2105{
Greg Claytone005f2c2010-11-06 01:53:30 +00002106 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002107 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2108 // See if we should broadcast this state to external clients?
2109 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2110 if (log)
2111 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2112
2113 if (should_broadcast)
2114 {
2115 if (log)
2116 {
2117 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2118 }
Caroline Tice861efb32010-11-16 05:07:41 +00002119 if (StateIsRunningState (internal_state))
2120 PushProcessInputReader ();
2121 else
2122 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002123 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2124 BroadcastEvent (event_sp);
2125 }
2126 else
2127 {
2128 if (log)
2129 {
2130 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2131 }
2132 }
2133}
2134
2135void *
2136Process::PrivateStateThread (void *arg)
2137{
2138 Process *proc = static_cast<Process*> (arg);
2139 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002140 return result;
2141}
2142
2143void *
2144Process::RunPrivateStateThread ()
2145{
2146 bool control_only = false;
2147 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2148
Greg Claytone005f2c2010-11-06 01:53:30 +00002149 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002150 if (log)
2151 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2152
2153 bool exit_now = false;
2154 while (!exit_now)
2155 {
2156 EventSP event_sp;
2157 WaitForEventsPrivate (NULL, event_sp, control_only);
2158 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2159 {
2160 switch (event_sp->GetType())
2161 {
2162 case eBroadcastInternalStateControlStop:
2163 exit_now = true;
2164 continue; // Go to next loop iteration so we exit without
2165 break; // doing any internal state managment below
2166
2167 case eBroadcastInternalStateControlPause:
2168 control_only = true;
2169 break;
2170
2171 case eBroadcastInternalStateControlResume:
2172 control_only = false;
2173 break;
2174 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002175
Jim Ingham3ae449a2010-11-17 02:32:00 +00002176 if (log)
2177 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2178
Chris Lattner24943d22010-06-08 16:52:24 +00002179 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002180 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002181 }
2182
2183
2184 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2185
2186 if (internal_state != eStateInvalid)
2187 {
2188 HandlePrivateEvent (event_sp);
2189 }
2190
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002191 if (internal_state == eStateInvalid ||
2192 internal_state == eStateExited ||
2193 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002194 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002195 if (log)
2196 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2197
Chris Lattner24943d22010-06-08 16:52:24 +00002198 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002199 }
Chris Lattner24943d22010-06-08 16:52:24 +00002200 }
2201
Caroline Tice926060e2010-10-29 21:48:37 +00002202 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002203 if (log)
2204 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2205
Greg Claytona4881d02011-01-22 07:12:45 +00002206 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2207 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002208 return NULL;
2209}
2210
Chris Lattner24943d22010-06-08 16:52:24 +00002211//------------------------------------------------------------------
2212// Process Event Data
2213//------------------------------------------------------------------
2214
2215Process::ProcessEventData::ProcessEventData () :
2216 EventData (),
2217 m_process_sp (),
2218 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002219 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002220 m_update_state (false),
2221 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002222{
2223}
2224
2225Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2226 EventData (),
2227 m_process_sp (process_sp),
2228 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002229 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002230 m_update_state (false),
2231 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002232{
2233}
2234
2235Process::ProcessEventData::~ProcessEventData()
2236{
2237}
2238
2239const ConstString &
2240Process::ProcessEventData::GetFlavorString ()
2241{
2242 static ConstString g_flavor ("Process::ProcessEventData");
2243 return g_flavor;
2244}
2245
2246const ConstString &
2247Process::ProcessEventData::GetFlavor () const
2248{
2249 return ProcessEventData::GetFlavorString ();
2250}
2251
Chris Lattner24943d22010-06-08 16:52:24 +00002252void
2253Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2254{
2255 // This function gets called twice for each event, once when the event gets pulled
2256 // off of the private process event queue, and once when it gets pulled off of
2257 // the public event queue. m_update_state is used to distinguish these
2258 // two cases; it is false when we're just pulling it off for private handling,
2259 // and we don't want to do the breakpoint command handling then.
2260
2261 if (!m_update_state)
2262 return;
2263
2264 m_process_sp->SetPublicState (m_state);
2265
2266 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2267 if (m_state == eStateStopped && ! m_restarted)
2268 {
2269 int num_threads = m_process_sp->GetThreadList().GetSize();
2270 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002271
Chris Lattner24943d22010-06-08 16:52:24 +00002272 for (idx = 0; idx < num_threads; ++idx)
2273 {
2274 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2275
Jim Ingham6297a3a2010-10-20 00:39:53 +00002276 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2277 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002278 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002279 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002280 }
2281 }
Greg Clayton643ee732010-08-04 01:40:35 +00002282
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002283 // The stop action might restart the target. If it does, then we want to mark that in the
2284 // event so that whoever is receiving it will know to wait for the running event and reflect
2285 // that state appropriately.
2286
Chris Lattner24943d22010-06-08 16:52:24 +00002287 if (m_process_sp->GetPrivateState() == eStateRunning)
2288 SetRestarted(true);
2289 }
2290}
2291
2292void
2293Process::ProcessEventData::Dump (Stream *s) const
2294{
2295 if (m_process_sp)
2296 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2297
2298 s->Printf("state = %s", StateAsCString(GetState()));;
2299}
2300
2301const Process::ProcessEventData *
2302Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2303{
2304 if (event_ptr)
2305 {
2306 const EventData *event_data = event_ptr->GetData();
2307 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2308 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2309 }
2310 return NULL;
2311}
2312
2313ProcessSP
2314Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2315{
2316 ProcessSP process_sp;
2317 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2318 if (data)
2319 process_sp = data->GetProcessSP();
2320 return process_sp;
2321}
2322
2323StateType
2324Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2325{
2326 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2327 if (data == NULL)
2328 return eStateInvalid;
2329 else
2330 return data->GetState();
2331}
2332
2333bool
2334Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2335{
2336 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2337 if (data == NULL)
2338 return false;
2339 else
2340 return data->GetRestarted();
2341}
2342
2343void
2344Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2345{
2346 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2347 if (data != NULL)
2348 data->SetRestarted(new_value);
2349}
2350
2351bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002352Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2353{
2354 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2355 if (data == NULL)
2356 return false;
2357 else
2358 return data->GetInterrupted ();
2359}
2360
2361void
2362Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2363{
2364 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2365 if (data != NULL)
2366 data->SetInterrupted(new_value);
2367}
2368
2369bool
Chris Lattner24943d22010-06-08 16:52:24 +00002370Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2371{
2372 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2373 if (data)
2374 {
2375 data->SetUpdateStateOnRemoval();
2376 return true;
2377 }
2378 return false;
2379}
2380
Chris Lattner24943d22010-06-08 16:52:24 +00002381Target *
2382Process::CalculateTarget ()
2383{
2384 return &m_target;
2385}
2386
2387Process *
2388Process::CalculateProcess ()
2389{
2390 return this;
2391}
2392
2393Thread *
2394Process::CalculateThread ()
2395{
2396 return NULL;
2397}
2398
2399StackFrame *
2400Process::CalculateStackFrame ()
2401{
2402 return NULL;
2403}
2404
2405void
Greg Claytona830adb2010-10-04 01:05:56 +00002406Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002407{
2408 exe_ctx.target = &m_target;
2409 exe_ctx.process = this;
2410 exe_ctx.thread = NULL;
2411 exe_ctx.frame = NULL;
2412}
2413
2414lldb::ProcessSP
2415Process::GetSP ()
2416{
2417 return GetTarget().GetProcessSP();
2418}
2419
Jim Ingham7508e732010-08-09 23:31:02 +00002420uint32_t
2421Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2422{
2423 return 0;
2424}
2425
2426ArchSpec
2427Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2428{
2429 return Host::GetArchSpecForExistingProcess (pid);
2430}
2431
2432ArchSpec
2433Process::GetArchSpecForExistingProcess (const char *process_name)
2434{
2435 return Host::GetArchSpecForExistingProcess (process_name);
2436}
2437
Caroline Tice861efb32010-11-16 05:07:41 +00002438void
2439Process::AppendSTDOUT (const char * s, size_t len)
2440{
Greg Clayton20d338f2010-11-18 05:57:03 +00002441 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002442 m_stdout_data.append (s, len);
2443
Greg Claytonb3781332010-12-05 19:16:56 +00002444 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002445}
2446
2447void
2448Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2449{
2450 Process *process = (Process *) baton;
2451 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2452}
2453
2454size_t
2455Process::ProcessInputReaderCallback (void *baton,
2456 InputReader &reader,
2457 lldb::InputReaderAction notification,
2458 const char *bytes,
2459 size_t bytes_len)
2460{
2461 Process *process = (Process *) baton;
2462
2463 switch (notification)
2464 {
2465 case eInputReaderActivate:
2466 break;
2467
2468 case eInputReaderDeactivate:
2469 break;
2470
2471 case eInputReaderReactivate:
2472 break;
2473
2474 case eInputReaderGotToken:
2475 {
2476 Error error;
2477 process->PutSTDIN (bytes, bytes_len, error);
2478 }
2479 break;
2480
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002481 case eInputReaderInterrupt:
2482 process->Halt ();
2483 break;
2484
2485 case eInputReaderEndOfFile:
2486 process->AppendSTDOUT ("^D", 2);
2487 break;
2488
Caroline Tice861efb32010-11-16 05:07:41 +00002489 case eInputReaderDone:
2490 break;
2491
2492 }
2493
2494 return bytes_len;
2495}
2496
2497void
2498Process::ResetProcessInputReader ()
2499{
2500 m_process_input_reader.reset();
2501}
2502
2503void
2504Process::SetUpProcessInputReader (int file_descriptor)
2505{
2506 // First set up the Read Thread for reading/handling process I/O
2507
2508 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2509
2510 if (conn_ap.get())
2511 {
2512 m_stdio_communication.SetConnection (conn_ap.release());
2513 if (m_stdio_communication.IsConnected())
2514 {
2515 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2516 m_stdio_communication.StartReadThread();
2517
2518 // Now read thread is set up, set up input reader.
2519
2520 if (!m_process_input_reader.get())
2521 {
2522 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2523 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2524 this,
2525 eInputReaderGranularityByte,
2526 NULL,
2527 NULL,
2528 false));
2529
2530 if (err.Fail())
2531 m_process_input_reader.reset();
2532 }
2533 }
2534 }
2535}
2536
2537void
2538Process::PushProcessInputReader ()
2539{
2540 if (m_process_input_reader && !m_process_input_reader->IsActive())
2541 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2542}
2543
2544void
2545Process::PopProcessInputReader ()
2546{
2547 if (m_process_input_reader && m_process_input_reader->IsActive())
2548 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2549}
2550
Greg Clayton990de7b2010-11-18 23:32:35 +00002551
2552void
2553Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002554{
Greg Clayton990de7b2010-11-18 23:32:35 +00002555 UserSettingsControllerSP &usc = GetSettingsController();
2556 usc.reset (new SettingsController);
2557 UserSettingsController::InitializeSettingsController (usc,
2558 SettingsController::global_settings_table,
2559 SettingsController::instance_settings_table);
2560}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002561
Greg Clayton990de7b2010-11-18 23:32:35 +00002562void
2563Process::Terminate ()
2564{
2565 UserSettingsControllerSP &usc = GetSettingsController();
2566 UserSettingsController::FinalizeSettingsController (usc);
2567 usc.reset();
2568}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002569
Greg Clayton990de7b2010-11-18 23:32:35 +00002570UserSettingsControllerSP &
2571Process::GetSettingsController ()
2572{
2573 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002574 return g_settings_controller;
2575}
2576
Caroline Tice1ebef442010-09-27 00:30:10 +00002577void
2578Process::UpdateInstanceName ()
2579{
2580 ModuleSP module_sp = GetTarget().GetExecutableModule();
2581 if (module_sp)
2582 {
2583 StreamString sstr;
2584 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2585
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002586 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002587 sstr.GetData());
2588 }
2589}
2590
Greg Clayton427f2902010-12-14 02:59:59 +00002591ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002592Process::RunThreadPlan (ExecutionContext &exe_ctx,
2593 lldb::ThreadPlanSP &thread_plan_sp,
2594 bool stop_others,
2595 bool try_all_threads,
2596 bool discard_on_error,
2597 uint32_t single_thread_timeout_usec,
2598 Stream &errors)
2599{
2600 ExecutionResults return_value = eExecutionSetupError;
2601
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002602 if (thread_plan_sp.get() == NULL)
2603 {
2604 errors.Printf("RunThreadPlan called with empty thread plan.");
2605 return lldb::eExecutionSetupError;
2606 }
2607
Jim Ingham360f53f2010-11-30 02:22:11 +00002608 // Save this value for restoration of the execution context after we run
2609 uint32_t tid = exe_ctx.thread->GetIndexID();
2610
2611 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2612 // so we should arrange to reset them as well.
2613
2614 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2615 lldb::StackFrameSP selected_frame_sp;
2616
2617 uint32_t selected_tid;
2618 if (selected_thread_sp != NULL)
2619 {
2620 selected_tid = selected_thread_sp->GetIndexID();
2621 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2622 }
2623 else
2624 {
2625 selected_tid = LLDB_INVALID_THREAD_ID;
2626 }
2627
2628 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2629
Jim Ingham6ae318c2011-01-23 21:14:08 +00002630 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham360f53f2010-11-30 02:22:11 +00002631 exe_ctx.process->HijackProcessEvents(&listener);
2632
Jim Ingham6ae318c2011-01-23 21:14:08 +00002633 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002634 if (log)
2635 {
2636 StreamString s;
2637 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham6ae318c2011-01-23 21:14:08 +00002638 log->Printf ("Resuming thread %u - 0x%4.4x to run thread plan \"%s\".", exe_ctx.thread->GetIndexID(), exe_ctx.thread->GetID(), s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002639 }
2640
Jim Ingham360f53f2010-11-30 02:22:11 +00002641 Error resume_error = exe_ctx.process->Resume ();
2642 if (!resume_error.Success())
2643 {
2644 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2645 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002646 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002647 }
2648
2649 // We need to call the function synchronously, so spin waiting for it to return.
2650 // If we get interrupted while executing, we're going to lose our context, and
2651 // won't be able to gather the result at this point.
2652 // We set the timeout AFTER the resume, since the resume takes some time and we
2653 // don't want to charge that to the timeout.
2654
2655 TimeValue* timeout_ptr = NULL;
2656 TimeValue real_timeout;
2657
2658 if (single_thread_timeout_usec != 0)
2659 {
2660 real_timeout = TimeValue::Now();
2661 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2662 timeout_ptr = &real_timeout;
2663 }
2664
Jim Ingham360f53f2010-11-30 02:22:11 +00002665 while (1)
2666 {
2667 lldb::EventSP event_sp;
2668 lldb::StateType stop_state = lldb::eStateInvalid;
2669 // Now wait for the process to stop again:
2670 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2671
2672 if (!got_event)
2673 {
2674 // Right now this is the only way to tell we've timed out...
2675 // We should interrupt the process here...
2676 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002677 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002678 if (try_all_threads)
2679 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2680 single_thread_timeout_usec);
2681 else
2682 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2683 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002684 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002685
Jim Inghamc556b462011-01-22 01:30:53 +00002686 Error halt_error = exe_ctx.process->Halt();
2687
2688 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002689 {
2690 timeout_ptr = NULL;
2691 if (log)
2692 log->Printf ("Halt succeeded.");
2693
2694 // Between the time that we got the timeout and the time we halted, but target
2695 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2696 // timeout to
2697 got_event = listener.WaitForEvent(NULL, event_sp);
2698
2699 if (got_event)
2700 {
2701 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2702 if (log)
2703 {
2704 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2705 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2706 log->Printf (" Event was the Halt interruption event.");
2707 }
2708
2709 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2710 {
2711 if (log)
2712 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002713 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002714 break;
2715 }
2716
2717 if (try_all_threads
2718 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2719 {
2720
2721 thread_plan_sp->SetStopOthers (false);
2722 if (log)
2723 log->Printf ("About to resume.");
2724
2725 exe_ctx.process->Resume();
2726 continue;
2727 }
2728 else
2729 {
2730 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002731 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002732 }
2733 }
2734 }
Jim Inghamc556b462011-01-22 01:30:53 +00002735 else
2736 {
2737
2738 if (log)
2739 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2740 halt_error.AsCString());
Jim Ingham6ae318c2011-01-23 21:14:08 +00002741 abort();
Jim Inghamc556b462011-01-22 01:30:53 +00002742
Jim Ingham6ae318c2011-01-23 21:14:08 +00002743 if (single_thread_timeout_usec != 0)
2744 {
2745 real_timeout = TimeValue::Now();
2746 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2747 timeout_ptr = &real_timeout;
2748 }
2749 continue;
Jim Inghamc556b462011-01-22 01:30:53 +00002750 }
2751
Jim Ingham360f53f2010-11-30 02:22:11 +00002752 }
2753
2754 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2755 if (log)
2756 log->Printf("Got event: %s.", StateAsCString(stop_state));
2757
2758 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2759 continue;
2760
2761 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2762 {
Greg Clayton427f2902010-12-14 02:59:59 +00002763 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002764 break;
2765 }
2766 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2767 {
Greg Clayton427f2902010-12-14 02:59:59 +00002768 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002769 break;
2770 }
2771 else
2772 {
2773 if (log)
2774 {
2775 StreamString s;
Jim Inghamc556b462011-01-22 01:30:53 +00002776 if (event_sp)
2777 event_sp->Dump (&s);
2778 else
2779 {
2780 log->Printf ("Stop event that interrupted us is NULL.");
2781 }
2782
Jim Ingham360f53f2010-11-30 02:22:11 +00002783 StreamString ts;
2784
2785 const char *event_explanation;
2786
2787 do
2788 {
2789 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2790
2791 if (!event_data)
2792 {
2793 event_explanation = "<no event data>";
2794 break;
2795 }
2796
2797 Process *process = event_data->GetProcessSP().get();
2798
2799 if (!process)
2800 {
2801 event_explanation = "<no process>";
2802 break;
2803 }
2804
2805 ThreadList &thread_list = process->GetThreadList();
2806
2807 uint32_t num_threads = thread_list.GetSize();
2808 uint32_t thread_index;
2809
2810 ts.Printf("<%u threads> ", num_threads);
2811
2812 for (thread_index = 0;
2813 thread_index < num_threads;
2814 ++thread_index)
2815 {
2816 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2817
2818 if (!thread)
2819 {
2820 ts.Printf("<?> ");
2821 continue;
2822 }
2823
Jim Inghamc556b462011-01-22 01:30:53 +00002824 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002825 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002826
2827 if (register_context)
2828 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2829 else
2830 ts.Printf("[ip unknown] ");
2831
2832 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2833 if (stop_info_sp)
2834 {
2835 const char *stop_desc = stop_info_sp->GetDescription();
2836 if (stop_desc)
2837 ts.PutCString (stop_desc);
2838 }
2839 ts.Printf(">");
2840 }
2841
2842 event_explanation = ts.GetData();
2843 } while (0);
2844
Jim Inghamc556b462011-01-22 01:30:53 +00002845 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2846 if (!GetThreadList().ShouldStop(event_sp.get()))
2847 {
2848 if (log)
2849 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2850 s.GetData(), event_explanation);
2851 if (single_thread_timeout_usec != 0)
2852 {
2853 real_timeout = TimeValue::Now();
2854 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2855 timeout_ptr = &real_timeout;
2856 }
2857
2858 continue;
2859 }
2860 else
2861 {
2862 if (log)
2863 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2864 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002865 }
2866
2867 if (discard_on_error && thread_plan_sp)
2868 {
2869 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2870 }
Greg Clayton427f2902010-12-14 02:59:59 +00002871 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002872 break;
2873 }
2874 }
2875
2876 if (exe_ctx.process)
2877 exe_ctx.process->RestoreProcessEvents ();
2878
2879 // Thread we ran the function in may have gone away because we ran the target
2880 // Check that it's still there.
2881 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2882 if (exe_ctx.thread)
2883 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2884
2885 // Also restore the current process'es selected frame & thread, since this function calling may
2886 // be done behind the user's back.
2887
2888 if (selected_tid != LLDB_INVALID_THREAD_ID)
2889 {
2890 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2891 {
2892 // We were able to restore the selected thread, now restore the frame:
2893 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2894 }
2895 }
2896
2897 return return_value;
2898}
2899
2900const char *
2901Process::ExecutionResultAsCString (ExecutionResults result)
2902{
2903 const char *result_name;
2904
2905 switch (result)
2906 {
Greg Clayton427f2902010-12-14 02:59:59 +00002907 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002908 result_name = "eExecutionCompleted";
2909 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002910 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002911 result_name = "eExecutionDiscarded";
2912 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002913 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002914 result_name = "eExecutionInterrupted";
2915 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002916 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002917 result_name = "eExecutionSetupError";
2918 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002919 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002920 result_name = "eExecutionTimedOut";
2921 break;
2922 }
2923 return result_name;
2924}
2925
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002926//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002927// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002928//--------------------------------------------------------------
2929
Greg Claytond0a5a232010-09-19 02:33:57 +00002930Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002931 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002932{
Greg Clayton638351a2010-12-04 00:10:17 +00002933 m_default_settings.reset (new ProcessInstanceSettings (*this,
2934 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002935 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002936}
2937
Greg Claytond0a5a232010-09-19 02:33:57 +00002938Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002939{
2940}
2941
2942lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002943Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002944{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002945 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2946 false,
2947 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002948 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2949 return new_settings_sp;
2950}
2951
2952//--------------------------------------------------------------
2953// class ProcessInstanceSettings
2954//--------------------------------------------------------------
2955
Greg Clayton638351a2010-12-04 00:10:17 +00002956ProcessInstanceSettings::ProcessInstanceSettings
2957(
2958 UserSettingsController &owner,
2959 bool live_instance,
2960 const char *name
2961) :
2962 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002963 m_run_args (),
2964 m_env_vars (),
2965 m_input_path (),
2966 m_output_path (),
2967 m_error_path (),
2968 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002969 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002970 m_disable_stdio (false),
2971 m_inherit_host_env (true),
2972 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002973{
Caroline Tice396704b2010-09-09 18:26:37 +00002974 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2975 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2976 // 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 +00002977 // This is true for CreateInstanceName() too.
2978
2979 if (GetInstanceName () == InstanceSettings::InvalidName())
2980 {
2981 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2982 m_owner.RegisterInstanceSettings (this);
2983 }
Caroline Tice396704b2010-09-09 18:26:37 +00002984
2985 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002986 {
2987 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2988 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00002989 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002990 }
2991}
2992
2993ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002994 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002995 m_run_args (rhs.m_run_args),
2996 m_env_vars (rhs.m_env_vars),
2997 m_input_path (rhs.m_input_path),
2998 m_output_path (rhs.m_output_path),
2999 m_error_path (rhs.m_error_path),
3000 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00003001 m_disable_aslr (rhs.m_disable_aslr),
3002 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003003{
3004 if (m_instance_name != InstanceSettings::GetDefaultName())
3005 {
3006 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3007 CopyInstanceSettings (pending_settings,false);
3008 m_owner.RemovePendingSettings (m_instance_name);
3009 }
3010}
3011
3012ProcessInstanceSettings::~ProcessInstanceSettings ()
3013{
3014}
3015
3016ProcessInstanceSettings&
3017ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3018{
3019 if (this != &rhs)
3020 {
3021 m_run_args = rhs.m_run_args;
3022 m_env_vars = rhs.m_env_vars;
3023 m_input_path = rhs.m_input_path;
3024 m_output_path = rhs.m_output_path;
3025 m_error_path = rhs.m_error_path;
3026 m_plugin = rhs.m_plugin;
3027 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003028 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003029 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003030 }
3031
3032 return *this;
3033}
3034
3035
3036void
3037ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3038 const char *index_value,
3039 const char *value,
3040 const ConstString &instance_name,
3041 const SettingEntry &entry,
3042 lldb::VarSetOperationType op,
3043 Error &err,
3044 bool pending)
3045{
3046 if (var_name == RunArgsVarName())
3047 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3048 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003049 {
3050 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003051 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003052 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003053 else if (var_name == InputPathVarName())
3054 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3055 else if (var_name == OutputPathVarName())
3056 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3057 else if (var_name == ErrorPathVarName())
3058 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3059 else if (var_name == PluginVarName())
3060 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003061 else if (var_name == InheritHostEnvVarName())
3062 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003063 else if (var_name == DisableASLRVarName())
3064 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003065 else if (var_name == DisableSTDIOVarName ())
3066 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003067}
3068
3069void
3070ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3071 bool pending)
3072{
3073 if (new_settings.get() == NULL)
3074 return;
3075
3076 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3077
3078 m_run_args = new_process_settings->m_run_args;
3079 m_env_vars = new_process_settings->m_env_vars;
3080 m_input_path = new_process_settings->m_input_path;
3081 m_output_path = new_process_settings->m_output_path;
3082 m_error_path = new_process_settings->m_error_path;
3083 m_plugin = new_process_settings->m_plugin;
3084 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003085 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003086}
3087
Caroline Ticebcb5b452010-09-20 21:37:42 +00003088bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003089ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3090 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003091 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003092 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003093{
3094 if (var_name == RunArgsVarName())
3095 {
3096 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003097 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003098 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3099 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003100 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003101 }
3102 else if (var_name == EnvVarsVarName())
3103 {
Greg Clayton638351a2010-12-04 00:10:17 +00003104 GetHostEnvironmentIfNeeded ();
3105
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003106 if (m_env_vars.size() > 0)
3107 {
3108 std::map<std::string, std::string>::iterator pos;
3109 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3110 {
3111 StreamString value_str;
3112 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3113 value.AppendString (value_str.GetData());
3114 }
3115 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003116 }
3117 else if (var_name == InputPathVarName())
3118 {
3119 value.AppendString (m_input_path.c_str());
3120 }
3121 else if (var_name == OutputPathVarName())
3122 {
3123 value.AppendString (m_output_path.c_str());
3124 }
3125 else if (var_name == ErrorPathVarName())
3126 {
3127 value.AppendString (m_error_path.c_str());
3128 }
3129 else if (var_name == PluginVarName())
3130 {
3131 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3132 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003133 else if (var_name == InheritHostEnvVarName())
3134 {
3135 if (m_inherit_host_env)
3136 value.AppendString ("true");
3137 else
3138 value.AppendString ("false");
3139 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003140 else if (var_name == DisableASLRVarName())
3141 {
3142 if (m_disable_aslr)
3143 value.AppendString ("true");
3144 else
3145 value.AppendString ("false");
3146 }
Caroline Ticebd666012010-12-03 18:46:09 +00003147 else if (var_name == DisableSTDIOVarName())
3148 {
3149 if (m_disable_stdio)
3150 value.AppendString ("true");
3151 else
3152 value.AppendString ("false");
3153 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003154 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003155 {
3156 if (err)
3157 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3158 return false;
3159 }
3160 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003161}
3162
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003163const ConstString
3164ProcessInstanceSettings::CreateInstanceName ()
3165{
3166 static int instance_count = 1;
3167 StreamString sstr;
3168
3169 sstr.Printf ("process_%d", instance_count);
3170 ++instance_count;
3171
3172 const ConstString ret_val (sstr.GetData());
3173 return ret_val;
3174}
3175
3176const ConstString &
3177ProcessInstanceSettings::RunArgsVarName ()
3178{
3179 static ConstString run_args_var_name ("run-args");
3180
3181 return run_args_var_name;
3182}
3183
3184const ConstString &
3185ProcessInstanceSettings::EnvVarsVarName ()
3186{
3187 static ConstString env_vars_var_name ("env-vars");
3188
3189 return env_vars_var_name;
3190}
3191
3192const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003193ProcessInstanceSettings::InheritHostEnvVarName ()
3194{
3195 static ConstString g_name ("inherit-env");
3196
3197 return g_name;
3198}
3199
3200const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003201ProcessInstanceSettings::InputPathVarName ()
3202{
3203 static ConstString input_path_var_name ("input-path");
3204
3205 return input_path_var_name;
3206}
3207
3208const ConstString &
3209ProcessInstanceSettings::OutputPathVarName ()
3210{
Caroline Tice87097232010-09-07 18:35:40 +00003211 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003212
3213 return output_path_var_name;
3214}
3215
3216const ConstString &
3217ProcessInstanceSettings::ErrorPathVarName ()
3218{
Caroline Tice87097232010-09-07 18:35:40 +00003219 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003220
3221 return error_path_var_name;
3222}
3223
3224const ConstString &
3225ProcessInstanceSettings::PluginVarName ()
3226{
3227 static ConstString plugin_var_name ("plugin");
3228
3229 return plugin_var_name;
3230}
3231
3232
3233const ConstString &
3234ProcessInstanceSettings::DisableASLRVarName ()
3235{
3236 static ConstString disable_aslr_var_name ("disable-aslr");
3237
3238 return disable_aslr_var_name;
3239}
3240
Caroline Ticebd666012010-12-03 18:46:09 +00003241const ConstString &
3242ProcessInstanceSettings::DisableSTDIOVarName ()
3243{
3244 static ConstString disable_stdio_var_name ("disable-stdio");
3245
3246 return disable_stdio_var_name;
3247}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003248
3249//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003250// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003251//--------------------------------------------------
3252
3253SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003254Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003255{
3256 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3257 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3258};
3259
3260
3261lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003262Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003263{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003264 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3265 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3266 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003267};
3268
3269SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003270Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003271{
Greg Clayton638351a2010-12-04 00:10:17 +00003272 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3273 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3274 { "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." },
3275 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003276 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3277 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3278 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3279 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003280 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3281 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3282 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003283};
3284
3285
Jim Ingham7508e732010-08-09 23:31:02 +00003286