blob: 03fc98298a1a007977b2b6e580c9b3fa5e44e557 [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"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000030#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000032#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/Target.h"
34#include "lldb/Target/TargetList.h"
35#include "lldb/Target/Thread.h"
36#include "lldb/Target/ThreadPlan.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
Greg Claytonfd119992011-01-07 06:08:19 +000041
42//----------------------------------------------------------------------
43// MemoryCache constructor
44//----------------------------------------------------------------------
45Process::MemoryCache::MemoryCache() :
46 m_cache_line_byte_size (512),
47 m_cache_mutex (Mutex::eMutexTypeRecursive),
48 m_cache ()
49{
50}
51
52//----------------------------------------------------------------------
53// Destructor
54//----------------------------------------------------------------------
55Process::MemoryCache::~MemoryCache()
56{
57}
58
59void
60Process::MemoryCache::Clear()
61{
62 Mutex::Locker locker (m_cache_mutex);
63 m_cache.clear();
64}
65
66void
67Process::MemoryCache::Flush (addr_t addr, size_t size)
68{
69 if (size == 0)
70 return;
71
72 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
73 const addr_t end_addr = (addr + size - 1);
74 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
75 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
76
77 Mutex::Locker locker (m_cache_mutex);
78 if (m_cache.empty())
79 return;
80
81 assert ((flush_start_addr % cache_line_byte_size) == 0);
82
83 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
84 {
85 collection::iterator pos = m_cache.find (curr_addr);
86 if (pos != m_cache.end())
87 m_cache.erase(pos);
88 }
89}
90
91size_t
92Process::MemoryCache::Read
93(
94 Process *process,
95 addr_t addr,
96 void *dst,
97 size_t dst_len,
98 Error &error
99)
100{
101 size_t bytes_left = dst_len;
102 if (dst && bytes_left > 0)
103 {
104 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
105 uint8_t *dst_buf = (uint8_t *)dst;
106 addr_t curr_addr = addr - (addr % cache_line_byte_size);
107 addr_t cache_offset = addr - curr_addr;
108 Mutex::Locker locker (m_cache_mutex);
109
110 while (bytes_left > 0)
111 {
112 collection::const_iterator pos = m_cache.find (curr_addr);
113 collection::const_iterator end = m_cache.end ();
114
115 if (pos != end)
116 {
117 size_t curr_read_size = cache_line_byte_size - cache_offset;
118 if (curr_read_size > bytes_left)
119 curr_read_size = bytes_left;
120
121 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
122
123 bytes_left -= curr_read_size;
124 curr_addr += curr_read_size + cache_offset;
125 cache_offset = 0;
126
127 if (bytes_left > 0)
128 {
129 // Get sequential cache page hits
130 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
131 {
132 assert ((curr_addr % cache_line_byte_size) == 0);
133
134 if (pos->first != curr_addr)
135 break;
136
137 curr_read_size = pos->second->GetByteSize();
138 if (curr_read_size > bytes_left)
139 curr_read_size = bytes_left;
140
141 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
142
143 bytes_left -= curr_read_size;
144 curr_addr += curr_read_size;
145
146 // We have a cache page that succeeded to read some bytes
147 // but not an entire page. If this happens, we must cap
148 // off how much data we are able to read...
149 if (pos->second->GetByteSize() != cache_line_byte_size)
150 return dst_len - bytes_left;
151 }
152 }
153 }
154
155 // We need to read from the process
156
157 if (bytes_left > 0)
158 {
159 assert ((curr_addr % cache_line_byte_size) == 0);
160 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
161 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
162 data_buffer_heap_ap->GetBytes(),
163 data_buffer_heap_ap->GetByteSize(),
164 error);
165 if (process_bytes_read == 0)
166 return dst_len - bytes_left;
167
168 if (process_bytes_read != cache_line_byte_size)
169 data_buffer_heap_ap->SetByteSize (process_bytes_read);
170 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
171 // We have read data and put it into the cache, continue through the
172 // loop again to get the data out of the cache...
173 }
174 }
175 }
176
177 return dst_len - bytes_left;
178}
179
Chris Lattner24943d22010-06-08 16:52:24 +0000180Process*
181Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
182{
183 ProcessCreateInstance create_callback = NULL;
184 if (plugin_name)
185 {
186 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
187 if (create_callback)
188 {
189 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
190 if (debugger_ap->CanDebug(target))
191 return debugger_ap.release();
192 }
193 }
194 else
195 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000196 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000197 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000198 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
199 if (debugger_ap->CanDebug(target))
200 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000201 }
202 }
203 return NULL;
204}
205
206
207//----------------------------------------------------------------------
208// Process constructor
209//----------------------------------------------------------------------
210Process::Process(Target &target, Listener &listener) :
211 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000212 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000213 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000214 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000215 m_public_state (eStateUnloaded),
216 m_private_state (eStateUnloaded),
217 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
218 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
219 m_private_state_listener ("lldb.process.internal_state_listener"),
220 m_private_state_control_wait(),
221 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
222 m_stop_id (0),
223 m_thread_index_id (0),
224 m_exit_status (-1),
225 m_exit_string (),
226 m_thread_list (this),
227 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000228 m_image_tokens (),
229 m_listener (listener),
230 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000231 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000232 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000233 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000234 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000235 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000236 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000237 m_stdout_data (),
Jim Inghamc2dc7c82011-01-29 01:49:25 +0000238 m_memory_cache (),
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000239 m_next_event_action_ap()
Chris Lattner24943d22010-06-08 16:52:24 +0000240{
Caroline Tice1ebef442010-09-27 00:30:10 +0000241 UpdateInstanceName();
242
Greg Claytone005f2c2010-11-06 01:53:30 +0000243 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000244 if (log)
245 log->Printf ("%p Process::Process()", this);
246
Greg Clayton49ce6822010-10-31 03:01:06 +0000247 SetEventName (eBroadcastBitStateChanged, "state-changed");
248 SetEventName (eBroadcastBitInterrupt, "interrupt");
249 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
250 SetEventName (eBroadcastBitSTDERR, "stderr-available");
251
Chris Lattner24943d22010-06-08 16:52:24 +0000252 listener.StartListeningForEvents (this,
253 eBroadcastBitStateChanged |
254 eBroadcastBitInterrupt |
255 eBroadcastBitSTDOUT |
256 eBroadcastBitSTDERR);
257
258 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
259 eBroadcastBitStateChanged);
260
261 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
262 eBroadcastInternalStateControlStop |
263 eBroadcastInternalStateControlPause |
264 eBroadcastInternalStateControlResume);
265}
266
267//----------------------------------------------------------------------
268// Destructor
269//----------------------------------------------------------------------
270Process::~Process()
271{
Greg Claytone005f2c2010-11-06 01:53:30 +0000272 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000273 if (log)
274 log->Printf ("%p Process::~Process()", this);
275 StopPrivateStateThread();
276}
277
278void
279Process::Finalize()
280{
281 // Do any cleanup needed prior to being destructed... Subclasses
282 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000283
284 // We need to destroy the loader before the derived Process class gets destroyed
285 // since it is very likely that undoing the loader will require access to the real process.
286 if (m_dyld_ap.get() != NULL)
287 m_dyld_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000288}
289
290void
291Process::RegisterNotificationCallbacks (const Notifications& callbacks)
292{
293 m_notifications.push_back(callbacks);
294 if (callbacks.initialize != NULL)
295 callbacks.initialize (callbacks.baton, this);
296}
297
298bool
299Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
300{
301 std::vector<Notifications>::iterator pos, end = m_notifications.end();
302 for (pos = m_notifications.begin(); pos != end; ++pos)
303 {
304 if (pos->baton == callbacks.baton &&
305 pos->initialize == callbacks.initialize &&
306 pos->process_state_changed == callbacks.process_state_changed)
307 {
308 m_notifications.erase(pos);
309 return true;
310 }
311 }
312 return false;
313}
314
315void
316Process::SynchronouslyNotifyStateChanged (StateType state)
317{
318 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
319 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
320 {
321 if (notification_pos->process_state_changed)
322 notification_pos->process_state_changed (notification_pos->baton, this, state);
323 }
324}
325
326// FIXME: We need to do some work on events before the general Listener sees them.
327// For instance if we are continuing from a breakpoint, we need to ensure that we do
328// the little "insert real insn, step & stop" trick. But we can't do that when the
329// event is delivered by the broadcaster - since that is done on the thread that is
330// waiting for new events, so if we needed more than one event for our handling, we would
331// stall. So instead we do it when we fetch the event off of the queue.
332//
333
334StateType
335Process::GetNextEvent (EventSP &event_sp)
336{
337 StateType state = eStateInvalid;
338
339 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
340 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
341
342 return state;
343}
344
345
346StateType
347Process::WaitForProcessToStop (const TimeValue *timeout)
348{
349 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
350 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
351}
352
353
354StateType
355Process::WaitForState
356(
357 const TimeValue *timeout,
358 const StateType *match_states, const uint32_t num_match_states
359)
360{
361 EventSP event_sp;
362 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000363 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000364 while (state != eStateInvalid)
365 {
Greg Claytond8c62532010-10-07 04:19:01 +0000366 // If we are exited or detached, we won't ever get back to any
367 // other valid state...
368 if (state == eStateDetached || state == eStateExited)
369 return state;
370
Chris Lattner24943d22010-06-08 16:52:24 +0000371 state = WaitForStateChangedEvents (timeout, event_sp);
372
373 for (i=0; i<num_match_states; ++i)
374 {
375 if (match_states[i] == state)
376 return state;
377 }
378 }
379 return state;
380}
381
Jim Ingham63e24d72010-10-11 23:53:14 +0000382bool
383Process::HijackProcessEvents (Listener *listener)
384{
385 if (listener != NULL)
386 {
387 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
388 }
389 else
390 return false;
391}
392
393void
394Process::RestoreProcessEvents ()
395{
396 RestoreBroadcaster();
397}
398
Jim Inghamf9f40c22011-02-08 05:20:59 +0000399bool
400Process::HijackPrivateProcessEvents (Listener *listener)
401{
402 if (listener != NULL)
403 {
404 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
405 }
406 else
407 return false;
408}
409
410void
411Process::RestorePrivateProcessEvents ()
412{
413 m_private_state_broadcaster.RestoreBroadcaster();
414}
415
Chris Lattner24943d22010-06-08 16:52:24 +0000416StateType
417Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
418{
Greg Claytone005f2c2010-11-06 01:53:30 +0000419 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000420
421 if (log)
422 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
423
424 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000425 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
426 this,
427 eBroadcastBitStateChanged,
428 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000429 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
430
431 if (log)
432 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
433 __FUNCTION__,
434 timeout,
435 StateAsCString(state));
436 return state;
437}
438
439Event *
440Process::PeekAtStateChangedEvents ()
441{
Greg Claytone005f2c2010-11-06 01:53:30 +0000442 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000443
444 if (log)
445 log->Printf ("Process::%s...", __FUNCTION__);
446
447 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000448 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
449 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000450 if (log)
451 {
452 if (event_ptr)
453 {
454 log->Printf ("Process::%s (event_ptr) => %s",
455 __FUNCTION__,
456 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
457 }
458 else
459 {
460 log->Printf ("Process::%s no events found",
461 __FUNCTION__);
462 }
463 }
464 return event_ptr;
465}
466
467StateType
468Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
469{
Greg Claytone005f2c2010-11-06 01:53:30 +0000470 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000471
472 if (log)
473 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
474
475 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000476 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
477 &m_private_state_broadcaster,
478 eBroadcastBitStateChanged,
479 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000480 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
481
482 // This is a bit of a hack, but when we wait here we could very well return
483 // to the command-line, and that could disable the log, which would render the
484 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000485 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000486 {
487 if (state == eStateInvalid)
488 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
489 else
490 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
491 }
Chris Lattner24943d22010-06-08 16:52:24 +0000492 return state;
493}
494
495bool
496Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
497{
Greg Claytone005f2c2010-11-06 01:53:30 +0000498 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000499
500 if (log)
501 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
502
503 if (control_only)
504 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
505 else
506 return m_private_state_listener.WaitForEvent(timeout, event_sp);
507}
508
509bool
510Process::IsRunning () const
511{
512 return StateIsRunningState (m_public_state.GetValue());
513}
514
515int
516Process::GetExitStatus ()
517{
518 if (m_public_state.GetValue() == eStateExited)
519 return m_exit_status;
520 return -1;
521}
522
Greg Clayton638351a2010-12-04 00:10:17 +0000523
524void
525Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
526{
527 if (m_inherit_host_env && !m_got_host_env)
528 {
529 m_got_host_env = true;
530 StringList host_env;
531 const size_t host_env_count = Host::GetEnvironment (host_env);
532 for (size_t idx=0; idx<host_env_count; idx++)
533 {
534 const char *env_entry = host_env.GetStringAtIndex (idx);
535 if (env_entry)
536 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000537 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000538 if (equal_pos)
539 {
540 std::string key (env_entry, equal_pos - env_entry);
541 std::string value (equal_pos + 1);
542 if (m_env_vars.find (key) == m_env_vars.end())
543 m_env_vars[key] = value;
544 }
545 }
546 }
547 }
548}
549
550
551size_t
552Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
553{
554 GetHostEnvironmentIfNeeded ();
555
556 dictionary::const_iterator pos, end = m_env_vars.end();
557 for (pos = m_env_vars.begin(); pos != end; ++pos)
558 {
559 std::string env_var_equal_value (pos->first);
560 env_var_equal_value.append(1, '=');
561 env_var_equal_value.append (pos->second);
562 env.AppendArgument (env_var_equal_value.c_str());
563 }
564 return env.GetArgumentCount();
565}
566
567
Chris Lattner24943d22010-06-08 16:52:24 +0000568const char *
569Process::GetExitDescription ()
570{
571 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
572 return m_exit_string.c_str();
573 return NULL;
574}
575
Greg Clayton72e1c782011-01-22 23:43:18 +0000576bool
Chris Lattner24943d22010-06-08 16:52:24 +0000577Process::SetExitStatus (int status, const char *cstr)
578{
Greg Clayton68ca8232011-01-25 02:58:48 +0000579 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
580 if (log)
581 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
582 status, status,
583 cstr ? "\"" : "",
584 cstr ? cstr : "NULL",
585 cstr ? "\"" : "");
586
Greg Clayton72e1c782011-01-22 23:43:18 +0000587 // We were already in the exited state
588 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +0000589 {
Greg Clayton644ddfb2011-01-26 23:47:29 +0000590 if (log)
591 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +0000592 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +0000593 }
Greg Clayton72e1c782011-01-22 23:43:18 +0000594
595 m_exit_status = status;
596 if (cstr)
597 m_exit_string = cstr;
598 else
599 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000600
Greg Clayton72e1c782011-01-22 23:43:18 +0000601 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +0000602
Greg Clayton72e1c782011-01-22 23:43:18 +0000603 SetPrivateState (eStateExited);
604 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000605}
606
607// This static callback can be used to watch for local child processes on
608// the current host. The the child process exits, the process will be
609// found in the global target list (we want to be completely sure that the
610// lldb_private::Process doesn't go away before we can deliver the signal.
611bool
612Process::SetProcessExitStatus
613(
614 void *callback_baton,
615 lldb::pid_t pid,
616 int signo, // Zero for no signal
617 int exit_status // Exit value of process if signal is zero
618)
619{
620 if (signo == 0 || exit_status)
621 {
Greg Clayton63094e02010-06-23 01:19:29 +0000622 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000623 if (target_sp)
624 {
625 ProcessSP process_sp (target_sp->GetProcessSP());
626 if (process_sp)
627 {
628 const char *signal_cstr = NULL;
629 if (signo)
630 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
631
632 process_sp->SetExitStatus (exit_status, signal_cstr);
633 }
634 }
635 return true;
636 }
637 return false;
638}
639
640
641uint32_t
642Process::GetNextThreadIndexID ()
643{
644 return ++m_thread_index_id;
645}
646
647StateType
648Process::GetState()
649{
650 // If any other threads access this we will need a mutex for it
651 return m_public_state.GetValue ();
652}
653
654void
655Process::SetPublicState (StateType new_state)
656{
Greg Clayton68ca8232011-01-25 02:58:48 +0000657 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000658 if (log)
659 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
660 m_public_state.SetValue (new_state);
661}
662
663StateType
664Process::GetPrivateState ()
665{
666 return m_private_state.GetValue();
667}
668
669void
670Process::SetPrivateState (StateType new_state)
671{
Greg Clayton68ca8232011-01-25 02:58:48 +0000672 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000673 bool state_changed = false;
674
675 if (log)
676 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
677
678 Mutex::Locker locker(m_private_state.GetMutex());
679
680 const StateType old_state = m_private_state.GetValueNoLock ();
681 state_changed = old_state != new_state;
682 if (state_changed)
683 {
684 m_private_state.SetValueNoLock (new_state);
685 if (StateIsStoppedState(new_state))
686 {
687 m_stop_id++;
Greg Claytonfd119992011-01-07 06:08:19 +0000688 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000689 if (log)
690 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
691 }
692 // Use our target to get a shared pointer to ourselves...
693 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
694 }
695 else
696 {
697 if (log)
698 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
699 }
700}
701
702
703uint32_t
704Process::GetStopID() const
705{
706 return m_stop_id;
707}
708
709addr_t
710Process::GetImageInfoAddress()
711{
712 return LLDB_INVALID_ADDRESS;
713}
714
Greg Clayton0baa3942010-11-04 01:54:29 +0000715//----------------------------------------------------------------------
716// LoadImage
717//
718// This function provides a default implementation that works for most
719// unix variants. Any Process subclasses that need to do shared library
720// loading differently should override LoadImage and UnloadImage and
721// do what is needed.
722//----------------------------------------------------------------------
723uint32_t
724Process::LoadImage (const FileSpec &image_spec, Error &error)
725{
726 DynamicLoader *loader = GetDynamicLoader();
727 if (loader)
728 {
729 error = loader->CanLoadImage();
730 if (error.Fail())
731 return LLDB_INVALID_IMAGE_TOKEN;
732 }
733
734 if (error.Success())
735 {
736 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
737 if (thread_sp == NULL)
738 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
739
740 if (thread_sp)
741 {
742 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
743
744 if (frame_sp)
745 {
746 ExecutionContext exe_ctx;
747 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000748 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000749 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000750 StreamString expr;
751 char path[PATH_MAX];
752 image_spec.GetPath(path, sizeof(path));
753 expr.Printf("dlopen (\"%s\", 2)", path);
754 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000755 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000756 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000757 if (result_valobj_sp->GetError().Success())
758 {
759 Scalar scalar;
760 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
761 {
762 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
763 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
764 {
765 uint32_t image_token = m_image_tokens.size();
766 m_image_tokens.push_back (image_ptr);
767 return image_token;
768 }
769 }
770 }
771 }
772 }
773 }
774 return LLDB_INVALID_IMAGE_TOKEN;
775}
776
777//----------------------------------------------------------------------
778// UnloadImage
779//
780// This function provides a default implementation that works for most
781// unix variants. Any Process subclasses that need to do shared library
782// loading differently should override LoadImage and UnloadImage and
783// do what is needed.
784//----------------------------------------------------------------------
785Error
786Process::UnloadImage (uint32_t image_token)
787{
788 Error error;
789 if (image_token < m_image_tokens.size())
790 {
791 const addr_t image_addr = m_image_tokens[image_token];
792 if (image_addr == LLDB_INVALID_ADDRESS)
793 {
794 error.SetErrorString("image already unloaded");
795 }
796 else
797 {
798 DynamicLoader *loader = GetDynamicLoader();
799 if (loader)
800 error = loader->CanLoadImage();
801
802 if (error.Success())
803 {
804 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
805 if (thread_sp == NULL)
806 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
807
808 if (thread_sp)
809 {
810 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
811
812 if (frame_sp)
813 {
814 ExecutionContext exe_ctx;
815 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000816 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000817 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000818 StreamString expr;
819 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
820 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000821 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000822 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000823 if (result_valobj_sp->GetError().Success())
824 {
825 Scalar scalar;
826 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
827 {
828 if (scalar.UInt(1))
829 {
830 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
831 }
832 else
833 {
834 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
835 }
836 }
837 }
838 else
839 {
840 error = result_valobj_sp->GetError();
841 }
842 }
843 }
844 }
845 }
846 }
847 else
848 {
849 error.SetErrorString("invalid image token");
850 }
851 return error;
852}
853
Chris Lattner24943d22010-06-08 16:52:24 +0000854const ABI *
855Process::GetABI()
856{
Chris Lattner24943d22010-06-08 16:52:24 +0000857 if (m_abi_sp.get() == NULL)
Greg Clayton395fc332011-02-15 21:59:32 +0000858 m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
Chris Lattner24943d22010-06-08 16:52:24 +0000859
860 return m_abi_sp.get();
861}
862
Jim Ingham642036f2010-09-23 02:01:19 +0000863LanguageRuntime *
864Process::GetLanguageRuntime(lldb::LanguageType language)
865{
866 LanguageRuntimeCollection::iterator pos;
867 pos = m_language_runtimes.find (language);
868 if (pos == m_language_runtimes.end())
869 {
870 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
871
872 m_language_runtimes[language]
873 = runtime;
874 return runtime.get();
875 }
876 else
877 return (*pos).second.get();
878}
879
880CPPLanguageRuntime *
881Process::GetCPPLanguageRuntime ()
882{
883 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
884 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
885 return static_cast<CPPLanguageRuntime *> (runtime);
886 return NULL;
887}
888
889ObjCLanguageRuntime *
890Process::GetObjCLanguageRuntime ()
891{
892 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
893 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
894 return static_cast<ObjCLanguageRuntime *> (runtime);
895 return NULL;
896}
897
Chris Lattner24943d22010-06-08 16:52:24 +0000898BreakpointSiteList &
899Process::GetBreakpointSiteList()
900{
901 return m_breakpoint_site_list;
902}
903
904const BreakpointSiteList &
905Process::GetBreakpointSiteList() const
906{
907 return m_breakpoint_site_list;
908}
909
910
911void
912Process::DisableAllBreakpointSites ()
913{
914 m_breakpoint_site_list.SetEnabledForAll (false);
915}
916
917Error
918Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
919{
920 Error error (DisableBreakpointSiteByID (break_id));
921
922 if (error.Success())
923 m_breakpoint_site_list.Remove(break_id);
924
925 return error;
926}
927
928Error
929Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
930{
931 Error error;
932 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
933 if (bp_site_sp)
934 {
935 if (bp_site_sp->IsEnabled())
936 error = DisableBreakpoint (bp_site_sp.get());
937 }
938 else
939 {
940 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
941 }
942
943 return error;
944}
945
946Error
947Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
948{
949 Error error;
950 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
951 if (bp_site_sp)
952 {
953 if (!bp_site_sp->IsEnabled())
954 error = EnableBreakpoint (bp_site_sp.get());
955 }
956 else
957 {
958 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
959 }
960 return error;
961}
962
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000963lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000964Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
965{
Greg Claytoneea26402010-09-14 23:36:40 +0000966 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000967 if (load_addr != LLDB_INVALID_ADDRESS)
968 {
969 BreakpointSiteSP bp_site_sp;
970
971 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
972 // create a new breakpoint site and add it.
973
974 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
975
976 if (bp_site_sp)
977 {
978 bp_site_sp->AddOwner (owner);
979 owner->SetBreakpointSite (bp_site_sp);
980 return bp_site_sp->GetID();
981 }
982 else
983 {
984 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
985 if (bp_site_sp)
986 {
987 if (EnableBreakpoint (bp_site_sp.get()).Success())
988 {
989 owner->SetBreakpointSite (bp_site_sp);
990 return m_breakpoint_site_list.Add (bp_site_sp);
991 }
992 }
993 }
994 }
995 // We failed to enable the breakpoint
996 return LLDB_INVALID_BREAK_ID;
997
998}
999
1000void
1001Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1002{
1003 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1004 if (num_owners == 0)
1005 {
1006 DisableBreakpoint(bp_site_sp.get());
1007 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1008 }
1009}
1010
1011
1012size_t
1013Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1014{
1015 size_t bytes_removed = 0;
1016 addr_t intersect_addr;
1017 size_t intersect_size;
1018 size_t opcode_offset;
1019 size_t idx;
1020 BreakpointSiteSP bp;
1021
1022 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1023 {
1024 if (bp->GetType() == BreakpointSite::eSoftware)
1025 {
1026 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1027 {
1028 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1029 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1030 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1031 size_t buf_offset = intersect_addr - bp_addr;
1032 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1033 }
1034 }
1035 }
1036 return bytes_removed;
1037}
1038
1039
1040Error
1041Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1042{
1043 Error error;
1044 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001045 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001046 const addr_t bp_addr = bp_site->GetLoadAddress();
1047 if (log)
1048 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1049 if (bp_site->IsEnabled())
1050 {
1051 if (log)
1052 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1053 return error;
1054 }
1055
1056 if (bp_addr == LLDB_INVALID_ADDRESS)
1057 {
1058 error.SetErrorString("BreakpointSite contains an invalid load address.");
1059 return error;
1060 }
1061 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1062 // trap for the breakpoint site
1063 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1064
1065 if (bp_opcode_size == 0)
1066 {
1067 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1068 }
1069 else
1070 {
1071 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1072
1073 if (bp_opcode_bytes == NULL)
1074 {
1075 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1076 return error;
1077 }
1078
1079 // Save the original opcode by reading it
1080 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1081 {
1082 // Write a software breakpoint in place of the original opcode
1083 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1084 {
1085 uint8_t verify_bp_opcode_bytes[64];
1086 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1087 {
1088 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1089 {
1090 bp_site->SetEnabled(true);
1091 bp_site->SetType (BreakpointSite::eSoftware);
1092 if (log)
1093 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1094 bp_site->GetID(),
1095 (uint64_t)bp_addr);
1096 }
1097 else
1098 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1099 }
1100 else
1101 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1102 }
1103 else
1104 error.SetErrorString("Unable to write breakpoint trap to memory.");
1105 }
1106 else
1107 error.SetErrorString("Unable to read memory at breakpoint address.");
1108 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001109 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001110 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1111 bp_site->GetID(),
1112 (uint64_t)bp_addr,
1113 error.AsCString());
1114 return error;
1115}
1116
1117Error
1118Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1119{
1120 Error error;
1121 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001122 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001123 addr_t bp_addr = bp_site->GetLoadAddress();
1124 lldb::user_id_t breakID = bp_site->GetID();
1125 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001126 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001127
1128 if (bp_site->IsHardware())
1129 {
1130 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1131 }
1132 else if (bp_site->IsEnabled())
1133 {
1134 const size_t break_op_size = bp_site->GetByteSize();
1135 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1136 if (break_op_size > 0)
1137 {
1138 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001139 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001140 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001141 bool break_op_found = false;
1142
1143 // Read the breakpoint opcode
1144 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1145 {
1146 bool verify = false;
1147 // Make sure we have the a breakpoint opcode exists at this address
1148 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1149 {
1150 break_op_found = true;
1151 // We found a valid breakpoint opcode at this address, now restore
1152 // the saved opcode.
1153 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1154 {
1155 verify = true;
1156 }
1157 else
1158 error.SetErrorString("Memory write failed when restoring original opcode.");
1159 }
1160 else
1161 {
1162 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1163 // Set verify to true and so we can check if the original opcode has already been restored
1164 verify = true;
1165 }
1166
1167 if (verify)
1168 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001169 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001170 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001171 // Verify that our original opcode made it back to the inferior
1172 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1173 {
1174 // compare the memory we just read with the original opcode
1175 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1176 {
1177 // SUCCESS
1178 bp_site->SetEnabled(false);
1179 if (log)
1180 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1181 return error;
1182 }
1183 else
1184 {
1185 if (break_op_found)
1186 error.SetErrorString("Failed to restore original opcode.");
1187 }
1188 }
1189 else
1190 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1191 }
1192 }
1193 else
1194 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1195 }
1196 }
1197 else
1198 {
1199 if (log)
1200 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1201 return error;
1202 }
1203
1204 if (log)
1205 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1206 bp_site->GetID(),
1207 (uint64_t)bp_addr,
1208 error.AsCString());
1209 return error;
1210
1211}
1212
Greg Claytonfd119992011-01-07 06:08:19 +00001213// Comment out line below to disable memory caching
1214#define ENABLE_MEMORY_CACHING
1215// Uncomment to verify memory caching works after making changes to caching code
1216//#define VERIFY_MEMORY_READS
1217
1218#if defined (ENABLE_MEMORY_CACHING)
1219
1220#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001221
1222size_t
1223Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1224{
Greg Claytonfd119992011-01-07 06:08:19 +00001225 // Memory caching is enabled, with debug verification
1226 if (buf && size)
1227 {
1228 // Uncomment the line below to make sure memory caching is working.
1229 // I ran this through the test suite and got no assertions, so I am
1230 // pretty confident this is working well. If any changes are made to
1231 // memory caching, uncomment the line below and test your changes!
1232
1233 // Verify all memory reads by using the cache first, then redundantly
1234 // reading the same memory from the inferior and comparing to make sure
1235 // everything is exactly the same.
1236 std::string verify_buf (size, '\0');
1237 assert (verify_buf.size() == size);
1238 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1239 Error verify_error;
1240 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1241 assert (cache_bytes_read == verify_bytes_read);
1242 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1243 assert (verify_error.Success() == error.Success());
1244 return cache_bytes_read;
1245 }
1246 return 0;
1247}
1248
1249#else // #if defined (VERIFY_MEMORY_READS)
1250
1251size_t
1252Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1253{
1254 // Memory caching enabled, no verification
1255 return m_memory_cache.Read (this, addr, buf, size, error);
1256}
1257
1258#endif // #else for #if defined (VERIFY_MEMORY_READS)
1259
1260#else // #if defined (ENABLE_MEMORY_CACHING)
1261
1262size_t
1263Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1264{
1265 // Memory caching is disabled
1266 return ReadMemoryFromInferior (addr, buf, size, error);
1267}
1268
1269#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1270
1271
1272size_t
1273Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1274{
Chris Lattner24943d22010-06-08 16:52:24 +00001275 if (buf == NULL || size == 0)
1276 return 0;
1277
1278 size_t bytes_read = 0;
1279 uint8_t *bytes = (uint8_t *)buf;
1280
1281 while (bytes_read < size)
1282 {
1283 const size_t curr_size = size - bytes_read;
1284 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1285 bytes + bytes_read,
1286 curr_size,
1287 error);
1288 bytes_read += curr_bytes_read;
1289 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1290 break;
1291 }
1292
1293 // Replace any software breakpoint opcodes that fall into this range back
1294 // into "buf" before we return
1295 if (bytes_read > 0)
1296 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1297 return bytes_read;
1298}
1299
Greg Claytonf72fdee2010-12-16 20:01:20 +00001300uint64_t
1301Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1302{
1303 if (integer_byte_size > sizeof(uint64_t))
1304 {
1305 error.SetErrorString ("unsupported integer size");
1306 }
1307 else
1308 {
1309 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton395fc332011-02-15 21:59:32 +00001310 DataExtractor data (tmp,
1311 integer_byte_size,
1312 m_target.GetArchitecture().GetByteOrder(),
1313 m_target.GetArchitecture().GetAddressByteSize());
Greg Claytonf72fdee2010-12-16 20:01:20 +00001314 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1315 {
1316 uint32_t offset = 0;
1317 return data.GetMaxU64 (&offset, integer_byte_size);
1318 }
1319 }
1320 // Any plug-in that doesn't return success a memory read with the number
1321 // of bytes that were requested should be setting the error
1322 assert (error.Fail());
1323 return 0;
1324}
1325
Chris Lattner24943d22010-06-08 16:52:24 +00001326size_t
1327Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1328{
1329 size_t bytes_written = 0;
1330 const uint8_t *bytes = (const uint8_t *)buf;
1331
1332 while (bytes_written < size)
1333 {
1334 const size_t curr_size = size - bytes_written;
1335 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1336 bytes + bytes_written,
1337 curr_size,
1338 error);
1339 bytes_written += curr_bytes_written;
1340 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1341 break;
1342 }
1343 return bytes_written;
1344}
1345
1346size_t
1347Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1348{
Greg Claytonfd119992011-01-07 06:08:19 +00001349#if defined (ENABLE_MEMORY_CACHING)
1350 m_memory_cache.Flush (addr, size);
1351#endif
1352
Chris Lattner24943d22010-06-08 16:52:24 +00001353 if (buf == NULL || size == 0)
1354 return 0;
1355 // We need to write any data that would go where any current software traps
1356 // (enabled software breakpoints) any software traps (breakpoints) that we
1357 // may have placed in our tasks memory.
1358
1359 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1360 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1361
1362 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1363 return DoWriteMemory(addr, buf, size, error);
1364
1365 BreakpointSiteList::collection::const_iterator pos;
1366 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001367 addr_t intersect_addr = 0;
1368 size_t intersect_size = 0;
1369 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001370 const uint8_t *ubuf = (const uint8_t *)buf;
1371
1372 for (pos = iter; pos != end; ++pos)
1373 {
1374 BreakpointSiteSP bp;
1375 bp = pos->second;
1376
1377 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1378 assert(addr <= intersect_addr && intersect_addr < addr + size);
1379 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1380 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1381
1382 // Check for bytes before this breakpoint
1383 const addr_t curr_addr = addr + bytes_written;
1384 if (intersect_addr > curr_addr)
1385 {
1386 // There are some bytes before this breakpoint that we need to
1387 // just write to memory
1388 size_t curr_size = intersect_addr - curr_addr;
1389 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1390 ubuf + bytes_written,
1391 curr_size,
1392 error);
1393 bytes_written += curr_bytes_written;
1394 if (curr_bytes_written != curr_size)
1395 {
1396 // We weren't able to write all of the requested bytes, we
1397 // are done looping and will return the number of bytes that
1398 // we have written so far.
1399 break;
1400 }
1401 }
1402
1403 // Now write any bytes that would cover up any software breakpoints
1404 // directly into the breakpoint opcode buffer
1405 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1406 bytes_written += intersect_size;
1407 }
1408
1409 // Write any remaining bytes after the last breakpoint if we have any left
1410 if (bytes_written < size)
1411 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1412 ubuf + bytes_written,
1413 size - bytes_written,
1414 error);
1415
1416 return bytes_written;
1417}
1418
1419addr_t
1420Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1421{
1422 // Fixme: we should track the blocks we've allocated, and clean them up...
1423 // We could even do our own allocator here if that ends up being more efficient.
Greg Clayton2860ba92011-01-23 19:58:49 +00001424 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1425 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1426 if (log)
Greg Claytonb349adc2011-01-24 06:30:45 +00001427 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001428 size,
1429 permissions & ePermissionsReadable ? 'r' : '-',
1430 permissions & ePermissionsWritable ? 'w' : '-',
1431 permissions & ePermissionsExecutable ? 'x' : '-',
1432 (uint64_t)allocated_addr,
1433 m_stop_id);
1434 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001435}
1436
1437Error
1438Process::DeallocateMemory (addr_t ptr)
1439{
Greg Clayton2860ba92011-01-23 19:58:49 +00001440 Error error(DoDeallocateMemory (ptr));
1441
1442 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1443 if (log)
1444 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1445 ptr,
1446 error.AsCString("SUCCESS"),
1447 m_stop_id);
1448 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001449}
1450
1451
1452Error
1453Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1454{
1455 Error error;
1456 error.SetErrorString("watchpoints are not supported");
1457 return error;
1458}
1459
1460Error
1461Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1462{
1463 Error error;
1464 error.SetErrorString("watchpoints are not supported");
1465 return error;
1466}
1467
1468StateType
1469Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1470{
1471 StateType state;
1472 // Now wait for the process to launch and return control to us, and then
1473 // call DidLaunch:
1474 while (1)
1475 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001476 event_sp.reset();
1477 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1478
1479 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001480 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001481
1482 // If state is invalid, then we timed out
1483 if (state == eStateInvalid)
1484 break;
1485
1486 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001487 HandlePrivateEvent (event_sp);
1488 }
1489 return state;
1490}
1491
1492Error
1493Process::Launch
1494(
1495 char const *argv[],
1496 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001497 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001498 const char *stdin_path,
1499 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001500 const char *stderr_path,
1501 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001502)
1503{
1504 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001505 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00001506 m_dyld_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001507 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001508
1509 Module *exe_module = m_target.GetExecutableModule().get();
1510 if (exe_module)
1511 {
1512 char exec_file_path[PATH_MAX];
1513 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1514 if (exe_module->GetFileSpec().Exists())
1515 {
Greg Claytona2f74232011-02-24 22:24:29 +00001516 if (PrivateStateThreadIsValid ())
1517 PausePrivateStateThread ();
1518
Chris Lattner24943d22010-06-08 16:52:24 +00001519 error = WillLaunch (exe_module);
1520 if (error.Success())
1521 {
Greg Claytond8c62532010-10-07 04:19:01 +00001522 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001523 // The args coming in should not contain the application name, the
1524 // lldb_private::Process class will add this in case the executable
1525 // gets resolved to a different file than was given on the command
1526 // line (like when an applicaiton bundle is specified and will
1527 // resolve to the contained exectuable file, or the file given was
1528 // a symlink or other file system link that resolves to a different
1529 // file).
1530
1531 // Get the resolved exectuable path
1532
1533 // Make a new argument vector
1534 std::vector<const char *> exec_path_plus_argv;
1535 // Append the resolved executable path
1536 exec_path_plus_argv.push_back (exec_file_path);
1537
1538 // Push all args if there are any
1539 if (argv)
1540 {
1541 for (int i = 0; argv[i]; ++i)
1542 exec_path_plus_argv.push_back(argv[i]);
1543 }
1544
1545 // Push a NULL to terminate the args.
1546 exec_path_plus_argv.push_back(NULL);
1547
1548 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001549 error = DoLaunch (exe_module,
1550 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1551 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001552 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001553 stdin_path,
1554 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001555 stderr_path,
1556 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001557
1558 if (error.Fail())
1559 {
1560 if (GetID() != LLDB_INVALID_PROCESS_ID)
1561 {
1562 SetID (LLDB_INVALID_PROCESS_ID);
1563 const char *error_string = error.AsCString();
1564 if (error_string == NULL)
1565 error_string = "launch failed";
1566 SetExitStatus (-1, error_string);
1567 }
1568 }
1569 else
1570 {
1571 EventSP event_sp;
1572 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1573
1574 if (state == eStateStopped || state == eStateCrashed)
1575 {
Greg Clayton75c703d2011-02-16 04:46:07 +00001576
Chris Lattner24943d22010-06-08 16:52:24 +00001577 DidLaunch ();
1578
Greg Clayton75c703d2011-02-16 04:46:07 +00001579 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1580 if (m_dyld_ap.get())
1581 m_dyld_ap->DidLaunch();
1582
Chris Lattner24943d22010-06-08 16:52:24 +00001583 // This delays passing the stopped event to listeners till DidLaunch gets
1584 // a chance to complete...
1585 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00001586
1587 if (PrivateStateThreadIsValid ())
1588 ResumePrivateStateThread ();
1589 else
1590 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001591 }
1592 else if (state == eStateExited)
1593 {
1594 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1595 // not likely to work, and return an invalid pid.
1596 HandlePrivateEvent (event_sp);
1597 }
1598 }
1599 }
1600 }
1601 else
1602 {
1603 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1604 }
1605 }
1606 return error;
1607}
1608
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001609Process::NextEventAction::EventActionResult
1610Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001611{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001612 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1613 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00001614 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001615 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00001616 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001617 return eEventActionRetry;
1618
1619 case eStateStopped:
1620 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00001621 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001622 // During attach, prior to sending the eStateStopped event,
1623 // lldb_private::Process subclasses must set the process must set
1624 // the new process ID.
1625 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00001626 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001627 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00001628 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001629
1630
1631 break;
1632 default:
1633 case eStateExited:
1634 case eStateInvalid:
1635 m_exit_string.assign ("No valid Process");
1636 return eEventActionExit;
1637 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001638 }
1639}
Chris Lattner24943d22010-06-08 16:52:24 +00001640
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001641Process::NextEventAction::EventActionResult
1642Process::AttachCompletionHandler::HandleBeingInterrupted()
1643{
1644 return eEventActionSuccess;
1645}
1646
1647const char *
1648Process::AttachCompletionHandler::GetExitString ()
1649{
1650 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00001651}
1652
1653Error
1654Process::Attach (lldb::pid_t attach_pid)
1655{
1656
Chris Lattner24943d22010-06-08 16:52:24 +00001657 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001658 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001659
Jim Ingham7508e732010-08-09 23:31:02 +00001660 // Find the process and its architecture. Make sure it matches the architecture
1661 // of the current Target, and if not adjust it.
1662
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001663 ProcessInfo process_info;
1664 PlatformSP platform_sp (Platform::GetSelectedPlatform ());
1665 if (platform_sp)
Jim Ingham7508e732010-08-09 23:31:02 +00001666 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001667 if (platform_sp->GetProcessInfo (attach_pid, process_info))
1668 {
1669 const ArchSpec &process_arch = process_info.GetArchitecture();
1670 if (process_arch.IsValid())
1671 GetTarget().SetArchitecture(process_arch);
1672 }
Jim Ingham7508e732010-08-09 23:31:02 +00001673 }
1674
Greg Clayton75c703d2011-02-16 04:46:07 +00001675 m_dyld_ap.reset();
1676
Greg Clayton54e7afa2010-07-09 20:39:50 +00001677 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001678 if (error.Success())
1679 {
Greg Claytond8c62532010-10-07 04:19:01 +00001680 SetPublicState (eStateAttaching);
1681
Greg Clayton54e7afa2010-07-09 20:39:50 +00001682 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001683 if (error.Success())
1684 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001685 SetNextEventAction(new Process::AttachCompletionHandler(this));
1686 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001687 }
1688 else
1689 {
1690 if (GetID() != LLDB_INVALID_PROCESS_ID)
1691 {
1692 SetID (LLDB_INVALID_PROCESS_ID);
1693 const char *error_string = error.AsCString();
1694 if (error_string == NULL)
1695 error_string = "attach failed";
1696
1697 SetExitStatus(-1, error_string);
1698 }
1699 }
1700 }
1701 return error;
1702}
1703
1704Error
1705Process::Attach (const char *process_name, bool wait_for_launch)
1706{
Chris Lattner24943d22010-06-08 16:52:24 +00001707 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001708 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001709
1710 // Find the process and its architecture. Make sure it matches the architecture
1711 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001712 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00001713
Jim Inghamea294182010-08-17 21:54:19 +00001714 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001715 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001716 ProcessInfoList process_infos;
1717 PlatformSP platform_sp (Platform::GetSelectedPlatform ());
1718 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00001719 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001720 platform_sp->FindProcessesByName (process_name, eNameMatchEquals, process_infos);
1721 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00001722 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001723 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
1724 }
1725 else if (process_infos.GetSize() == 0)
1726 {
1727 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
1728 }
1729 else
1730 {
1731 ProcessInfo process_info;
1732 if (process_infos.GetInfoAtIndex (0, process_info))
1733 {
1734 const ArchSpec &process_arch = process_info.GetArchitecture();
1735 if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
1736 {
1737 // Set the architecture on the target.
1738 GetTarget().SetArchitecture (process_arch);
1739 }
1740 }
Chris Lattner24943d22010-06-08 16:52:24 +00001741 }
1742 }
1743 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001744 {
1745 error.SetErrorString ("Invalid platform");
1746 }
1747 }
1748
1749 if (error.Success())
1750 {
1751 m_dyld_ap.reset();
1752
1753 error = WillAttachToProcessWithName(process_name, wait_for_launch);
1754 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00001755 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001756 SetPublicState (eStateAttaching);
1757 error = DoAttachToProcessWithName (process_name, wait_for_launch);
1758 if (error.Fail())
1759 {
1760 if (GetID() != LLDB_INVALID_PROCESS_ID)
1761 {
1762 SetID (LLDB_INVALID_PROCESS_ID);
1763 const char *error_string = error.AsCString();
1764 if (error_string == NULL)
1765 error_string = "attach failed";
1766
1767 SetExitStatus(-1, error_string);
1768 }
1769 }
1770 else
1771 {
1772 SetNextEventAction(new Process::AttachCompletionHandler(this));
1773 StartPrivateStateThread();
1774 }
Chris Lattner24943d22010-06-08 16:52:24 +00001775 }
1776 }
1777 return error;
1778}
1779
Greg Clayton75c703d2011-02-16 04:46:07 +00001780void
1781Process::CompleteAttach ()
1782{
1783 // Let the process subclass figure out at much as it can about the process
1784 // before we go looking for a dynamic loader plug-in.
1785 DidAttach();
1786
1787 // We have complete the attach, now it is time to find the dynamic loader
1788 // plug-in
1789 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1790 if (m_dyld_ap.get())
1791 m_dyld_ap->DidAttach();
1792
1793 // Figure out which one is the executable, and set that in our target:
1794 ModuleList &modules = m_target.GetImages();
1795
1796 size_t num_modules = modules.GetSize();
1797 for (int i = 0; i < num_modules; i++)
1798 {
1799 ModuleSP module_sp (modules.GetModuleAtIndex(i));
1800 if (module_sp->IsExecutable())
1801 {
1802 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
1803 if (target_exe_module_sp != module_sp)
1804 m_target.SetExecutableModule (module_sp, false);
1805 break;
1806 }
1807 }
1808}
1809
Chris Lattner24943d22010-06-08 16:52:24 +00001810Error
Greg Claytone71e2582011-02-04 01:58:07 +00001811Process::ConnectRemote (const char *remote_url)
1812{
Greg Claytone71e2582011-02-04 01:58:07 +00001813 m_abi_sp.reset();
1814 m_process_input_reader.reset();
1815
1816 // Find the process and its architecture. Make sure it matches the architecture
1817 // of the current Target, and if not adjust it.
1818
1819 Error error (DoConnectRemote (remote_url));
1820 if (error.Success())
1821 {
Greg Claytona2f74232011-02-24 22:24:29 +00001822 StartPrivateStateThread();
1823 // If we attached and actually have a process on the other end, then
1824 // this ended up being the equivalent of an attach.
1825 if (GetID() != LLDB_INVALID_PROCESS_ID)
1826 {
1827 CompleteAttach ();
1828 }
Greg Claytone71e2582011-02-04 01:58:07 +00001829 }
1830 return error;
1831}
1832
1833
1834Error
Chris Lattner24943d22010-06-08 16:52:24 +00001835Process::Resume ()
1836{
Greg Claytone005f2c2010-11-06 01:53:30 +00001837 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001838 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00001839 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1840 m_stop_id,
1841 StateAsCString(m_public_state.GetValue()),
1842 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00001843
1844 Error error (WillResume());
1845 // Tell the process it is about to resume before the thread list
1846 if (error.Success())
1847 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001848 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001849 // can let all of our threads know that they are about to be
1850 // resumed. Threads will each be called with
1851 // Thread::WillResume(StateType) where StateType contains the state
1852 // that they are supposed to have when the process is resumed
1853 // (suspended/running/stepping). Threads should also check
1854 // their resume signal in lldb::Thread::GetResumeSignal()
1855 // to see if they are suppoed to start back up with a signal.
1856 if (m_thread_list.WillResume())
1857 {
1858 error = DoResume();
1859 if (error.Success())
1860 {
1861 DidResume();
1862 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00001863 if (log)
1864 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00001865 }
1866 }
1867 else
1868 {
Jim Inghamac959662011-01-24 06:34:17 +00001869 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00001870 }
1871 }
Jim Inghamac959662011-01-24 06:34:17 +00001872 else if (log)
1873 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00001874 return error;
1875}
1876
1877Error
1878Process::Halt ()
1879{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001880 // Pause our private state thread so we can ensure no one else eats
1881 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00001882 Listener halt_listener ("lldb.process.halt_listener");
1883 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00001884
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001885 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001886 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001887
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001888 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001889 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001890
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001891 bool caused_stop = false;
1892
1893 // Ask the process subclass to actually halt our process
1894 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001895 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001896 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001897 if (m_public_state.GetValue() == eStateAttaching)
1898 {
1899 SetExitStatus(SIGKILL, "Cancelled async attach.");
1900 Destroy ();
1901 }
1902 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00001903 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001904 // If "caused_stop" is true, then DoHalt stopped the process. If
1905 // "caused_stop" is false, the process was already stopped.
1906 // If the DoHalt caused the process to stop, then we want to catch
1907 // this event and set the interrupted bool to true before we pass
1908 // this along so clients know that the process was interrupted by
1909 // a halt command.
1910 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00001911 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00001912 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001913 TimeValue timeout_time;
1914 timeout_time = TimeValue::Now();
1915 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001916 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1917 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001918
Jim Inghamf9f40c22011-02-08 05:20:59 +00001919 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00001920 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001921 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00001922 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00001923 }
1924 else
1925 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001926 if (StateIsStoppedState (state))
1927 {
1928 // We caused the process to interrupt itself, so mark this
1929 // as such in the stop event so clients can tell an interrupted
1930 // process from a natural stop
1931 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1932 }
1933 else
1934 {
1935 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1936 if (log)
1937 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1938 error.SetErrorString ("Did not get stopped event after halt.");
1939 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001940 }
1941 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001942 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00001943 }
1944 }
Chris Lattner24943d22010-06-08 16:52:24 +00001945 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001946 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00001947 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001948
1949 // Post any event we might have consumed. If all goes well, we will have
1950 // stopped the process, intercepted the event and set the interrupted
1951 // bool in the event. Post it to the private event queue and that will end up
1952 // correctly setting the state.
1953 if (event_sp)
1954 m_private_state_broadcaster.BroadcastEvent(event_sp);
1955
Chris Lattner24943d22010-06-08 16:52:24 +00001956 return error;
1957}
1958
1959Error
1960Process::Detach ()
1961{
1962 Error error (WillDetach());
1963
1964 if (error.Success())
1965 {
1966 DisableAllBreakpointSites();
1967 error = DoDetach();
1968 if (error.Success())
1969 {
1970 DidDetach();
1971 StopPrivateStateThread();
1972 }
1973 }
1974 return error;
1975}
1976
1977Error
1978Process::Destroy ()
1979{
1980 Error error (WillDestroy());
1981 if (error.Success())
1982 {
1983 DisableAllBreakpointSites();
1984 error = DoDestroy();
1985 if (error.Success())
1986 {
1987 DidDestroy();
1988 StopPrivateStateThread();
1989 }
Caroline Tice861efb32010-11-16 05:07:41 +00001990 m_stdio_communication.StopReadThread();
1991 m_stdio_communication.Disconnect();
1992 if (m_process_input_reader && m_process_input_reader->IsActive())
1993 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1994 if (m_process_input_reader)
1995 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001996 }
1997 return error;
1998}
1999
2000Error
2001Process::Signal (int signal)
2002{
2003 Error error (WillSignal());
2004 if (error.Success())
2005 {
2006 error = DoSignal(signal);
2007 if (error.Success())
2008 DidSignal();
2009 }
2010 return error;
2011}
2012
Greg Clayton395fc332011-02-15 21:59:32 +00002013lldb::ByteOrder
2014Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002015{
Greg Clayton395fc332011-02-15 21:59:32 +00002016 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002017}
2018
2019uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002020Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002021{
Greg Clayton395fc332011-02-15 21:59:32 +00002022 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002023}
2024
Greg Clayton395fc332011-02-15 21:59:32 +00002025
Chris Lattner24943d22010-06-08 16:52:24 +00002026bool
2027Process::ShouldBroadcastEvent (Event *event_ptr)
2028{
2029 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2030 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002031 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002032
2033 switch (state)
2034 {
Greg Claytone71e2582011-02-04 01:58:07 +00002035 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002036 case eStateAttaching:
2037 case eStateLaunching:
2038 case eStateDetached:
2039 case eStateExited:
2040 case eStateUnloaded:
2041 // These events indicate changes in the state of the debugging session, always report them.
2042 return_value = true;
2043 break;
2044 case eStateInvalid:
2045 // We stopped for no apparent reason, don't report it.
2046 return_value = false;
2047 break;
2048 case eStateRunning:
2049 case eStateStepping:
2050 // If we've started the target running, we handle the cases where we
2051 // are already running and where there is a transition from stopped to
2052 // running differently.
2053 // running -> running: Automatically suppress extra running events
2054 // stopped -> running: Report except when there is one or more no votes
2055 // and no yes votes.
2056 SynchronouslyNotifyStateChanged (state);
2057 switch (m_public_state.GetValue())
2058 {
2059 case eStateRunning:
2060 case eStateStepping:
2061 // We always suppress multiple runnings with no PUBLIC stop in between.
2062 return_value = false;
2063 break;
2064 default:
2065 // TODO: make this work correctly. For now always report
2066 // run if we aren't running so we don't miss any runnning
2067 // events. If I run the lldb/test/thread/a.out file and
2068 // break at main.cpp:58, run and hit the breakpoints on
2069 // multiple threads, then somehow during the stepping over
2070 // of all breakpoints no run gets reported.
2071 return_value = true;
2072
2073 // This is a transition from stop to run.
2074 switch (m_thread_list.ShouldReportRun (event_ptr))
2075 {
2076 case eVoteYes:
2077 case eVoteNoOpinion:
2078 return_value = true;
2079 break;
2080 case eVoteNo:
2081 return_value = false;
2082 break;
2083 }
2084 break;
2085 }
2086 break;
2087 case eStateStopped:
2088 case eStateCrashed:
2089 case eStateSuspended:
2090 {
2091 // We've stopped. First see if we're going to restart the target.
2092 // If we are going to stop, then we always broadcast the event.
2093 // 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 +00002094 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002095 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002096 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002097 if (log)
2098 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002099 return true;
2100 }
2101 else
2102 {
Chris Lattner24943d22010-06-08 16:52:24 +00002103 RefreshStateAfterStop ();
2104
2105 if (m_thread_list.ShouldStop (event_ptr) == false)
2106 {
2107 switch (m_thread_list.ShouldReportStop (event_ptr))
2108 {
2109 case eVoteYes:
2110 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002111 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002112 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002113 case eVoteNo:
2114 return_value = false;
2115 break;
2116 }
2117
2118 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002119 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002120 Resume ();
2121 }
2122 else
2123 {
2124 return_value = true;
2125 SynchronouslyNotifyStateChanged (state);
2126 }
2127 }
2128 }
2129 }
2130
2131 if (log)
2132 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2133 return return_value;
2134}
2135
Chris Lattner24943d22010-06-08 16:52:24 +00002136
2137bool
2138Process::StartPrivateStateThread ()
2139{
Greg Claytone005f2c2010-11-06 01:53:30 +00002140 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002141
2142 if (log)
2143 log->Printf ("Process::%s ( )", __FUNCTION__);
2144
2145 // Create a thread that watches our internal state and controls which
2146 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002147 char thread_name[1024];
2148 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2149 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002150 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002151}
2152
2153void
2154Process::PausePrivateStateThread ()
2155{
2156 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2157}
2158
2159void
2160Process::ResumePrivateStateThread ()
2161{
2162 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2163}
2164
2165void
2166Process::StopPrivateStateThread ()
2167{
2168 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2169}
2170
2171void
2172Process::ControlPrivateStateThread (uint32_t signal)
2173{
Greg Claytone005f2c2010-11-06 01:53:30 +00002174 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002175
2176 assert (signal == eBroadcastInternalStateControlStop ||
2177 signal == eBroadcastInternalStateControlPause ||
2178 signal == eBroadcastInternalStateControlResume);
2179
2180 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002181 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002182
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002183 // Signal the private state thread. First we should copy this is case the
2184 // thread starts exiting since the private state thread will NULL this out
2185 // when it exits
2186 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002187 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002188 {
2189 TimeValue timeout_time;
2190 bool timed_out;
2191
2192 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2193
2194 timeout_time = TimeValue::Now();
2195 timeout_time.OffsetWithSeconds(2);
2196 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2197 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2198
2199 if (signal == eBroadcastInternalStateControlStop)
2200 {
2201 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002202 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002203
2204 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002205 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002206 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002207 }
2208 }
2209}
2210
2211void
2212Process::HandlePrivateEvent (EventSP &event_sp)
2213{
Greg Claytone005f2c2010-11-06 01:53:30 +00002214 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002215
Greg Clayton68ca8232011-01-25 02:58:48 +00002216 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002217
2218 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002219 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002220 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002221 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002222 switch (action_result)
2223 {
2224 case NextEventAction::eEventActionSuccess:
2225 SetNextEventAction(NULL);
2226 break;
2227 case NextEventAction::eEventActionRetry:
2228 break;
2229 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002230 // Handle Exiting Here. If we already got an exited event,
2231 // we should just propagate it. Otherwise, swallow this event,
2232 // and set our state to exit so the next event will kill us.
2233 if (new_state != eStateExited)
2234 {
2235 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002236 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002237 SetNextEventAction(NULL);
2238 return;
2239 }
2240 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002241 break;
2242 }
2243 }
2244
Chris Lattner24943d22010-06-08 16:52:24 +00002245 // See if we should broadcast this state to external clients?
2246 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002247
2248 if (should_broadcast)
2249 {
2250 if (log)
2251 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002252 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2253 __FUNCTION__,
2254 GetID(),
2255 StateAsCString(new_state),
2256 StateAsCString (GetState ()),
2257 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002258 }
Greg Clayton68ca8232011-01-25 02:58:48 +00002259 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002260 PushProcessInputReader ();
2261 else
2262 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002263 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2264 BroadcastEvent (event_sp);
2265 }
2266 else
2267 {
2268 if (log)
2269 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002270 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2271 __FUNCTION__,
2272 GetID(),
2273 StateAsCString(new_state),
2274 StateAsCString (GetState ()),
2275 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002276 }
2277 }
2278}
2279
2280void *
2281Process::PrivateStateThread (void *arg)
2282{
2283 Process *proc = static_cast<Process*> (arg);
2284 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002285 return result;
2286}
2287
2288void *
2289Process::RunPrivateStateThread ()
2290{
2291 bool control_only = false;
2292 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2293
Greg Claytone005f2c2010-11-06 01:53:30 +00002294 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002295 if (log)
2296 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2297
2298 bool exit_now = false;
2299 while (!exit_now)
2300 {
2301 EventSP event_sp;
2302 WaitForEventsPrivate (NULL, event_sp, control_only);
2303 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2304 {
2305 switch (event_sp->GetType())
2306 {
2307 case eBroadcastInternalStateControlStop:
2308 exit_now = true;
2309 continue; // Go to next loop iteration so we exit without
2310 break; // doing any internal state managment below
2311
2312 case eBroadcastInternalStateControlPause:
2313 control_only = true;
2314 break;
2315
2316 case eBroadcastInternalStateControlResume:
2317 control_only = false;
2318 break;
2319 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002320
Jim Ingham3ae449a2010-11-17 02:32:00 +00002321 if (log)
2322 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2323
Chris Lattner24943d22010-06-08 16:52:24 +00002324 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002325 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002326 }
2327
2328
2329 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2330
2331 if (internal_state != eStateInvalid)
2332 {
2333 HandlePrivateEvent (event_sp);
2334 }
2335
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002336 if (internal_state == eStateInvalid ||
2337 internal_state == eStateExited ||
2338 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002339 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002340 if (log)
2341 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2342
Chris Lattner24943d22010-06-08 16:52:24 +00002343 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002344 }
Chris Lattner24943d22010-06-08 16:52:24 +00002345 }
2346
Caroline Tice926060e2010-10-29 21:48:37 +00002347 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002348 if (log)
2349 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2350
Greg Claytona4881d02011-01-22 07:12:45 +00002351 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2352 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002353 return NULL;
2354}
2355
Chris Lattner24943d22010-06-08 16:52:24 +00002356//------------------------------------------------------------------
2357// Process Event Data
2358//------------------------------------------------------------------
2359
2360Process::ProcessEventData::ProcessEventData () :
2361 EventData (),
2362 m_process_sp (),
2363 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002364 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002365 m_update_state (false),
2366 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002367{
2368}
2369
2370Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2371 EventData (),
2372 m_process_sp (process_sp),
2373 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002374 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002375 m_update_state (false),
2376 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002377{
2378}
2379
2380Process::ProcessEventData::~ProcessEventData()
2381{
2382}
2383
2384const ConstString &
2385Process::ProcessEventData::GetFlavorString ()
2386{
2387 static ConstString g_flavor ("Process::ProcessEventData");
2388 return g_flavor;
2389}
2390
2391const ConstString &
2392Process::ProcessEventData::GetFlavor () const
2393{
2394 return ProcessEventData::GetFlavorString ();
2395}
2396
Chris Lattner24943d22010-06-08 16:52:24 +00002397void
2398Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2399{
2400 // This function gets called twice for each event, once when the event gets pulled
2401 // off of the private process event queue, and once when it gets pulled off of
2402 // the public event queue. m_update_state is used to distinguish these
2403 // two cases; it is false when we're just pulling it off for private handling,
2404 // and we don't want to do the breakpoint command handling then.
2405
2406 if (!m_update_state)
2407 return;
2408
2409 m_process_sp->SetPublicState (m_state);
2410
2411 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2412 if (m_state == eStateStopped && ! m_restarted)
2413 {
2414 int num_threads = m_process_sp->GetThreadList().GetSize();
2415 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002416
Chris Lattner24943d22010-06-08 16:52:24 +00002417 for (idx = 0; idx < num_threads; ++idx)
2418 {
2419 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2420
Jim Ingham6297a3a2010-10-20 00:39:53 +00002421 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2422 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002423 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002424 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002425 }
2426 }
Greg Clayton643ee732010-08-04 01:40:35 +00002427
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002428 // The stop action might restart the target. If it does, then we want to mark that in the
2429 // event so that whoever is receiving it will know to wait for the running event and reflect
2430 // that state appropriately.
2431
Chris Lattner24943d22010-06-08 16:52:24 +00002432 if (m_process_sp->GetPrivateState() == eStateRunning)
2433 SetRestarted(true);
2434 }
2435}
2436
2437void
2438Process::ProcessEventData::Dump (Stream *s) const
2439{
2440 if (m_process_sp)
2441 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2442
2443 s->Printf("state = %s", StateAsCString(GetState()));;
2444}
2445
2446const Process::ProcessEventData *
2447Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2448{
2449 if (event_ptr)
2450 {
2451 const EventData *event_data = event_ptr->GetData();
2452 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2453 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2454 }
2455 return NULL;
2456}
2457
2458ProcessSP
2459Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2460{
2461 ProcessSP process_sp;
2462 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2463 if (data)
2464 process_sp = data->GetProcessSP();
2465 return process_sp;
2466}
2467
2468StateType
2469Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2470{
2471 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2472 if (data == NULL)
2473 return eStateInvalid;
2474 else
2475 return data->GetState();
2476}
2477
2478bool
2479Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2480{
2481 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2482 if (data == NULL)
2483 return false;
2484 else
2485 return data->GetRestarted();
2486}
2487
2488void
2489Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2490{
2491 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2492 if (data != NULL)
2493 data->SetRestarted(new_value);
2494}
2495
2496bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002497Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2498{
2499 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2500 if (data == NULL)
2501 return false;
2502 else
2503 return data->GetInterrupted ();
2504}
2505
2506void
2507Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2508{
2509 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2510 if (data != NULL)
2511 data->SetInterrupted(new_value);
2512}
2513
2514bool
Chris Lattner24943d22010-06-08 16:52:24 +00002515Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2516{
2517 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2518 if (data)
2519 {
2520 data->SetUpdateStateOnRemoval();
2521 return true;
2522 }
2523 return false;
2524}
2525
Chris Lattner24943d22010-06-08 16:52:24 +00002526void
Greg Claytona830adb2010-10-04 01:05:56 +00002527Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002528{
2529 exe_ctx.target = &m_target;
2530 exe_ctx.process = this;
2531 exe_ctx.thread = NULL;
2532 exe_ctx.frame = NULL;
2533}
2534
2535lldb::ProcessSP
2536Process::GetSP ()
2537{
2538 return GetTarget().GetProcessSP();
2539}
2540
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002541//uint32_t
2542//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2543//{
2544// return 0;
2545//}
2546//
2547//ArchSpec
2548//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2549//{
2550// return Host::GetArchSpecForExistingProcess (pid);
2551//}
2552//
2553//ArchSpec
2554//Process::GetArchSpecForExistingProcess (const char *process_name)
2555//{
2556// return Host::GetArchSpecForExistingProcess (process_name);
2557//}
2558//
Caroline Tice861efb32010-11-16 05:07:41 +00002559void
2560Process::AppendSTDOUT (const char * s, size_t len)
2561{
Greg Clayton20d338f2010-11-18 05:57:03 +00002562 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002563 m_stdout_data.append (s, len);
2564
Greg Claytonb3781332010-12-05 19:16:56 +00002565 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002566}
2567
2568void
2569Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2570{
2571 Process *process = (Process *) baton;
2572 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2573}
2574
2575size_t
2576Process::ProcessInputReaderCallback (void *baton,
2577 InputReader &reader,
2578 lldb::InputReaderAction notification,
2579 const char *bytes,
2580 size_t bytes_len)
2581{
2582 Process *process = (Process *) baton;
2583
2584 switch (notification)
2585 {
2586 case eInputReaderActivate:
2587 break;
2588
2589 case eInputReaderDeactivate:
2590 break;
2591
2592 case eInputReaderReactivate:
2593 break;
2594
2595 case eInputReaderGotToken:
2596 {
2597 Error error;
2598 process->PutSTDIN (bytes, bytes_len, error);
2599 }
2600 break;
2601
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002602 case eInputReaderInterrupt:
2603 process->Halt ();
2604 break;
2605
2606 case eInputReaderEndOfFile:
2607 process->AppendSTDOUT ("^D", 2);
2608 break;
2609
Caroline Tice861efb32010-11-16 05:07:41 +00002610 case eInputReaderDone:
2611 break;
2612
2613 }
2614
2615 return bytes_len;
2616}
2617
2618void
2619Process::ResetProcessInputReader ()
2620{
2621 m_process_input_reader.reset();
2622}
2623
2624void
2625Process::SetUpProcessInputReader (int file_descriptor)
2626{
2627 // First set up the Read Thread for reading/handling process I/O
2628
2629 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2630
2631 if (conn_ap.get())
2632 {
2633 m_stdio_communication.SetConnection (conn_ap.release());
2634 if (m_stdio_communication.IsConnected())
2635 {
2636 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2637 m_stdio_communication.StartReadThread();
2638
2639 // Now read thread is set up, set up input reader.
2640
2641 if (!m_process_input_reader.get())
2642 {
2643 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2644 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2645 this,
2646 eInputReaderGranularityByte,
2647 NULL,
2648 NULL,
2649 false));
2650
2651 if (err.Fail())
2652 m_process_input_reader.reset();
2653 }
2654 }
2655 }
2656}
2657
2658void
2659Process::PushProcessInputReader ()
2660{
2661 if (m_process_input_reader && !m_process_input_reader->IsActive())
2662 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2663}
2664
2665void
2666Process::PopProcessInputReader ()
2667{
2668 if (m_process_input_reader && m_process_input_reader->IsActive())
2669 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2670}
2671
Greg Claytond284b662011-02-18 01:44:25 +00002672// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00002673void
Caroline Tice2a456812011-03-10 22:14:10 +00002674Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002675{
Greg Claytond284b662011-02-18 01:44:25 +00002676 static std::vector<lldb::OptionEnumValueElement> g_plugins;
2677
2678 int i=0;
2679 const char *name;
2680 OptionEnumValueElement option_enum;
2681 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
2682 {
2683 if (name)
2684 {
2685 option_enum.value = i;
2686 option_enum.string_value = name;
2687 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
2688 g_plugins.push_back (option_enum);
2689 }
2690 ++i;
2691 }
2692 option_enum.value = 0;
2693 option_enum.string_value = NULL;
2694 option_enum.usage = NULL;
2695 g_plugins.push_back (option_enum);
2696
2697 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
2698 {
2699 if (::strcmp (name, "plugin") == 0)
2700 {
2701 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
2702 break;
2703 }
2704 }
Greg Clayton990de7b2010-11-18 23:32:35 +00002705 UserSettingsControllerSP &usc = GetSettingsController();
2706 usc.reset (new SettingsController);
2707 UserSettingsController::InitializeSettingsController (usc,
2708 SettingsController::global_settings_table,
2709 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00002710
2711 // Now call SettingsInitialize() for each 'child' of Process settings
2712 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00002713}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002714
Greg Clayton990de7b2010-11-18 23:32:35 +00002715void
Caroline Tice2a456812011-03-10 22:14:10 +00002716Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00002717{
Caroline Tice2a456812011-03-10 22:14:10 +00002718 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
2719
2720 Thread::SettingsTerminate ();
2721
2722 // Now terminate Process Settings.
2723
Greg Clayton990de7b2010-11-18 23:32:35 +00002724 UserSettingsControllerSP &usc = GetSettingsController();
2725 UserSettingsController::FinalizeSettingsController (usc);
2726 usc.reset();
2727}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002728
Greg Clayton990de7b2010-11-18 23:32:35 +00002729UserSettingsControllerSP &
2730Process::GetSettingsController ()
2731{
2732 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002733 return g_settings_controller;
2734}
2735
Caroline Tice1ebef442010-09-27 00:30:10 +00002736void
2737Process::UpdateInstanceName ()
2738{
2739 ModuleSP module_sp = GetTarget().GetExecutableModule();
2740 if (module_sp)
2741 {
2742 StreamString sstr;
2743 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2744
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002745 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002746 sstr.GetData());
2747 }
2748}
2749
Greg Clayton427f2902010-12-14 02:59:59 +00002750ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002751Process::RunThreadPlan (ExecutionContext &exe_ctx,
2752 lldb::ThreadPlanSP &thread_plan_sp,
2753 bool stop_others,
2754 bool try_all_threads,
2755 bool discard_on_error,
2756 uint32_t single_thread_timeout_usec,
2757 Stream &errors)
2758{
2759 ExecutionResults return_value = eExecutionSetupError;
2760
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002761 if (thread_plan_sp.get() == NULL)
2762 {
2763 errors.Printf("RunThreadPlan called with empty thread plan.");
2764 return lldb::eExecutionSetupError;
2765 }
2766
Jim Inghamac959662011-01-24 06:34:17 +00002767 if (m_private_state.GetValue() != eStateStopped)
2768 {
2769 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00002770 return lldb::eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00002771 }
2772
Jim Ingham360f53f2010-11-30 02:22:11 +00002773 // Save this value for restoration of the execution context after we run
2774 uint32_t tid = exe_ctx.thread->GetIndexID();
2775
2776 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2777 // so we should arrange to reset them as well.
2778
2779 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2780 lldb::StackFrameSP selected_frame_sp;
2781
2782 uint32_t selected_tid;
2783 if (selected_thread_sp != NULL)
2784 {
2785 selected_tid = selected_thread_sp->GetIndexID();
2786 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2787 }
2788 else
2789 {
2790 selected_tid = LLDB_INVALID_THREAD_ID;
2791 }
2792
2793 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2794
Jim Ingham6ae318c2011-01-23 21:14:08 +00002795 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00002796
2797 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2798 // restored on exit to the function.
2799
2800 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00002801
Jim Ingham6ae318c2011-01-23 21:14:08 +00002802 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002803 if (log)
2804 {
2805 StreamString s;
2806 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002807 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2808 exe_ctx.thread->GetIndexID(),
2809 exe_ctx.thread->GetID(),
2810 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002811 }
2812
Jim Inghamf9f40c22011-02-08 05:20:59 +00002813 bool got_event;
2814 lldb::EventSP event_sp;
2815 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00002816
2817 TimeValue* timeout_ptr = NULL;
2818 TimeValue real_timeout;
2819
Jim Inghamf9f40c22011-02-08 05:20:59 +00002820 bool first_timeout = true;
2821 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00002822
Jim Ingham360f53f2010-11-30 02:22:11 +00002823 while (1)
2824 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002825 // We usually want to resume the process if we get to the top of the loop.
2826 // The only exception is if we get two running events with no intervening
2827 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00002828
Jim Inghamf9f40c22011-02-08 05:20:59 +00002829 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00002830 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002831 // Do the initial resume and wait for the running event before going further.
2832
2833 Error resume_error = exe_ctx.process->Resume ();
2834 if (!resume_error.Success())
2835 {
2836 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2837 return_value = lldb::eExecutionSetupError;
2838 break;
2839 }
2840
2841 real_timeout = TimeValue::Now();
2842 real_timeout.OffsetWithMicroSeconds(500000);
2843 timeout_ptr = &real_timeout;
2844
2845 got_event = listener.WaitForEvent(NULL, event_sp);
2846 if (!got_event)
2847 {
2848 if (log)
2849 log->Printf("Didn't get any event after initial resume, exiting.");
2850
2851 errors.Printf("Didn't get any event after initial resume, exiting.");
2852 return_value = lldb::eExecutionSetupError;
2853 break;
2854 }
2855
2856 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2857 if (stop_state != eStateRunning)
2858 {
2859 if (log)
2860 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2861
2862 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2863 return_value = lldb::eExecutionSetupError;
2864 break;
2865 }
2866
2867 if (log)
2868 log->Printf ("Resuming succeeded.");
2869 // We need to call the function synchronously, so spin waiting for it to return.
2870 // If we get interrupted while executing, we're going to lose our context, and
2871 // won't be able to gather the result at this point.
2872 // We set the timeout AFTER the resume, since the resume takes some time and we
2873 // don't want to charge that to the timeout.
2874
2875 if (single_thread_timeout_usec != 0)
2876 {
2877 real_timeout = TimeValue::Now();
2878 if (first_timeout)
2879 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2880 else
2881 real_timeout.OffsetWithSeconds(10);
2882
2883 timeout_ptr = &real_timeout;
2884 }
2885 }
2886 else
2887 {
2888 if (log)
2889 log->Printf ("Handled an extra running event.");
2890 do_resume = true;
2891 }
2892
2893 // Now wait for the process to stop again:
2894 stop_state = lldb::eStateInvalid;
2895 event_sp.reset();
2896 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2897
2898 if (got_event)
2899 {
2900 if (event_sp.get())
2901 {
2902 bool keep_going = false;
2903 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2904 if (log)
2905 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2906
2907 switch (stop_state)
2908 {
2909 case lldb::eStateStopped:
2910 // Yay, we're done.
2911 if (log)
2912 log->Printf ("Execution completed successfully.");
2913 return_value = lldb::eExecutionCompleted;
2914 break;
2915 case lldb::eStateCrashed:
2916 if (log)
2917 log->Printf ("Execution crashed.");
2918 return_value = lldb::eExecutionInterrupted;
2919 break;
2920 case lldb::eStateRunning:
2921 do_resume = false;
2922 keep_going = true;
2923 break;
2924 default:
2925 if (log)
2926 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
2927 return_value = lldb::eExecutionInterrupted;
2928 break;
2929 }
2930 if (keep_going)
2931 continue;
2932 else
2933 break;
2934 }
2935 else
2936 {
2937 if (log)
2938 log->Printf ("got_event was true, but the event pointer was null. How odd...");
2939 return_value = lldb::eExecutionInterrupted;
2940 break;
2941 }
2942 }
2943 else
2944 {
2945 // If we didn't get an event that means we've timed out...
2946 // We will interrupt the process here. Depending on what we were asked to do we will
2947 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00002948 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002949
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002950 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002951 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002952 {
2953 if (first_timeout)
2954 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2955 "trying with all threads enabled.",
2956 single_thread_timeout_usec);
2957 else
2958 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2959 "and timeout: %d timed out.",
2960 single_thread_timeout_usec);
2961 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002962 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00002963 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2964 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00002965 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002966 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002967
Jim Inghamc556b462011-01-22 01:30:53 +00002968 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00002969 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002970 {
Jim Ingham360f53f2010-11-30 02:22:11 +00002971 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00002972 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00002973
Jim Inghamf9f40c22011-02-08 05:20:59 +00002974 // If halt succeeds, it always produces a stopped event. Wait for that:
2975
2976 real_timeout = TimeValue::Now();
2977 real_timeout.OffsetWithMicroSeconds(500000);
2978
2979 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00002980
2981 if (got_event)
2982 {
2983 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2984 if (log)
2985 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002986 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00002987 if (stop_state == lldb::eStateStopped
2988 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00002989 log->Printf (" Event was the Halt interruption event.");
2990 }
2991
Jim Inghamf9f40c22011-02-08 05:20:59 +00002992 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00002993 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002994 // Between the time we initiated the Halt and the time we delivered it, the process could have
2995 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00002996
Jim Inghamf9f40c22011-02-08 05:20:59 +00002997 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2998 {
2999 if (log)
3000 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3001 "Exiting wait loop.");
3002 return_value = lldb::eExecutionCompleted;
3003 break;
3004 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003005
Jim Inghamf9f40c22011-02-08 05:20:59 +00003006 if (!try_all_threads)
3007 {
3008 if (log)
3009 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
3010 return_value = lldb::eExecutionInterrupted;
3011 break;
3012 }
3013
3014 if (first_timeout)
3015 {
3016 // Set all the other threads to run, and return to the top of the loop, which will continue;
3017 first_timeout = false;
3018 thread_plan_sp->SetStopOthers (false);
3019 if (log)
3020 log->Printf ("Process::RunThreadPlan(): About to resume.");
3021
3022 continue;
3023 }
3024 else
3025 {
3026 // Running all threads failed, so return Interrupted.
3027 if (log)
3028 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3029 return_value = lldb::eExecutionInterrupted;
3030 break;
3031 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003032 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003033 }
3034 else
3035 { if (log)
3036 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
3037 "I'm getting out of here passing Interrupted.");
3038 return_value = lldb::eExecutionInterrupted;
3039 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003040 }
3041 }
Jim Inghamc556b462011-01-22 01:30:53 +00003042 else
3043 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003044 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3045 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003046 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003047 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.",
3048 halt_error.AsCString());
3049 real_timeout = TimeValue::Now();
3050 real_timeout.OffsetWithMicroSeconds(500000);
3051 timeout_ptr = &real_timeout;
3052 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3053 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003054 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003055 // This is not going anywhere, bag out.
3056 if (log)
3057 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
3058 return_value = lldb::eExecutionInterrupted;
3059 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003060 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003061 else
3062 {
3063 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3064 if (log)
3065 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3066 if (stop_state == lldb::eStateStopped)
3067 {
3068 // Between the time we initiated the Halt and the time we delivered it, the process could have
3069 // already finished its job. Check that here:
3070
3071 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3072 {
3073 if (log)
3074 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3075 "Exiting wait loop.");
3076 return_value = lldb::eExecutionCompleted;
3077 break;
3078 }
3079
3080 if (first_timeout)
3081 {
3082 // Set all the other threads to run, and return to the top of the loop, which will continue;
3083 first_timeout = false;
3084 thread_plan_sp->SetStopOthers (false);
3085 if (log)
3086 log->Printf ("Process::RunThreadPlan(): About to resume.");
3087
3088 continue;
3089 }
3090 else
3091 {
3092 // Running all threads failed, so return Interrupted.
3093 if (log)
3094 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3095 return_value = lldb::eExecutionInterrupted;
3096 break;
3097 }
3098 }
3099 else
3100 {
3101 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3102 " a stopped event, instead got %s.", StateAsCString(stop_state));
3103 return_value = lldb::eExecutionInterrupted;
3104 break;
3105 }
3106 }
Jim Inghamc556b462011-01-22 01:30:53 +00003107 }
3108
Jim Ingham360f53f2010-11-30 02:22:11 +00003109 }
3110
Jim Inghamf9f40c22011-02-08 05:20:59 +00003111 } // END WAIT LOOP
3112
3113 // Now do some processing on the results of the run:
3114 if (return_value == eExecutionInterrupted)
3115 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003116 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003117 {
3118 StreamString s;
3119 if (event_sp)
3120 event_sp->Dump (&s);
3121 else
3122 {
3123 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3124 }
3125
3126 StreamString ts;
3127
3128 const char *event_explanation;
3129
3130 do
3131 {
3132 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3133
3134 if (!event_data)
3135 {
3136 event_explanation = "<no event data>";
3137 break;
3138 }
3139
3140 Process *process = event_data->GetProcessSP().get();
3141
3142 if (!process)
3143 {
3144 event_explanation = "<no process>";
3145 break;
3146 }
3147
3148 ThreadList &thread_list = process->GetThreadList();
3149
3150 uint32_t num_threads = thread_list.GetSize();
3151 uint32_t thread_index;
3152
3153 ts.Printf("<%u threads> ", num_threads);
3154
3155 for (thread_index = 0;
3156 thread_index < num_threads;
3157 ++thread_index)
3158 {
3159 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3160
3161 if (!thread)
3162 {
3163 ts.Printf("<?> ");
3164 continue;
3165 }
3166
3167 ts.Printf("<0x%4.4x ", thread->GetID());
3168 RegisterContext *register_context = thread->GetRegisterContext().get();
3169
3170 if (register_context)
3171 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3172 else
3173 ts.Printf("[ip unknown] ");
3174
3175 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3176 if (stop_info_sp)
3177 {
3178 const char *stop_desc = stop_info_sp->GetDescription();
3179 if (stop_desc)
3180 ts.PutCString (stop_desc);
3181 }
3182 ts.Printf(">");
3183 }
3184
3185 event_explanation = ts.GetData();
3186 } while (0);
3187
3188 if (log)
3189 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3190
3191 if (discard_on_error && thread_plan_sp)
3192 {
3193 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3194 }
3195 }
3196 }
3197 else if (return_value == eExecutionSetupError)
3198 {
3199 if (log)
3200 log->Printf("Process::RunThreadPlan(): execution set up error.");
3201
3202 if (discard_on_error && thread_plan_sp)
3203 {
3204 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3205 }
3206 }
3207 else
3208 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003209 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3210 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003211 if (log)
3212 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton427f2902010-12-14 02:59:59 +00003213 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003214 }
3215 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3216 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003217 if (log)
3218 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton427f2902010-12-14 02:59:59 +00003219 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003220 }
3221 else
3222 {
3223 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003224 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003225 if (discard_on_error && thread_plan_sp)
3226 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003227 if (log)
3228 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003229 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3230 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003231 }
3232 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003233
Jim Ingham360f53f2010-11-30 02:22:11 +00003234 // Thread we ran the function in may have gone away because we ran the target
3235 // Check that it's still there.
3236 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3237 if (exe_ctx.thread)
3238 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3239
3240 // Also restore the current process'es selected frame & thread, since this function calling may
3241 // be done behind the user's back.
3242
3243 if (selected_tid != LLDB_INVALID_THREAD_ID)
3244 {
3245 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3246 {
3247 // We were able to restore the selected thread, now restore the frame:
3248 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3249 }
3250 }
3251
3252 return return_value;
3253}
3254
3255const char *
3256Process::ExecutionResultAsCString (ExecutionResults result)
3257{
3258 const char *result_name;
3259
3260 switch (result)
3261 {
Greg Clayton427f2902010-12-14 02:59:59 +00003262 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003263 result_name = "eExecutionCompleted";
3264 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003265 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003266 result_name = "eExecutionDiscarded";
3267 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003268 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003269 result_name = "eExecutionInterrupted";
3270 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003271 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003272 result_name = "eExecutionSetupError";
3273 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003274 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003275 result_name = "eExecutionTimedOut";
3276 break;
3277 }
3278 return result_name;
3279}
3280
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003281//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003282// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003283//--------------------------------------------------------------
3284
Greg Claytond0a5a232010-09-19 02:33:57 +00003285Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003286 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003287{
Greg Clayton638351a2010-12-04 00:10:17 +00003288 m_default_settings.reset (new ProcessInstanceSettings (*this,
3289 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00003290 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003291}
3292
Greg Claytond0a5a232010-09-19 02:33:57 +00003293Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003294{
3295}
3296
3297lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00003298Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003299{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003300 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3301 false,
3302 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003303 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3304 return new_settings_sp;
3305}
3306
3307//--------------------------------------------------------------
3308// class ProcessInstanceSettings
3309//--------------------------------------------------------------
3310
Greg Clayton638351a2010-12-04 00:10:17 +00003311ProcessInstanceSettings::ProcessInstanceSettings
3312(
3313 UserSettingsController &owner,
3314 bool live_instance,
3315 const char *name
3316) :
3317 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003318 m_run_args (),
3319 m_env_vars (),
3320 m_input_path (),
3321 m_output_path (),
3322 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00003323 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00003324 m_disable_stdio (false),
3325 m_inherit_host_env (true),
3326 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003327{
Caroline Tice396704b2010-09-09 18:26:37 +00003328 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3329 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3330 // 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 +00003331 // This is true for CreateInstanceName() too.
3332
3333 if (GetInstanceName () == InstanceSettings::InvalidName())
3334 {
3335 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3336 m_owner.RegisterInstanceSettings (this);
3337 }
Caroline Tice396704b2010-09-09 18:26:37 +00003338
3339 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003340 {
3341 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3342 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003343 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003344 }
3345}
3346
3347ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003348 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003349 m_run_args (rhs.m_run_args),
3350 m_env_vars (rhs.m_env_vars),
3351 m_input_path (rhs.m_input_path),
3352 m_output_path (rhs.m_output_path),
3353 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00003354 m_disable_aslr (rhs.m_disable_aslr),
3355 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003356{
3357 if (m_instance_name != InstanceSettings::GetDefaultName())
3358 {
3359 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3360 CopyInstanceSettings (pending_settings,false);
3361 m_owner.RemovePendingSettings (m_instance_name);
3362 }
3363}
3364
3365ProcessInstanceSettings::~ProcessInstanceSettings ()
3366{
3367}
3368
3369ProcessInstanceSettings&
3370ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3371{
3372 if (this != &rhs)
3373 {
3374 m_run_args = rhs.m_run_args;
3375 m_env_vars = rhs.m_env_vars;
3376 m_input_path = rhs.m_input_path;
3377 m_output_path = rhs.m_output_path;
3378 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003379 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003380 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003381 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003382 }
3383
3384 return *this;
3385}
3386
3387
3388void
3389ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3390 const char *index_value,
3391 const char *value,
3392 const ConstString &instance_name,
3393 const SettingEntry &entry,
3394 lldb::VarSetOperationType op,
3395 Error &err,
3396 bool pending)
3397{
3398 if (var_name == RunArgsVarName())
3399 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3400 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003401 {
3402 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003403 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003404 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003405 else if (var_name == InputPathVarName())
3406 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3407 else if (var_name == OutputPathVarName())
3408 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3409 else if (var_name == ErrorPathVarName())
3410 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003411 else if (var_name == DisableASLRVarName())
3412 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003413 else if (var_name == DisableSTDIOVarName ())
3414 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003415}
3416
3417void
3418ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3419 bool pending)
3420{
3421 if (new_settings.get() == NULL)
3422 return;
3423
3424 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3425
3426 m_run_args = new_process_settings->m_run_args;
3427 m_env_vars = new_process_settings->m_env_vars;
3428 m_input_path = new_process_settings->m_input_path;
3429 m_output_path = new_process_settings->m_output_path;
3430 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003431 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003432 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003433}
3434
Caroline Ticebcb5b452010-09-20 21:37:42 +00003435bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003436ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3437 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003438 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003439 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003440{
3441 if (var_name == RunArgsVarName())
3442 {
3443 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003444 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003445 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3446 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003447 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003448 }
3449 else if (var_name == EnvVarsVarName())
3450 {
Greg Clayton638351a2010-12-04 00:10:17 +00003451 GetHostEnvironmentIfNeeded ();
3452
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003453 if (m_env_vars.size() > 0)
3454 {
3455 std::map<std::string, std::string>::iterator pos;
3456 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3457 {
3458 StreamString value_str;
3459 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3460 value.AppendString (value_str.GetData());
3461 }
3462 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003463 }
3464 else if (var_name == InputPathVarName())
3465 {
3466 value.AppendString (m_input_path.c_str());
3467 }
3468 else if (var_name == OutputPathVarName())
3469 {
3470 value.AppendString (m_output_path.c_str());
3471 }
3472 else if (var_name == ErrorPathVarName())
3473 {
3474 value.AppendString (m_error_path.c_str());
3475 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003476 else if (var_name == InheritHostEnvVarName())
3477 {
3478 if (m_inherit_host_env)
3479 value.AppendString ("true");
3480 else
3481 value.AppendString ("false");
3482 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003483 else if (var_name == DisableASLRVarName())
3484 {
3485 if (m_disable_aslr)
3486 value.AppendString ("true");
3487 else
3488 value.AppendString ("false");
3489 }
Caroline Ticebd666012010-12-03 18:46:09 +00003490 else if (var_name == DisableSTDIOVarName())
3491 {
3492 if (m_disable_stdio)
3493 value.AppendString ("true");
3494 else
3495 value.AppendString ("false");
3496 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003497 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003498 {
3499 if (err)
3500 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3501 return false;
3502 }
3503 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003504}
3505
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003506const ConstString
3507ProcessInstanceSettings::CreateInstanceName ()
3508{
3509 static int instance_count = 1;
3510 StreamString sstr;
3511
3512 sstr.Printf ("process_%d", instance_count);
3513 ++instance_count;
3514
3515 const ConstString ret_val (sstr.GetData());
3516 return ret_val;
3517}
3518
3519const ConstString &
3520ProcessInstanceSettings::RunArgsVarName ()
3521{
3522 static ConstString run_args_var_name ("run-args");
3523
3524 return run_args_var_name;
3525}
3526
3527const ConstString &
3528ProcessInstanceSettings::EnvVarsVarName ()
3529{
3530 static ConstString env_vars_var_name ("env-vars");
3531
3532 return env_vars_var_name;
3533}
3534
3535const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003536ProcessInstanceSettings::InheritHostEnvVarName ()
3537{
3538 static ConstString g_name ("inherit-env");
3539
3540 return g_name;
3541}
3542
3543const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003544ProcessInstanceSettings::InputPathVarName ()
3545{
3546 static ConstString input_path_var_name ("input-path");
3547
3548 return input_path_var_name;
3549}
3550
3551const ConstString &
3552ProcessInstanceSettings::OutputPathVarName ()
3553{
Caroline Tice87097232010-09-07 18:35:40 +00003554 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003555
3556 return output_path_var_name;
3557}
3558
3559const ConstString &
3560ProcessInstanceSettings::ErrorPathVarName ()
3561{
Caroline Tice87097232010-09-07 18:35:40 +00003562 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003563
3564 return error_path_var_name;
3565}
3566
3567const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003568ProcessInstanceSettings::DisableASLRVarName ()
3569{
3570 static ConstString disable_aslr_var_name ("disable-aslr");
3571
3572 return disable_aslr_var_name;
3573}
3574
Caroline Ticebd666012010-12-03 18:46:09 +00003575const ConstString &
3576ProcessInstanceSettings::DisableSTDIOVarName ()
3577{
3578 static ConstString disable_stdio_var_name ("disable-stdio");
3579
3580 return disable_stdio_var_name;
3581}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003582
3583//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003584// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003585//--------------------------------------------------
3586
3587SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003588Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003589{
3590 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3591 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3592};
3593
3594
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003595SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003596Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003597{
Greg Clayton638351a2010-12-04 00:10:17 +00003598 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3599 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3600 { "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." },
3601 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003602 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3603 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3604 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytond284b662011-02-18 01:44:25 +00003605 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003606 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3607 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3608 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003609};
3610
3611
Jim Ingham7508e732010-08-09 23:31:02 +00003612