blob: 3999f150bbab9377f422d50d99423927915a2c8b [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)
Greg Claytonb349adc2011-01-24 06:30:45 +00001404 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001405 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)
Jim Inghamac959662011-01-24 06:34:17 +00001719 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1720 m_stop_id,
1721 StateAsCString(m_public_state.GetValue()),
1722 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00001723
1724 Error error (WillResume());
1725 // Tell the process it is about to resume before the thread list
1726 if (error.Success())
1727 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001728 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001729 // can let all of our threads know that they are about to be
1730 // resumed. Threads will each be called with
1731 // Thread::WillResume(StateType) where StateType contains the state
1732 // that they are supposed to have when the process is resumed
1733 // (suspended/running/stepping). Threads should also check
1734 // their resume signal in lldb::Thread::GetResumeSignal()
1735 // to see if they are suppoed to start back up with a signal.
1736 if (m_thread_list.WillResume())
1737 {
1738 error = DoResume();
1739 if (error.Success())
1740 {
1741 DidResume();
1742 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00001743 if (log)
1744 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00001745 }
1746 }
1747 else
1748 {
Jim Inghamac959662011-01-24 06:34:17 +00001749 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00001750 }
1751 }
Jim Inghamac959662011-01-24 06:34:17 +00001752 else if (log)
1753 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00001754 return error;
1755}
1756
1757Error
1758Process::Halt ()
1759{
1760 Error error (WillHalt());
1761
1762 if (error.Success())
1763 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001764
1765 bool caused_stop = false;
1766 EventSP event_sp;
1767
1768 // Pause our private state thread so we can ensure no one else eats
1769 // the stop event out from under us.
1770 PausePrivateStateThread();
1771
1772 // Ask the process subclass to actually halt our process
Jim Ingham3ae449a2010-11-17 02:32:00 +00001773 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001774 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001775 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001776 // If "caused_stop" is true, then DoHalt stopped the process. If
1777 // "caused_stop" is false, the process was already stopped.
1778 // If the DoHalt caused the process to stop, then we want to catch
1779 // this event and set the interrupted bool to true before we pass
1780 // this along so clients know that the process was interrupted by
1781 // a halt command.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001782 if (caused_stop)
1783 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001784 // Wait for 2 seconds for the process to stop.
1785 TimeValue timeout_time;
1786 timeout_time = TimeValue::Now();
Greg Clayton72e1c782011-01-22 23:43:18 +00001787 timeout_time.OffsetWithSeconds(1);
Greg Clayton20d338f2010-11-18 05:57:03 +00001788 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1789
1790 if (state == eStateInvalid)
1791 {
1792 // We timeout out and didn't get a stop event...
1793 error.SetErrorString ("Halt timed out.");
1794 }
1795 else
1796 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001797 if (StateIsStoppedState (state))
1798 {
1799 // We caused the process to interrupt itself, so mark this
1800 // as such in the stop event so clients can tell an interrupted
1801 // process from a natural stop
1802 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1803 }
1804 else
1805 {
1806 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1807 if (log)
1808 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1809 error.SetErrorString ("Did not get stopped event after halt.");
1810 }
1811 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00001812 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001813 DidHalt();
1814
Jim Ingham3ae449a2010-11-17 02:32:00 +00001815 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001816 // Resume our private state thread before we post the event (if any)
1817 ResumePrivateStateThread();
1818
1819 // Post any event we might have consumed. If all goes well, we will have
1820 // stopped the process, intercepted the event and set the interrupted
Jim Ingham360f53f2010-11-30 02:22:11 +00001821 // bool in the event. Post it to the private event queue and that will end up
1822 // correctly setting the state.
Greg Clayton20d338f2010-11-18 05:57:03 +00001823 if (event_sp)
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001824 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton20d338f2010-11-18 05:57:03 +00001825
Chris Lattner24943d22010-06-08 16:52:24 +00001826 }
1827 return error;
1828}
1829
1830Error
1831Process::Detach ()
1832{
1833 Error error (WillDetach());
1834
1835 if (error.Success())
1836 {
1837 DisableAllBreakpointSites();
1838 error = DoDetach();
1839 if (error.Success())
1840 {
1841 DidDetach();
1842 StopPrivateStateThread();
1843 }
1844 }
1845 return error;
1846}
1847
1848Error
1849Process::Destroy ()
1850{
1851 Error error (WillDestroy());
1852 if (error.Success())
1853 {
1854 DisableAllBreakpointSites();
1855 error = DoDestroy();
1856 if (error.Success())
1857 {
1858 DidDestroy();
1859 StopPrivateStateThread();
1860 }
Caroline Tice861efb32010-11-16 05:07:41 +00001861 m_stdio_communication.StopReadThread();
1862 m_stdio_communication.Disconnect();
1863 if (m_process_input_reader && m_process_input_reader->IsActive())
1864 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1865 if (m_process_input_reader)
1866 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001867 }
1868 return error;
1869}
1870
1871Error
1872Process::Signal (int signal)
1873{
1874 Error error (WillSignal());
1875 if (error.Success())
1876 {
1877 error = DoSignal(signal);
1878 if (error.Success())
1879 DidSignal();
1880 }
1881 return error;
1882}
1883
1884UnixSignals &
1885Process::GetUnixSignals ()
1886{
1887 return m_unix_signals;
1888}
1889
1890Target &
1891Process::GetTarget ()
1892{
1893 return m_target;
1894}
1895
1896const Target &
1897Process::GetTarget () const
1898{
1899 return m_target;
1900}
1901
1902uint32_t
1903Process::GetAddressByteSize()
1904{
Greg Clayton20d338f2010-11-18 05:57:03 +00001905 if (m_addr_byte_size == 0)
1906 return m_target.GetArchitecture().GetAddressByteSize();
1907 return m_addr_byte_size;
Chris Lattner24943d22010-06-08 16:52:24 +00001908}
1909
1910bool
1911Process::ShouldBroadcastEvent (Event *event_ptr)
1912{
1913 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1914 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00001915 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001916
1917 switch (state)
1918 {
1919 case eStateAttaching:
1920 case eStateLaunching:
1921 case eStateDetached:
1922 case eStateExited:
1923 case eStateUnloaded:
1924 // These events indicate changes in the state of the debugging session, always report them.
1925 return_value = true;
1926 break;
1927 case eStateInvalid:
1928 // We stopped for no apparent reason, don't report it.
1929 return_value = false;
1930 break;
1931 case eStateRunning:
1932 case eStateStepping:
1933 // If we've started the target running, we handle the cases where we
1934 // are already running and where there is a transition from stopped to
1935 // running differently.
1936 // running -> running: Automatically suppress extra running events
1937 // stopped -> running: Report except when there is one or more no votes
1938 // and no yes votes.
1939 SynchronouslyNotifyStateChanged (state);
1940 switch (m_public_state.GetValue())
1941 {
1942 case eStateRunning:
1943 case eStateStepping:
1944 // We always suppress multiple runnings with no PUBLIC stop in between.
1945 return_value = false;
1946 break;
1947 default:
1948 // TODO: make this work correctly. For now always report
1949 // run if we aren't running so we don't miss any runnning
1950 // events. If I run the lldb/test/thread/a.out file and
1951 // break at main.cpp:58, run and hit the breakpoints on
1952 // multiple threads, then somehow during the stepping over
1953 // of all breakpoints no run gets reported.
1954 return_value = true;
1955
1956 // This is a transition from stop to run.
1957 switch (m_thread_list.ShouldReportRun (event_ptr))
1958 {
1959 case eVoteYes:
1960 case eVoteNoOpinion:
1961 return_value = true;
1962 break;
1963 case eVoteNo:
1964 return_value = false;
1965 break;
1966 }
1967 break;
1968 }
1969 break;
1970 case eStateStopped:
1971 case eStateCrashed:
1972 case eStateSuspended:
1973 {
1974 // We've stopped. First see if we're going to restart the target.
1975 // If we are going to stop, then we always broadcast the event.
1976 // 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 +00001977 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00001978 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00001979 {
Greg Clayton20d338f2010-11-18 05:57:03 +00001980 if (log)
1981 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00001982 return true;
1983 }
1984 else
1985 {
Chris Lattner24943d22010-06-08 16:52:24 +00001986 RefreshStateAfterStop ();
1987
1988 if (m_thread_list.ShouldStop (event_ptr) == false)
1989 {
1990 switch (m_thread_list.ShouldReportStop (event_ptr))
1991 {
1992 case eVoteYes:
1993 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00001994 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00001995 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00001996 case eVoteNo:
1997 return_value = false;
1998 break;
1999 }
2000
2001 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002002 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002003 Resume ();
2004 }
2005 else
2006 {
2007 return_value = true;
2008 SynchronouslyNotifyStateChanged (state);
2009 }
2010 }
2011 }
2012 }
2013
2014 if (log)
2015 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2016 return return_value;
2017}
2018
2019//------------------------------------------------------------------
2020// Thread Queries
2021//------------------------------------------------------------------
2022
2023ThreadList &
2024Process::GetThreadList ()
2025{
2026 return m_thread_list;
2027}
2028
2029const ThreadList &
2030Process::GetThreadList () const
2031{
2032 return m_thread_list;
2033}
2034
2035
2036bool
2037Process::StartPrivateStateThread ()
2038{
Greg Claytone005f2c2010-11-06 01:53:30 +00002039 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002040
2041 if (log)
2042 log->Printf ("Process::%s ( )", __FUNCTION__);
2043
2044 // Create a thread that watches our internal state and controls which
2045 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002046 char thread_name[1024];
2047 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2048 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002049 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2050}
2051
2052void
2053Process::PausePrivateStateThread ()
2054{
2055 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2056}
2057
2058void
2059Process::ResumePrivateStateThread ()
2060{
2061 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2062}
2063
2064void
2065Process::StopPrivateStateThread ()
2066{
2067 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2068}
2069
2070void
2071Process::ControlPrivateStateThread (uint32_t signal)
2072{
Greg Claytone005f2c2010-11-06 01:53:30 +00002073 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002074
2075 assert (signal == eBroadcastInternalStateControlStop ||
2076 signal == eBroadcastInternalStateControlPause ||
2077 signal == eBroadcastInternalStateControlResume);
2078
2079 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002080 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002081
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002082 // Signal the private state thread. First we should copy this is case the
2083 // thread starts exiting since the private state thread will NULL this out
2084 // when it exits
2085 const lldb::thread_t private_state_thread = m_private_state_thread;
2086 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner24943d22010-06-08 16:52:24 +00002087 {
2088 TimeValue timeout_time;
2089 bool timed_out;
2090
2091 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2092
2093 timeout_time = TimeValue::Now();
2094 timeout_time.OffsetWithSeconds(2);
2095 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2096 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2097
2098 if (signal == eBroadcastInternalStateControlStop)
2099 {
2100 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002101 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002102
2103 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002104 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002105 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002106 }
2107 }
2108}
2109
2110void
2111Process::HandlePrivateEvent (EventSP &event_sp)
2112{
Greg Claytone005f2c2010-11-06 01:53:30 +00002113 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002114 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2115 // See if we should broadcast this state to external clients?
2116 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2117 if (log)
2118 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2119
2120 if (should_broadcast)
2121 {
2122 if (log)
2123 {
2124 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2125 }
Caroline Tice861efb32010-11-16 05:07:41 +00002126 if (StateIsRunningState (internal_state))
2127 PushProcessInputReader ();
2128 else
2129 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002130 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2131 BroadcastEvent (event_sp);
2132 }
2133 else
2134 {
2135 if (log)
2136 {
2137 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2138 }
2139 }
2140}
2141
2142void *
2143Process::PrivateStateThread (void *arg)
2144{
2145 Process *proc = static_cast<Process*> (arg);
2146 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002147 return result;
2148}
2149
2150void *
2151Process::RunPrivateStateThread ()
2152{
2153 bool control_only = false;
2154 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2155
Greg Claytone005f2c2010-11-06 01:53:30 +00002156 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002157 if (log)
2158 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2159
2160 bool exit_now = false;
2161 while (!exit_now)
2162 {
2163 EventSP event_sp;
2164 WaitForEventsPrivate (NULL, event_sp, control_only);
2165 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2166 {
2167 switch (event_sp->GetType())
2168 {
2169 case eBroadcastInternalStateControlStop:
2170 exit_now = true;
2171 continue; // Go to next loop iteration so we exit without
2172 break; // doing any internal state managment below
2173
2174 case eBroadcastInternalStateControlPause:
2175 control_only = true;
2176 break;
2177
2178 case eBroadcastInternalStateControlResume:
2179 control_only = false;
2180 break;
2181 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002182
Jim Ingham3ae449a2010-11-17 02:32:00 +00002183 if (log)
2184 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2185
Chris Lattner24943d22010-06-08 16:52:24 +00002186 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002187 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002188 }
2189
2190
2191 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2192
2193 if (internal_state != eStateInvalid)
2194 {
2195 HandlePrivateEvent (event_sp);
2196 }
2197
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002198 if (internal_state == eStateInvalid ||
2199 internal_state == eStateExited ||
2200 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002201 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002202 if (log)
2203 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2204
Chris Lattner24943d22010-06-08 16:52:24 +00002205 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002206 }
Chris Lattner24943d22010-06-08 16:52:24 +00002207 }
2208
Caroline Tice926060e2010-10-29 21:48:37 +00002209 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002210 if (log)
2211 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2212
Greg Claytona4881d02011-01-22 07:12:45 +00002213 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2214 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002215 return NULL;
2216}
2217
Chris Lattner24943d22010-06-08 16:52:24 +00002218//------------------------------------------------------------------
2219// Process Event Data
2220//------------------------------------------------------------------
2221
2222Process::ProcessEventData::ProcessEventData () :
2223 EventData (),
2224 m_process_sp (),
2225 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002226 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002227 m_update_state (false),
2228 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002229{
2230}
2231
2232Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2233 EventData (),
2234 m_process_sp (process_sp),
2235 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002236 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002237 m_update_state (false),
2238 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002239{
2240}
2241
2242Process::ProcessEventData::~ProcessEventData()
2243{
2244}
2245
2246const ConstString &
2247Process::ProcessEventData::GetFlavorString ()
2248{
2249 static ConstString g_flavor ("Process::ProcessEventData");
2250 return g_flavor;
2251}
2252
2253const ConstString &
2254Process::ProcessEventData::GetFlavor () const
2255{
2256 return ProcessEventData::GetFlavorString ();
2257}
2258
Chris Lattner24943d22010-06-08 16:52:24 +00002259void
2260Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2261{
2262 // This function gets called twice for each event, once when the event gets pulled
2263 // off of the private process event queue, and once when it gets pulled off of
2264 // the public event queue. m_update_state is used to distinguish these
2265 // two cases; it is false when we're just pulling it off for private handling,
2266 // and we don't want to do the breakpoint command handling then.
2267
2268 if (!m_update_state)
2269 return;
2270
2271 m_process_sp->SetPublicState (m_state);
2272
2273 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2274 if (m_state == eStateStopped && ! m_restarted)
2275 {
2276 int num_threads = m_process_sp->GetThreadList().GetSize();
2277 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002278
Chris Lattner24943d22010-06-08 16:52:24 +00002279 for (idx = 0; idx < num_threads; ++idx)
2280 {
2281 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2282
Jim Ingham6297a3a2010-10-20 00:39:53 +00002283 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2284 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002285 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002286 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002287 }
2288 }
Greg Clayton643ee732010-08-04 01:40:35 +00002289
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002290 // The stop action might restart the target. If it does, then we want to mark that in the
2291 // event so that whoever is receiving it will know to wait for the running event and reflect
2292 // that state appropriately.
2293
Chris Lattner24943d22010-06-08 16:52:24 +00002294 if (m_process_sp->GetPrivateState() == eStateRunning)
2295 SetRestarted(true);
2296 }
2297}
2298
2299void
2300Process::ProcessEventData::Dump (Stream *s) const
2301{
2302 if (m_process_sp)
2303 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2304
2305 s->Printf("state = %s", StateAsCString(GetState()));;
2306}
2307
2308const Process::ProcessEventData *
2309Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2310{
2311 if (event_ptr)
2312 {
2313 const EventData *event_data = event_ptr->GetData();
2314 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2315 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2316 }
2317 return NULL;
2318}
2319
2320ProcessSP
2321Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2322{
2323 ProcessSP process_sp;
2324 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2325 if (data)
2326 process_sp = data->GetProcessSP();
2327 return process_sp;
2328}
2329
2330StateType
2331Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2332{
2333 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2334 if (data == NULL)
2335 return eStateInvalid;
2336 else
2337 return data->GetState();
2338}
2339
2340bool
2341Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2342{
2343 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2344 if (data == NULL)
2345 return false;
2346 else
2347 return data->GetRestarted();
2348}
2349
2350void
2351Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2352{
2353 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2354 if (data != NULL)
2355 data->SetRestarted(new_value);
2356}
2357
2358bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002359Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2360{
2361 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2362 if (data == NULL)
2363 return false;
2364 else
2365 return data->GetInterrupted ();
2366}
2367
2368void
2369Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2370{
2371 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2372 if (data != NULL)
2373 data->SetInterrupted(new_value);
2374}
2375
2376bool
Chris Lattner24943d22010-06-08 16:52:24 +00002377Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2378{
2379 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2380 if (data)
2381 {
2382 data->SetUpdateStateOnRemoval();
2383 return true;
2384 }
2385 return false;
2386}
2387
Chris Lattner24943d22010-06-08 16:52:24 +00002388Target *
2389Process::CalculateTarget ()
2390{
2391 return &m_target;
2392}
2393
2394Process *
2395Process::CalculateProcess ()
2396{
2397 return this;
2398}
2399
2400Thread *
2401Process::CalculateThread ()
2402{
2403 return NULL;
2404}
2405
2406StackFrame *
2407Process::CalculateStackFrame ()
2408{
2409 return NULL;
2410}
2411
2412void
Greg Claytona830adb2010-10-04 01:05:56 +00002413Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002414{
2415 exe_ctx.target = &m_target;
2416 exe_ctx.process = this;
2417 exe_ctx.thread = NULL;
2418 exe_ctx.frame = NULL;
2419}
2420
2421lldb::ProcessSP
2422Process::GetSP ()
2423{
2424 return GetTarget().GetProcessSP();
2425}
2426
Jim Ingham7508e732010-08-09 23:31:02 +00002427uint32_t
2428Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2429{
2430 return 0;
2431}
2432
2433ArchSpec
2434Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2435{
2436 return Host::GetArchSpecForExistingProcess (pid);
2437}
2438
2439ArchSpec
2440Process::GetArchSpecForExistingProcess (const char *process_name)
2441{
2442 return Host::GetArchSpecForExistingProcess (process_name);
2443}
2444
Caroline Tice861efb32010-11-16 05:07:41 +00002445void
2446Process::AppendSTDOUT (const char * s, size_t len)
2447{
Greg Clayton20d338f2010-11-18 05:57:03 +00002448 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002449 m_stdout_data.append (s, len);
2450
Greg Claytonb3781332010-12-05 19:16:56 +00002451 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002452}
2453
2454void
2455Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2456{
2457 Process *process = (Process *) baton;
2458 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2459}
2460
2461size_t
2462Process::ProcessInputReaderCallback (void *baton,
2463 InputReader &reader,
2464 lldb::InputReaderAction notification,
2465 const char *bytes,
2466 size_t bytes_len)
2467{
2468 Process *process = (Process *) baton;
2469
2470 switch (notification)
2471 {
2472 case eInputReaderActivate:
2473 break;
2474
2475 case eInputReaderDeactivate:
2476 break;
2477
2478 case eInputReaderReactivate:
2479 break;
2480
2481 case eInputReaderGotToken:
2482 {
2483 Error error;
2484 process->PutSTDIN (bytes, bytes_len, error);
2485 }
2486 break;
2487
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002488 case eInputReaderInterrupt:
2489 process->Halt ();
2490 break;
2491
2492 case eInputReaderEndOfFile:
2493 process->AppendSTDOUT ("^D", 2);
2494 break;
2495
Caroline Tice861efb32010-11-16 05:07:41 +00002496 case eInputReaderDone:
2497 break;
2498
2499 }
2500
2501 return bytes_len;
2502}
2503
2504void
2505Process::ResetProcessInputReader ()
2506{
2507 m_process_input_reader.reset();
2508}
2509
2510void
2511Process::SetUpProcessInputReader (int file_descriptor)
2512{
2513 // First set up the Read Thread for reading/handling process I/O
2514
2515 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2516
2517 if (conn_ap.get())
2518 {
2519 m_stdio_communication.SetConnection (conn_ap.release());
2520 if (m_stdio_communication.IsConnected())
2521 {
2522 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2523 m_stdio_communication.StartReadThread();
2524
2525 // Now read thread is set up, set up input reader.
2526
2527 if (!m_process_input_reader.get())
2528 {
2529 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2530 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2531 this,
2532 eInputReaderGranularityByte,
2533 NULL,
2534 NULL,
2535 false));
2536
2537 if (err.Fail())
2538 m_process_input_reader.reset();
2539 }
2540 }
2541 }
2542}
2543
2544void
2545Process::PushProcessInputReader ()
2546{
2547 if (m_process_input_reader && !m_process_input_reader->IsActive())
2548 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2549}
2550
2551void
2552Process::PopProcessInputReader ()
2553{
2554 if (m_process_input_reader && m_process_input_reader->IsActive())
2555 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2556}
2557
Greg Clayton990de7b2010-11-18 23:32:35 +00002558
2559void
2560Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002561{
Greg Clayton990de7b2010-11-18 23:32:35 +00002562 UserSettingsControllerSP &usc = GetSettingsController();
2563 usc.reset (new SettingsController);
2564 UserSettingsController::InitializeSettingsController (usc,
2565 SettingsController::global_settings_table,
2566 SettingsController::instance_settings_table);
2567}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002568
Greg Clayton990de7b2010-11-18 23:32:35 +00002569void
2570Process::Terminate ()
2571{
2572 UserSettingsControllerSP &usc = GetSettingsController();
2573 UserSettingsController::FinalizeSettingsController (usc);
2574 usc.reset();
2575}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002576
Greg Clayton990de7b2010-11-18 23:32:35 +00002577UserSettingsControllerSP &
2578Process::GetSettingsController ()
2579{
2580 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002581 return g_settings_controller;
2582}
2583
Caroline Tice1ebef442010-09-27 00:30:10 +00002584void
2585Process::UpdateInstanceName ()
2586{
2587 ModuleSP module_sp = GetTarget().GetExecutableModule();
2588 if (module_sp)
2589 {
2590 StreamString sstr;
2591 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2592
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002593 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002594 sstr.GetData());
2595 }
2596}
2597
Greg Clayton427f2902010-12-14 02:59:59 +00002598ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002599Process::RunThreadPlan (ExecutionContext &exe_ctx,
2600 lldb::ThreadPlanSP &thread_plan_sp,
2601 bool stop_others,
2602 bool try_all_threads,
2603 bool discard_on_error,
2604 uint32_t single_thread_timeout_usec,
2605 Stream &errors)
2606{
2607 ExecutionResults return_value = eExecutionSetupError;
2608
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002609 if (thread_plan_sp.get() == NULL)
2610 {
2611 errors.Printf("RunThreadPlan called with empty thread plan.");
2612 return lldb::eExecutionSetupError;
2613 }
2614
Jim Inghamac959662011-01-24 06:34:17 +00002615 if (m_private_state.GetValue() != eStateStopped)
2616 {
2617 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
2618 // REMOVE BEAR TRAP...
2619 // abort();
2620 }
2621
Jim Ingham360f53f2010-11-30 02:22:11 +00002622 // Save this value for restoration of the execution context after we run
2623 uint32_t tid = exe_ctx.thread->GetIndexID();
2624
2625 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2626 // so we should arrange to reset them as well.
2627
2628 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2629 lldb::StackFrameSP selected_frame_sp;
2630
2631 uint32_t selected_tid;
2632 if (selected_thread_sp != NULL)
2633 {
2634 selected_tid = selected_thread_sp->GetIndexID();
2635 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2636 }
2637 else
2638 {
2639 selected_tid = LLDB_INVALID_THREAD_ID;
2640 }
2641
2642 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2643
Jim Ingham6ae318c2011-01-23 21:14:08 +00002644 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham360f53f2010-11-30 02:22:11 +00002645 exe_ctx.process->HijackProcessEvents(&listener);
Jim Inghamac959662011-01-24 06:34:17 +00002646
Jim Ingham6ae318c2011-01-23 21:14:08 +00002647 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002648 if (log)
2649 {
2650 StreamString s;
2651 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham6ae318c2011-01-23 21:14:08 +00002652 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 +00002653 }
2654
Jim Ingham360f53f2010-11-30 02:22:11 +00002655 Error resume_error = exe_ctx.process->Resume ();
2656 if (!resume_error.Success())
2657 {
2658 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2659 exe_ctx.process->RestoreProcessEvents();
Greg Clayton427f2902010-12-14 02:59:59 +00002660 return lldb::eExecutionSetupError;
Jim Ingham360f53f2010-11-30 02:22:11 +00002661 }
2662
2663 // We need to call the function synchronously, so spin waiting for it to return.
2664 // If we get interrupted while executing, we're going to lose our context, and
2665 // won't be able to gather the result at this point.
2666 // We set the timeout AFTER the resume, since the resume takes some time and we
2667 // don't want to charge that to the timeout.
2668
2669 TimeValue* timeout_ptr = NULL;
2670 TimeValue real_timeout;
2671
2672 if (single_thread_timeout_usec != 0)
2673 {
2674 real_timeout = TimeValue::Now();
2675 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2676 timeout_ptr = &real_timeout;
2677 }
2678
Jim Ingham360f53f2010-11-30 02:22:11 +00002679 while (1)
2680 {
2681 lldb::EventSP event_sp;
2682 lldb::StateType stop_state = lldb::eStateInvalid;
2683 // Now wait for the process to stop again:
2684 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2685
2686 if (!got_event)
2687 {
2688 // Right now this is the only way to tell we've timed out...
2689 // We should interrupt the process here...
2690 // Not really sure what to do if Halt fails here...
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002691 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002692 if (try_all_threads)
2693 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2694 single_thread_timeout_usec);
2695 else
2696 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2697 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002698 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002699
Jim Inghamc556b462011-01-22 01:30:53 +00002700 Error halt_error = exe_ctx.process->Halt();
2701
2702 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002703 {
2704 timeout_ptr = NULL;
2705 if (log)
2706 log->Printf ("Halt succeeded.");
2707
2708 // Between the time that we got the timeout and the time we halted, but target
2709 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2710 // timeout to
2711 got_event = listener.WaitForEvent(NULL, event_sp);
2712
2713 if (got_event)
2714 {
2715 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2716 if (log)
2717 {
2718 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2719 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2720 log->Printf (" Event was the Halt interruption event.");
2721 }
2722
2723 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2724 {
2725 if (log)
2726 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton427f2902010-12-14 02:59:59 +00002727 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002728 break;
2729 }
2730
2731 if (try_all_threads
2732 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2733 {
2734
2735 thread_plan_sp->SetStopOthers (false);
2736 if (log)
2737 log->Printf ("About to resume.");
2738
2739 exe_ctx.process->Resume();
2740 continue;
2741 }
2742 else
2743 {
2744 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton427f2902010-12-14 02:59:59 +00002745 return lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002746 }
2747 }
2748 }
Jim Inghamc556b462011-01-22 01:30:53 +00002749 else
2750 {
2751
2752 if (log)
2753 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2754 halt_error.AsCString());
Jim Inghamac959662011-01-24 06:34:17 +00002755// abort();
Jim Inghamc556b462011-01-22 01:30:53 +00002756
Jim Ingham6ae318c2011-01-23 21:14:08 +00002757 if (single_thread_timeout_usec != 0)
2758 {
2759 real_timeout = TimeValue::Now();
2760 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2761 timeout_ptr = &real_timeout;
2762 }
2763 continue;
Jim Inghamc556b462011-01-22 01:30:53 +00002764 }
2765
Jim Ingham360f53f2010-11-30 02:22:11 +00002766 }
2767
2768 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2769 if (log)
2770 log->Printf("Got event: %s.", StateAsCString(stop_state));
2771
2772 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2773 continue;
2774
2775 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2776 {
Greg Clayton427f2902010-12-14 02:59:59 +00002777 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002778 break;
2779 }
2780 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2781 {
Greg Clayton427f2902010-12-14 02:59:59 +00002782 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00002783 break;
2784 }
2785 else
2786 {
2787 if (log)
2788 {
2789 StreamString s;
Jim Inghamc556b462011-01-22 01:30:53 +00002790 if (event_sp)
2791 event_sp->Dump (&s);
2792 else
2793 {
2794 log->Printf ("Stop event that interrupted us is NULL.");
2795 }
2796
Jim Ingham360f53f2010-11-30 02:22:11 +00002797 StreamString ts;
2798
2799 const char *event_explanation;
2800
2801 do
2802 {
2803 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2804
2805 if (!event_data)
2806 {
2807 event_explanation = "<no event data>";
2808 break;
2809 }
2810
2811 Process *process = event_data->GetProcessSP().get();
2812
2813 if (!process)
2814 {
2815 event_explanation = "<no process>";
2816 break;
2817 }
2818
2819 ThreadList &thread_list = process->GetThreadList();
2820
2821 uint32_t num_threads = thread_list.GetSize();
2822 uint32_t thread_index;
2823
2824 ts.Printf("<%u threads> ", num_threads);
2825
2826 for (thread_index = 0;
2827 thread_index < num_threads;
2828 ++thread_index)
2829 {
2830 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2831
2832 if (!thread)
2833 {
2834 ts.Printf("<?> ");
2835 continue;
2836 }
2837
Jim Inghamc556b462011-01-22 01:30:53 +00002838 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton08d7d3a2011-01-06 22:15:06 +00002839 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Ingham360f53f2010-11-30 02:22:11 +00002840
2841 if (register_context)
2842 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2843 else
2844 ts.Printf("[ip unknown] ");
2845
2846 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2847 if (stop_info_sp)
2848 {
2849 const char *stop_desc = stop_info_sp->GetDescription();
2850 if (stop_desc)
2851 ts.PutCString (stop_desc);
2852 }
2853 ts.Printf(">");
2854 }
2855
2856 event_explanation = ts.GetData();
2857 } while (0);
2858
Jim Inghamc556b462011-01-22 01:30:53 +00002859 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2860 if (!GetThreadList().ShouldStop(event_sp.get()))
2861 {
2862 if (log)
2863 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2864 s.GetData(), event_explanation);
2865 if (single_thread_timeout_usec != 0)
2866 {
2867 real_timeout = TimeValue::Now();
2868 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2869 timeout_ptr = &real_timeout;
2870 }
2871
2872 continue;
2873 }
2874 else
2875 {
2876 if (log)
2877 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2878 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002879 }
2880
2881 if (discard_on_error && thread_plan_sp)
2882 {
2883 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2884 }
Greg Clayton427f2902010-12-14 02:59:59 +00002885 return_value = lldb::eExecutionInterrupted;
Jim Ingham360f53f2010-11-30 02:22:11 +00002886 break;
2887 }
2888 }
2889
2890 if (exe_ctx.process)
2891 exe_ctx.process->RestoreProcessEvents ();
2892
2893 // Thread we ran the function in may have gone away because we ran the target
2894 // Check that it's still there.
2895 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2896 if (exe_ctx.thread)
2897 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2898
2899 // Also restore the current process'es selected frame & thread, since this function calling may
2900 // be done behind the user's back.
2901
2902 if (selected_tid != LLDB_INVALID_THREAD_ID)
2903 {
2904 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2905 {
2906 // We were able to restore the selected thread, now restore the frame:
2907 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2908 }
2909 }
2910
2911 return return_value;
2912}
2913
2914const char *
2915Process::ExecutionResultAsCString (ExecutionResults result)
2916{
2917 const char *result_name;
2918
2919 switch (result)
2920 {
Greg Clayton427f2902010-12-14 02:59:59 +00002921 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002922 result_name = "eExecutionCompleted";
2923 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002924 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00002925 result_name = "eExecutionDiscarded";
2926 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002927 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00002928 result_name = "eExecutionInterrupted";
2929 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002930 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00002931 result_name = "eExecutionSetupError";
2932 break;
Greg Clayton427f2902010-12-14 02:59:59 +00002933 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00002934 result_name = "eExecutionTimedOut";
2935 break;
2936 }
2937 return result_name;
2938}
2939
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002940//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00002941// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002942//--------------------------------------------------------------
2943
Greg Claytond0a5a232010-09-19 02:33:57 +00002944Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00002945 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002946{
Greg Clayton638351a2010-12-04 00:10:17 +00002947 m_default_settings.reset (new ProcessInstanceSettings (*this,
2948 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00002949 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002950}
2951
Greg Claytond0a5a232010-09-19 02:33:57 +00002952Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002953{
2954}
2955
2956lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00002957Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002958{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002959 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2960 false,
2961 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002962 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2963 return new_settings_sp;
2964}
2965
2966//--------------------------------------------------------------
2967// class ProcessInstanceSettings
2968//--------------------------------------------------------------
2969
Greg Clayton638351a2010-12-04 00:10:17 +00002970ProcessInstanceSettings::ProcessInstanceSettings
2971(
2972 UserSettingsController &owner,
2973 bool live_instance,
2974 const char *name
2975) :
2976 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002977 m_run_args (),
2978 m_env_vars (),
2979 m_input_path (),
2980 m_output_path (),
2981 m_error_path (),
2982 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00002983 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00002984 m_disable_stdio (false),
2985 m_inherit_host_env (true),
2986 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002987{
Caroline Tice396704b2010-09-09 18:26:37 +00002988 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2989 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2990 // 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 +00002991 // This is true for CreateInstanceName() too.
2992
2993 if (GetInstanceName () == InstanceSettings::InvalidName())
2994 {
2995 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2996 m_owner.RegisterInstanceSettings (this);
2997 }
Caroline Tice396704b2010-09-09 18:26:37 +00002998
2999 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003000 {
3001 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3002 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003003 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003004 }
3005}
3006
3007ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003008 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003009 m_run_args (rhs.m_run_args),
3010 m_env_vars (rhs.m_env_vars),
3011 m_input_path (rhs.m_input_path),
3012 m_output_path (rhs.m_output_path),
3013 m_error_path (rhs.m_error_path),
3014 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00003015 m_disable_aslr (rhs.m_disable_aslr),
3016 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003017{
3018 if (m_instance_name != InstanceSettings::GetDefaultName())
3019 {
3020 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3021 CopyInstanceSettings (pending_settings,false);
3022 m_owner.RemovePendingSettings (m_instance_name);
3023 }
3024}
3025
3026ProcessInstanceSettings::~ProcessInstanceSettings ()
3027{
3028}
3029
3030ProcessInstanceSettings&
3031ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3032{
3033 if (this != &rhs)
3034 {
3035 m_run_args = rhs.m_run_args;
3036 m_env_vars = rhs.m_env_vars;
3037 m_input_path = rhs.m_input_path;
3038 m_output_path = rhs.m_output_path;
3039 m_error_path = rhs.m_error_path;
3040 m_plugin = rhs.m_plugin;
3041 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003042 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003043 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003044 }
3045
3046 return *this;
3047}
3048
3049
3050void
3051ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3052 const char *index_value,
3053 const char *value,
3054 const ConstString &instance_name,
3055 const SettingEntry &entry,
3056 lldb::VarSetOperationType op,
3057 Error &err,
3058 bool pending)
3059{
3060 if (var_name == RunArgsVarName())
3061 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3062 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003063 {
3064 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003065 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003066 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003067 else if (var_name == InputPathVarName())
3068 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3069 else if (var_name == OutputPathVarName())
3070 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3071 else if (var_name == ErrorPathVarName())
3072 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3073 else if (var_name == PluginVarName())
3074 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003075 else if (var_name == InheritHostEnvVarName())
3076 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003077 else if (var_name == DisableASLRVarName())
3078 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003079 else if (var_name == DisableSTDIOVarName ())
3080 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003081}
3082
3083void
3084ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3085 bool pending)
3086{
3087 if (new_settings.get() == NULL)
3088 return;
3089
3090 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3091
3092 m_run_args = new_process_settings->m_run_args;
3093 m_env_vars = new_process_settings->m_env_vars;
3094 m_input_path = new_process_settings->m_input_path;
3095 m_output_path = new_process_settings->m_output_path;
3096 m_error_path = new_process_settings->m_error_path;
3097 m_plugin = new_process_settings->m_plugin;
3098 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003099 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003100}
3101
Caroline Ticebcb5b452010-09-20 21:37:42 +00003102bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003103ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3104 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003105 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003106 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003107{
3108 if (var_name == RunArgsVarName())
3109 {
3110 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003111 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003112 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3113 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003114 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003115 }
3116 else if (var_name == EnvVarsVarName())
3117 {
Greg Clayton638351a2010-12-04 00:10:17 +00003118 GetHostEnvironmentIfNeeded ();
3119
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003120 if (m_env_vars.size() > 0)
3121 {
3122 std::map<std::string, std::string>::iterator pos;
3123 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3124 {
3125 StreamString value_str;
3126 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3127 value.AppendString (value_str.GetData());
3128 }
3129 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003130 }
3131 else if (var_name == InputPathVarName())
3132 {
3133 value.AppendString (m_input_path.c_str());
3134 }
3135 else if (var_name == OutputPathVarName())
3136 {
3137 value.AppendString (m_output_path.c_str());
3138 }
3139 else if (var_name == ErrorPathVarName())
3140 {
3141 value.AppendString (m_error_path.c_str());
3142 }
3143 else if (var_name == PluginVarName())
3144 {
3145 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3146 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003147 else if (var_name == InheritHostEnvVarName())
3148 {
3149 if (m_inherit_host_env)
3150 value.AppendString ("true");
3151 else
3152 value.AppendString ("false");
3153 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003154 else if (var_name == DisableASLRVarName())
3155 {
3156 if (m_disable_aslr)
3157 value.AppendString ("true");
3158 else
3159 value.AppendString ("false");
3160 }
Caroline Ticebd666012010-12-03 18:46:09 +00003161 else if (var_name == DisableSTDIOVarName())
3162 {
3163 if (m_disable_stdio)
3164 value.AppendString ("true");
3165 else
3166 value.AppendString ("false");
3167 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003168 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003169 {
3170 if (err)
3171 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3172 return false;
3173 }
3174 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003175}
3176
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003177const ConstString
3178ProcessInstanceSettings::CreateInstanceName ()
3179{
3180 static int instance_count = 1;
3181 StreamString sstr;
3182
3183 sstr.Printf ("process_%d", instance_count);
3184 ++instance_count;
3185
3186 const ConstString ret_val (sstr.GetData());
3187 return ret_val;
3188}
3189
3190const ConstString &
3191ProcessInstanceSettings::RunArgsVarName ()
3192{
3193 static ConstString run_args_var_name ("run-args");
3194
3195 return run_args_var_name;
3196}
3197
3198const ConstString &
3199ProcessInstanceSettings::EnvVarsVarName ()
3200{
3201 static ConstString env_vars_var_name ("env-vars");
3202
3203 return env_vars_var_name;
3204}
3205
3206const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003207ProcessInstanceSettings::InheritHostEnvVarName ()
3208{
3209 static ConstString g_name ("inherit-env");
3210
3211 return g_name;
3212}
3213
3214const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003215ProcessInstanceSettings::InputPathVarName ()
3216{
3217 static ConstString input_path_var_name ("input-path");
3218
3219 return input_path_var_name;
3220}
3221
3222const ConstString &
3223ProcessInstanceSettings::OutputPathVarName ()
3224{
Caroline Tice87097232010-09-07 18:35:40 +00003225 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003226
3227 return output_path_var_name;
3228}
3229
3230const ConstString &
3231ProcessInstanceSettings::ErrorPathVarName ()
3232{
Caroline Tice87097232010-09-07 18:35:40 +00003233 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003234
3235 return error_path_var_name;
3236}
3237
3238const ConstString &
3239ProcessInstanceSettings::PluginVarName ()
3240{
3241 static ConstString plugin_var_name ("plugin");
3242
3243 return plugin_var_name;
3244}
3245
3246
3247const ConstString &
3248ProcessInstanceSettings::DisableASLRVarName ()
3249{
3250 static ConstString disable_aslr_var_name ("disable-aslr");
3251
3252 return disable_aslr_var_name;
3253}
3254
Caroline Ticebd666012010-12-03 18:46:09 +00003255const ConstString &
3256ProcessInstanceSettings::DisableSTDIOVarName ()
3257{
3258 static ConstString disable_stdio_var_name ("disable-stdio");
3259
3260 return disable_stdio_var_name;
3261}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003262
3263//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003264// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003265//--------------------------------------------------
3266
3267SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003268Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003269{
3270 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3271 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3272};
3273
3274
3275lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003276Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003277{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003278 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3279 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3280 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003281};
3282
3283SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003284Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003285{
Greg Clayton638351a2010-12-04 00:10:17 +00003286 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3287 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3288 { "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." },
3289 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003290 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3291 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3292 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3293 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003294 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3295 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3296 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003297};
3298
3299
Jim Ingham7508e732010-08-09 23:31:02 +00003300