blob: 54c60f55b54a87a9dfea6609ecbfd0363b01be53 [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
Greg Claytonb1888f22011-03-19 01:12:21 +00001040
1041size_t
1042Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1043{
1044 PlatformSP platform_sp (m_target.GetPlatform());
1045 if (platform_sp)
1046 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1047 return 0;
1048}
1049
Chris Lattner24943d22010-06-08 16:52:24 +00001050Error
1051Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1052{
1053 Error error;
1054 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001055 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001056 const addr_t bp_addr = bp_site->GetLoadAddress();
1057 if (log)
1058 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1059 if (bp_site->IsEnabled())
1060 {
1061 if (log)
1062 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1063 return error;
1064 }
1065
1066 if (bp_addr == LLDB_INVALID_ADDRESS)
1067 {
1068 error.SetErrorString("BreakpointSite contains an invalid load address.");
1069 return error;
1070 }
1071 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1072 // trap for the breakpoint site
1073 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1074
1075 if (bp_opcode_size == 0)
1076 {
1077 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1078 }
1079 else
1080 {
1081 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1082
1083 if (bp_opcode_bytes == NULL)
1084 {
1085 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1086 return error;
1087 }
1088
1089 // Save the original opcode by reading it
1090 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1091 {
1092 // Write a software breakpoint in place of the original opcode
1093 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1094 {
1095 uint8_t verify_bp_opcode_bytes[64];
1096 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1097 {
1098 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1099 {
1100 bp_site->SetEnabled(true);
1101 bp_site->SetType (BreakpointSite::eSoftware);
1102 if (log)
1103 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1104 bp_site->GetID(),
1105 (uint64_t)bp_addr);
1106 }
1107 else
1108 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1109 }
1110 else
1111 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1112 }
1113 else
1114 error.SetErrorString("Unable to write breakpoint trap to memory.");
1115 }
1116 else
1117 error.SetErrorString("Unable to read memory at breakpoint address.");
1118 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001119 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001120 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1121 bp_site->GetID(),
1122 (uint64_t)bp_addr,
1123 error.AsCString());
1124 return error;
1125}
1126
1127Error
1128Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1129{
1130 Error error;
1131 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001132 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001133 addr_t bp_addr = bp_site->GetLoadAddress();
1134 lldb::user_id_t breakID = bp_site->GetID();
1135 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001136 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001137
1138 if (bp_site->IsHardware())
1139 {
1140 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1141 }
1142 else if (bp_site->IsEnabled())
1143 {
1144 const size_t break_op_size = bp_site->GetByteSize();
1145 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1146 if (break_op_size > 0)
1147 {
1148 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001149 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001150 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001151 bool break_op_found = false;
1152
1153 // Read the breakpoint opcode
1154 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1155 {
1156 bool verify = false;
1157 // Make sure we have the a breakpoint opcode exists at this address
1158 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1159 {
1160 break_op_found = true;
1161 // We found a valid breakpoint opcode at this address, now restore
1162 // the saved opcode.
1163 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1164 {
1165 verify = true;
1166 }
1167 else
1168 error.SetErrorString("Memory write failed when restoring original opcode.");
1169 }
1170 else
1171 {
1172 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1173 // Set verify to true and so we can check if the original opcode has already been restored
1174 verify = true;
1175 }
1176
1177 if (verify)
1178 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001179 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001180 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001181 // Verify that our original opcode made it back to the inferior
1182 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1183 {
1184 // compare the memory we just read with the original opcode
1185 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1186 {
1187 // SUCCESS
1188 bp_site->SetEnabled(false);
1189 if (log)
1190 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1191 return error;
1192 }
1193 else
1194 {
1195 if (break_op_found)
1196 error.SetErrorString("Failed to restore original opcode.");
1197 }
1198 }
1199 else
1200 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1201 }
1202 }
1203 else
1204 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1205 }
1206 }
1207 else
1208 {
1209 if (log)
1210 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1211 return error;
1212 }
1213
1214 if (log)
1215 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1216 bp_site->GetID(),
1217 (uint64_t)bp_addr,
1218 error.AsCString());
1219 return error;
1220
1221}
1222
Greg Claytonfd119992011-01-07 06:08:19 +00001223// Comment out line below to disable memory caching
1224#define ENABLE_MEMORY_CACHING
1225// Uncomment to verify memory caching works after making changes to caching code
1226//#define VERIFY_MEMORY_READS
1227
1228#if defined (ENABLE_MEMORY_CACHING)
1229
1230#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001231
1232size_t
1233Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1234{
Greg Claytonfd119992011-01-07 06:08:19 +00001235 // Memory caching is enabled, with debug verification
1236 if (buf && size)
1237 {
1238 // Uncomment the line below to make sure memory caching is working.
1239 // I ran this through the test suite and got no assertions, so I am
1240 // pretty confident this is working well. If any changes are made to
1241 // memory caching, uncomment the line below and test your changes!
1242
1243 // Verify all memory reads by using the cache first, then redundantly
1244 // reading the same memory from the inferior and comparing to make sure
1245 // everything is exactly the same.
1246 std::string verify_buf (size, '\0');
1247 assert (verify_buf.size() == size);
1248 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1249 Error verify_error;
1250 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1251 assert (cache_bytes_read == verify_bytes_read);
1252 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1253 assert (verify_error.Success() == error.Success());
1254 return cache_bytes_read;
1255 }
1256 return 0;
1257}
1258
1259#else // #if defined (VERIFY_MEMORY_READS)
1260
1261size_t
1262Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1263{
1264 // Memory caching enabled, no verification
1265 return m_memory_cache.Read (this, addr, buf, size, error);
1266}
1267
1268#endif // #else for #if defined (VERIFY_MEMORY_READS)
1269
1270#else // #if defined (ENABLE_MEMORY_CACHING)
1271
1272size_t
1273Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1274{
1275 // Memory caching is disabled
1276 return ReadMemoryFromInferior (addr, buf, size, error);
1277}
1278
1279#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1280
1281
1282size_t
1283Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1284{
Chris Lattner24943d22010-06-08 16:52:24 +00001285 if (buf == NULL || size == 0)
1286 return 0;
1287
1288 size_t bytes_read = 0;
1289 uint8_t *bytes = (uint8_t *)buf;
1290
1291 while (bytes_read < size)
1292 {
1293 const size_t curr_size = size - bytes_read;
1294 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1295 bytes + bytes_read,
1296 curr_size,
1297 error);
1298 bytes_read += curr_bytes_read;
1299 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1300 break;
1301 }
1302
1303 // Replace any software breakpoint opcodes that fall into this range back
1304 // into "buf" before we return
1305 if (bytes_read > 0)
1306 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1307 return bytes_read;
1308}
1309
Greg Claytonf72fdee2010-12-16 20:01:20 +00001310uint64_t
1311Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1312{
1313 if (integer_byte_size > sizeof(uint64_t))
1314 {
1315 error.SetErrorString ("unsupported integer size");
1316 }
1317 else
1318 {
1319 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton395fc332011-02-15 21:59:32 +00001320 DataExtractor data (tmp,
1321 integer_byte_size,
1322 m_target.GetArchitecture().GetByteOrder(),
1323 m_target.GetArchitecture().GetAddressByteSize());
Greg Claytonf72fdee2010-12-16 20:01:20 +00001324 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1325 {
1326 uint32_t offset = 0;
1327 return data.GetMaxU64 (&offset, integer_byte_size);
1328 }
1329 }
1330 // Any plug-in that doesn't return success a memory read with the number
1331 // of bytes that were requested should be setting the error
1332 assert (error.Fail());
1333 return 0;
1334}
1335
Chris Lattner24943d22010-06-08 16:52:24 +00001336size_t
1337Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1338{
1339 size_t bytes_written = 0;
1340 const uint8_t *bytes = (const uint8_t *)buf;
1341
1342 while (bytes_written < size)
1343 {
1344 const size_t curr_size = size - bytes_written;
1345 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1346 bytes + bytes_written,
1347 curr_size,
1348 error);
1349 bytes_written += curr_bytes_written;
1350 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1351 break;
1352 }
1353 return bytes_written;
1354}
1355
1356size_t
1357Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1358{
Greg Claytonfd119992011-01-07 06:08:19 +00001359#if defined (ENABLE_MEMORY_CACHING)
1360 m_memory_cache.Flush (addr, size);
1361#endif
1362
Chris Lattner24943d22010-06-08 16:52:24 +00001363 if (buf == NULL || size == 0)
1364 return 0;
1365 // We need to write any data that would go where any current software traps
1366 // (enabled software breakpoints) any software traps (breakpoints) that we
1367 // may have placed in our tasks memory.
1368
1369 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1370 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1371
1372 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1373 return DoWriteMemory(addr, buf, size, error);
1374
1375 BreakpointSiteList::collection::const_iterator pos;
1376 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001377 addr_t intersect_addr = 0;
1378 size_t intersect_size = 0;
1379 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001380 const uint8_t *ubuf = (const uint8_t *)buf;
1381
1382 for (pos = iter; pos != end; ++pos)
1383 {
1384 BreakpointSiteSP bp;
1385 bp = pos->second;
1386
1387 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1388 assert(addr <= intersect_addr && intersect_addr < addr + size);
1389 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1390 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1391
1392 // Check for bytes before this breakpoint
1393 const addr_t curr_addr = addr + bytes_written;
1394 if (intersect_addr > curr_addr)
1395 {
1396 // There are some bytes before this breakpoint that we need to
1397 // just write to memory
1398 size_t curr_size = intersect_addr - curr_addr;
1399 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1400 ubuf + bytes_written,
1401 curr_size,
1402 error);
1403 bytes_written += curr_bytes_written;
1404 if (curr_bytes_written != curr_size)
1405 {
1406 // We weren't able to write all of the requested bytes, we
1407 // are done looping and will return the number of bytes that
1408 // we have written so far.
1409 break;
1410 }
1411 }
1412
1413 // Now write any bytes that would cover up any software breakpoints
1414 // directly into the breakpoint opcode buffer
1415 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1416 bytes_written += intersect_size;
1417 }
1418
1419 // Write any remaining bytes after the last breakpoint if we have any left
1420 if (bytes_written < size)
1421 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1422 ubuf + bytes_written,
1423 size - bytes_written,
1424 error);
1425
1426 return bytes_written;
1427}
1428
1429addr_t
1430Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1431{
1432 // Fixme: we should track the blocks we've allocated, and clean them up...
1433 // We could even do our own allocator here if that ends up being more efficient.
Greg Clayton2860ba92011-01-23 19:58:49 +00001434 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1435 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1436 if (log)
Greg Claytonb349adc2011-01-24 06:30:45 +00001437 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001438 size,
1439 permissions & ePermissionsReadable ? 'r' : '-',
1440 permissions & ePermissionsWritable ? 'w' : '-',
1441 permissions & ePermissionsExecutable ? 'x' : '-',
1442 (uint64_t)allocated_addr,
1443 m_stop_id);
1444 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001445}
1446
1447Error
1448Process::DeallocateMemory (addr_t ptr)
1449{
Greg Clayton2860ba92011-01-23 19:58:49 +00001450 Error error(DoDeallocateMemory (ptr));
1451
1452 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1453 if (log)
1454 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1455 ptr,
1456 error.AsCString("SUCCESS"),
1457 m_stop_id);
1458 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001459}
1460
1461
1462Error
1463Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1464{
1465 Error error;
1466 error.SetErrorString("watchpoints are not supported");
1467 return error;
1468}
1469
1470Error
1471Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1472{
1473 Error error;
1474 error.SetErrorString("watchpoints are not supported");
1475 return error;
1476}
1477
1478StateType
1479Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1480{
1481 StateType state;
1482 // Now wait for the process to launch and return control to us, and then
1483 // call DidLaunch:
1484 while (1)
1485 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001486 event_sp.reset();
1487 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1488
1489 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001490 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001491
1492 // If state is invalid, then we timed out
1493 if (state == eStateInvalid)
1494 break;
1495
1496 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001497 HandlePrivateEvent (event_sp);
1498 }
1499 return state;
1500}
1501
1502Error
1503Process::Launch
1504(
1505 char const *argv[],
1506 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001507 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001508 const char *stdin_path,
1509 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001510 const char *stderr_path,
1511 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001512)
1513{
1514 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001515 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00001516 m_dyld_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001517 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001518
1519 Module *exe_module = m_target.GetExecutableModule().get();
1520 if (exe_module)
1521 {
1522 char exec_file_path[PATH_MAX];
1523 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1524 if (exe_module->GetFileSpec().Exists())
1525 {
Greg Claytona2f74232011-02-24 22:24:29 +00001526 if (PrivateStateThreadIsValid ())
1527 PausePrivateStateThread ();
1528
Chris Lattner24943d22010-06-08 16:52:24 +00001529 error = WillLaunch (exe_module);
1530 if (error.Success())
1531 {
Greg Claytond8c62532010-10-07 04:19:01 +00001532 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001533 // The args coming in should not contain the application name, the
1534 // lldb_private::Process class will add this in case the executable
1535 // gets resolved to a different file than was given on the command
1536 // line (like when an applicaiton bundle is specified and will
1537 // resolve to the contained exectuable file, or the file given was
1538 // a symlink or other file system link that resolves to a different
1539 // file).
1540
1541 // Get the resolved exectuable path
1542
1543 // Make a new argument vector
1544 std::vector<const char *> exec_path_plus_argv;
1545 // Append the resolved executable path
1546 exec_path_plus_argv.push_back (exec_file_path);
1547
1548 // Push all args if there are any
1549 if (argv)
1550 {
1551 for (int i = 0; argv[i]; ++i)
1552 exec_path_plus_argv.push_back(argv[i]);
1553 }
1554
1555 // Push a NULL to terminate the args.
1556 exec_path_plus_argv.push_back(NULL);
1557
1558 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001559 error = DoLaunch (exe_module,
1560 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1561 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001562 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001563 stdin_path,
1564 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001565 stderr_path,
1566 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001567
1568 if (error.Fail())
1569 {
1570 if (GetID() != LLDB_INVALID_PROCESS_ID)
1571 {
1572 SetID (LLDB_INVALID_PROCESS_ID);
1573 const char *error_string = error.AsCString();
1574 if (error_string == NULL)
1575 error_string = "launch failed";
1576 SetExitStatus (-1, error_string);
1577 }
1578 }
1579 else
1580 {
1581 EventSP event_sp;
1582 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1583
1584 if (state == eStateStopped || state == eStateCrashed)
1585 {
Greg Clayton75c703d2011-02-16 04:46:07 +00001586
Chris Lattner24943d22010-06-08 16:52:24 +00001587 DidLaunch ();
1588
Greg Clayton4fdf7602011-03-20 04:57:14 +00001589 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00001590 if (m_dyld_ap.get())
1591 m_dyld_ap->DidLaunch();
1592
Chris Lattner24943d22010-06-08 16:52:24 +00001593 // This delays passing the stopped event to listeners till DidLaunch gets
1594 // a chance to complete...
1595 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00001596
1597 if (PrivateStateThreadIsValid ())
1598 ResumePrivateStateThread ();
1599 else
1600 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001601 }
1602 else if (state == eStateExited)
1603 {
1604 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1605 // not likely to work, and return an invalid pid.
1606 HandlePrivateEvent (event_sp);
1607 }
1608 }
1609 }
1610 }
1611 else
1612 {
1613 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1614 }
1615 }
1616 return error;
1617}
1618
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001619Process::NextEventAction::EventActionResult
1620Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001621{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001622 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1623 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00001624 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001625 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00001626 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001627 return eEventActionRetry;
1628
1629 case eStateStopped:
1630 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00001631 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001632 // During attach, prior to sending the eStateStopped event,
1633 // lldb_private::Process subclasses must set the process must set
1634 // the new process ID.
1635 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00001636 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001637 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00001638 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001639
1640
1641 break;
1642 default:
1643 case eStateExited:
1644 case eStateInvalid:
1645 m_exit_string.assign ("No valid Process");
1646 return eEventActionExit;
1647 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001648 }
1649}
Chris Lattner24943d22010-06-08 16:52:24 +00001650
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001651Process::NextEventAction::EventActionResult
1652Process::AttachCompletionHandler::HandleBeingInterrupted()
1653{
1654 return eEventActionSuccess;
1655}
1656
1657const char *
1658Process::AttachCompletionHandler::GetExitString ()
1659{
1660 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00001661}
1662
1663Error
1664Process::Attach (lldb::pid_t attach_pid)
1665{
1666
Chris Lattner24943d22010-06-08 16:52:24 +00001667 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001668 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001669
Jim Ingham7508e732010-08-09 23:31:02 +00001670 // Find the process and its architecture. Make sure it matches the architecture
1671 // of the current Target, and if not adjust it.
1672
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001673 ProcessInfo process_info;
Greg Claytonb1888f22011-03-19 01:12:21 +00001674 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001675 if (platform_sp)
Jim Ingham7508e732010-08-09 23:31:02 +00001676 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001677 if (platform_sp->GetProcessInfo (attach_pid, process_info))
1678 {
1679 const ArchSpec &process_arch = process_info.GetArchitecture();
1680 if (process_arch.IsValid())
1681 GetTarget().SetArchitecture(process_arch);
1682 }
Jim Ingham7508e732010-08-09 23:31:02 +00001683 }
1684
Greg Clayton75c703d2011-02-16 04:46:07 +00001685 m_dyld_ap.reset();
1686
Greg Clayton54e7afa2010-07-09 20:39:50 +00001687 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001688 if (error.Success())
1689 {
Greg Claytond8c62532010-10-07 04:19:01 +00001690 SetPublicState (eStateAttaching);
1691
Greg Clayton54e7afa2010-07-09 20:39:50 +00001692 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001693 if (error.Success())
1694 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001695 SetNextEventAction(new Process::AttachCompletionHandler(this));
1696 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001697 }
1698 else
1699 {
1700 if (GetID() != LLDB_INVALID_PROCESS_ID)
1701 {
1702 SetID (LLDB_INVALID_PROCESS_ID);
1703 const char *error_string = error.AsCString();
1704 if (error_string == NULL)
1705 error_string = "attach failed";
1706
1707 SetExitStatus(-1, error_string);
1708 }
1709 }
1710 }
1711 return error;
1712}
1713
1714Error
1715Process::Attach (const char *process_name, bool wait_for_launch)
1716{
Chris Lattner24943d22010-06-08 16:52:24 +00001717 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001718 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001719
1720 // Find the process and its architecture. Make sure it matches the architecture
1721 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001722 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00001723
Jim Inghamea294182010-08-17 21:54:19 +00001724 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001725 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001726 ProcessInfoList process_infos;
Greg Claytonb1888f22011-03-19 01:12:21 +00001727 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001728 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00001729 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001730 platform_sp->FindProcessesByName (process_name, eNameMatchEquals, process_infos);
1731 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00001732 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001733 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
1734 }
1735 else if (process_infos.GetSize() == 0)
1736 {
1737 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
1738 }
1739 else
1740 {
1741 ProcessInfo process_info;
1742 if (process_infos.GetInfoAtIndex (0, process_info))
1743 {
1744 const ArchSpec &process_arch = process_info.GetArchitecture();
1745 if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
1746 {
1747 // Set the architecture on the target.
1748 GetTarget().SetArchitecture (process_arch);
1749 }
1750 }
Chris Lattner24943d22010-06-08 16:52:24 +00001751 }
1752 }
1753 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001754 {
1755 error.SetErrorString ("Invalid platform");
1756 }
1757 }
1758
1759 if (error.Success())
1760 {
1761 m_dyld_ap.reset();
1762
1763 error = WillAttachToProcessWithName(process_name, wait_for_launch);
1764 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00001765 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001766 SetPublicState (eStateAttaching);
1767 error = DoAttachToProcessWithName (process_name, wait_for_launch);
1768 if (error.Fail())
1769 {
1770 if (GetID() != LLDB_INVALID_PROCESS_ID)
1771 {
1772 SetID (LLDB_INVALID_PROCESS_ID);
1773 const char *error_string = error.AsCString();
1774 if (error_string == NULL)
1775 error_string = "attach failed";
1776
1777 SetExitStatus(-1, error_string);
1778 }
1779 }
1780 else
1781 {
1782 SetNextEventAction(new Process::AttachCompletionHandler(this));
1783 StartPrivateStateThread();
1784 }
Chris Lattner24943d22010-06-08 16:52:24 +00001785 }
1786 }
1787 return error;
1788}
1789
Greg Clayton75c703d2011-02-16 04:46:07 +00001790void
1791Process::CompleteAttach ()
1792{
1793 // Let the process subclass figure out at much as it can about the process
1794 // before we go looking for a dynamic loader plug-in.
1795 DidAttach();
1796
1797 // We have complete the attach, now it is time to find the dynamic loader
1798 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00001799 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00001800 if (m_dyld_ap.get())
1801 m_dyld_ap->DidAttach();
1802
1803 // Figure out which one is the executable, and set that in our target:
1804 ModuleList &modules = m_target.GetImages();
1805
1806 size_t num_modules = modules.GetSize();
1807 for (int i = 0; i < num_modules; i++)
1808 {
1809 ModuleSP module_sp (modules.GetModuleAtIndex(i));
1810 if (module_sp->IsExecutable())
1811 {
1812 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
1813 if (target_exe_module_sp != module_sp)
1814 m_target.SetExecutableModule (module_sp, false);
1815 break;
1816 }
1817 }
1818}
1819
Chris Lattner24943d22010-06-08 16:52:24 +00001820Error
Greg Claytone71e2582011-02-04 01:58:07 +00001821Process::ConnectRemote (const char *remote_url)
1822{
Greg Claytone71e2582011-02-04 01:58:07 +00001823 m_abi_sp.reset();
1824 m_process_input_reader.reset();
1825
1826 // Find the process and its architecture. Make sure it matches the architecture
1827 // of the current Target, and if not adjust it.
1828
1829 Error error (DoConnectRemote (remote_url));
1830 if (error.Success())
1831 {
Greg Claytona2f74232011-02-24 22:24:29 +00001832 StartPrivateStateThread();
1833 // If we attached and actually have a process on the other end, then
1834 // this ended up being the equivalent of an attach.
1835 if (GetID() != LLDB_INVALID_PROCESS_ID)
1836 {
1837 CompleteAttach ();
1838 }
Greg Claytone71e2582011-02-04 01:58:07 +00001839 }
1840 return error;
1841}
1842
1843
1844Error
Chris Lattner24943d22010-06-08 16:52:24 +00001845Process::Resume ()
1846{
Greg Claytone005f2c2010-11-06 01:53:30 +00001847 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001848 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00001849 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1850 m_stop_id,
1851 StateAsCString(m_public_state.GetValue()),
1852 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00001853
1854 Error error (WillResume());
1855 // Tell the process it is about to resume before the thread list
1856 if (error.Success())
1857 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001858 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001859 // can let all of our threads know that they are about to be
1860 // resumed. Threads will each be called with
1861 // Thread::WillResume(StateType) where StateType contains the state
1862 // that they are supposed to have when the process is resumed
1863 // (suspended/running/stepping). Threads should also check
1864 // their resume signal in lldb::Thread::GetResumeSignal()
1865 // to see if they are suppoed to start back up with a signal.
1866 if (m_thread_list.WillResume())
1867 {
1868 error = DoResume();
1869 if (error.Success())
1870 {
1871 DidResume();
1872 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00001873 if (log)
1874 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00001875 }
1876 }
1877 else
1878 {
Jim Inghamac959662011-01-24 06:34:17 +00001879 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00001880 }
1881 }
Jim Inghamac959662011-01-24 06:34:17 +00001882 else if (log)
1883 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00001884 return error;
1885}
1886
1887Error
1888Process::Halt ()
1889{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001890 // Pause our private state thread so we can ensure no one else eats
1891 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00001892 Listener halt_listener ("lldb.process.halt_listener");
1893 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00001894
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001895 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001896 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001897
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001898 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001899 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001900
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001901 bool caused_stop = false;
1902
1903 // Ask the process subclass to actually halt our process
1904 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001905 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001906 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001907 if (m_public_state.GetValue() == eStateAttaching)
1908 {
1909 SetExitStatus(SIGKILL, "Cancelled async attach.");
1910 Destroy ();
1911 }
1912 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00001913 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001914 // If "caused_stop" is true, then DoHalt stopped the process. If
1915 // "caused_stop" is false, the process was already stopped.
1916 // If the DoHalt caused the process to stop, then we want to catch
1917 // this event and set the interrupted bool to true before we pass
1918 // this along so clients know that the process was interrupted by
1919 // a halt command.
1920 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00001921 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00001922 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001923 TimeValue timeout_time;
1924 timeout_time = TimeValue::Now();
1925 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001926 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1927 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001928
Jim Inghamf9f40c22011-02-08 05:20:59 +00001929 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00001930 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001931 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00001932 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00001933 }
1934 else
1935 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001936 if (StateIsStoppedState (state))
1937 {
1938 // We caused the process to interrupt itself, so mark this
1939 // as such in the stop event so clients can tell an interrupted
1940 // process from a natural stop
1941 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1942 }
1943 else
1944 {
1945 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1946 if (log)
1947 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1948 error.SetErrorString ("Did not get stopped event after halt.");
1949 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001950 }
1951 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001952 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00001953 }
1954 }
Chris Lattner24943d22010-06-08 16:52:24 +00001955 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001956 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00001957 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001958
1959 // Post any event we might have consumed. If all goes well, we will have
1960 // stopped the process, intercepted the event and set the interrupted
1961 // bool in the event. Post it to the private event queue and that will end up
1962 // correctly setting the state.
1963 if (event_sp)
1964 m_private_state_broadcaster.BroadcastEvent(event_sp);
1965
Chris Lattner24943d22010-06-08 16:52:24 +00001966 return error;
1967}
1968
1969Error
1970Process::Detach ()
1971{
1972 Error error (WillDetach());
1973
1974 if (error.Success())
1975 {
1976 DisableAllBreakpointSites();
1977 error = DoDetach();
1978 if (error.Success())
1979 {
1980 DidDetach();
1981 StopPrivateStateThread();
1982 }
1983 }
1984 return error;
1985}
1986
1987Error
1988Process::Destroy ()
1989{
1990 Error error (WillDestroy());
1991 if (error.Success())
1992 {
1993 DisableAllBreakpointSites();
1994 error = DoDestroy();
1995 if (error.Success())
1996 {
1997 DidDestroy();
1998 StopPrivateStateThread();
1999 }
Caroline Tice861efb32010-11-16 05:07:41 +00002000 m_stdio_communication.StopReadThread();
2001 m_stdio_communication.Disconnect();
2002 if (m_process_input_reader && m_process_input_reader->IsActive())
2003 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2004 if (m_process_input_reader)
2005 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002006 }
2007 return error;
2008}
2009
2010Error
2011Process::Signal (int signal)
2012{
2013 Error error (WillSignal());
2014 if (error.Success())
2015 {
2016 error = DoSignal(signal);
2017 if (error.Success())
2018 DidSignal();
2019 }
2020 return error;
2021}
2022
Greg Clayton395fc332011-02-15 21:59:32 +00002023lldb::ByteOrder
2024Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002025{
Greg Clayton395fc332011-02-15 21:59:32 +00002026 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002027}
2028
2029uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002030Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002031{
Greg Clayton395fc332011-02-15 21:59:32 +00002032 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002033}
2034
Greg Clayton395fc332011-02-15 21:59:32 +00002035
Chris Lattner24943d22010-06-08 16:52:24 +00002036bool
2037Process::ShouldBroadcastEvent (Event *event_ptr)
2038{
2039 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2040 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002041 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002042
2043 switch (state)
2044 {
Greg Claytone71e2582011-02-04 01:58:07 +00002045 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002046 case eStateAttaching:
2047 case eStateLaunching:
2048 case eStateDetached:
2049 case eStateExited:
2050 case eStateUnloaded:
2051 // These events indicate changes in the state of the debugging session, always report them.
2052 return_value = true;
2053 break;
2054 case eStateInvalid:
2055 // We stopped for no apparent reason, don't report it.
2056 return_value = false;
2057 break;
2058 case eStateRunning:
2059 case eStateStepping:
2060 // If we've started the target running, we handle the cases where we
2061 // are already running and where there is a transition from stopped to
2062 // running differently.
2063 // running -> running: Automatically suppress extra running events
2064 // stopped -> running: Report except when there is one or more no votes
2065 // and no yes votes.
2066 SynchronouslyNotifyStateChanged (state);
2067 switch (m_public_state.GetValue())
2068 {
2069 case eStateRunning:
2070 case eStateStepping:
2071 // We always suppress multiple runnings with no PUBLIC stop in between.
2072 return_value = false;
2073 break;
2074 default:
2075 // TODO: make this work correctly. For now always report
2076 // run if we aren't running so we don't miss any runnning
2077 // events. If I run the lldb/test/thread/a.out file and
2078 // break at main.cpp:58, run and hit the breakpoints on
2079 // multiple threads, then somehow during the stepping over
2080 // of all breakpoints no run gets reported.
2081 return_value = true;
2082
2083 // This is a transition from stop to run.
2084 switch (m_thread_list.ShouldReportRun (event_ptr))
2085 {
2086 case eVoteYes:
2087 case eVoteNoOpinion:
2088 return_value = true;
2089 break;
2090 case eVoteNo:
2091 return_value = false;
2092 break;
2093 }
2094 break;
2095 }
2096 break;
2097 case eStateStopped:
2098 case eStateCrashed:
2099 case eStateSuspended:
2100 {
2101 // We've stopped. First see if we're going to restart the target.
2102 // If we are going to stop, then we always broadcast the event.
2103 // 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 +00002104 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002105 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002106 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002107 if (log)
2108 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002109 return true;
2110 }
2111 else
2112 {
Chris Lattner24943d22010-06-08 16:52:24 +00002113 RefreshStateAfterStop ();
2114
2115 if (m_thread_list.ShouldStop (event_ptr) == false)
2116 {
2117 switch (m_thread_list.ShouldReportStop (event_ptr))
2118 {
2119 case eVoteYes:
2120 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002121 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002122 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002123 case eVoteNo:
2124 return_value = false;
2125 break;
2126 }
2127
2128 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002129 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002130 Resume ();
2131 }
2132 else
2133 {
2134 return_value = true;
2135 SynchronouslyNotifyStateChanged (state);
2136 }
2137 }
2138 }
2139 }
2140
2141 if (log)
2142 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2143 return return_value;
2144}
2145
Chris Lattner24943d22010-06-08 16:52:24 +00002146
2147bool
2148Process::StartPrivateStateThread ()
2149{
Greg Claytone005f2c2010-11-06 01:53:30 +00002150 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002151
2152 if (log)
2153 log->Printf ("Process::%s ( )", __FUNCTION__);
2154
2155 // Create a thread that watches our internal state and controls which
2156 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002157 char thread_name[1024];
2158 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2159 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002160 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002161}
2162
2163void
2164Process::PausePrivateStateThread ()
2165{
2166 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2167}
2168
2169void
2170Process::ResumePrivateStateThread ()
2171{
2172 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2173}
2174
2175void
2176Process::StopPrivateStateThread ()
2177{
2178 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2179}
2180
2181void
2182Process::ControlPrivateStateThread (uint32_t signal)
2183{
Greg Claytone005f2c2010-11-06 01:53:30 +00002184 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002185
2186 assert (signal == eBroadcastInternalStateControlStop ||
2187 signal == eBroadcastInternalStateControlPause ||
2188 signal == eBroadcastInternalStateControlResume);
2189
2190 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002191 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002192
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002193 // Signal the private state thread. First we should copy this is case the
2194 // thread starts exiting since the private state thread will NULL this out
2195 // when it exits
2196 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002197 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002198 {
2199 TimeValue timeout_time;
2200 bool timed_out;
2201
2202 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2203
2204 timeout_time = TimeValue::Now();
2205 timeout_time.OffsetWithSeconds(2);
2206 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2207 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2208
2209 if (signal == eBroadcastInternalStateControlStop)
2210 {
2211 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002212 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002213
2214 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002215 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002216 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002217 }
2218 }
2219}
2220
2221void
2222Process::HandlePrivateEvent (EventSP &event_sp)
2223{
Greg Claytone005f2c2010-11-06 01:53:30 +00002224 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002225
Greg Clayton68ca8232011-01-25 02:58:48 +00002226 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002227
2228 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002229 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002230 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002231 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002232 switch (action_result)
2233 {
2234 case NextEventAction::eEventActionSuccess:
2235 SetNextEventAction(NULL);
2236 break;
2237 case NextEventAction::eEventActionRetry:
2238 break;
2239 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002240 // Handle Exiting Here. If we already got an exited event,
2241 // we should just propagate it. Otherwise, swallow this event,
2242 // and set our state to exit so the next event will kill us.
2243 if (new_state != eStateExited)
2244 {
2245 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002246 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002247 SetNextEventAction(NULL);
2248 return;
2249 }
2250 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002251 break;
2252 }
2253 }
2254
Chris Lattner24943d22010-06-08 16:52:24 +00002255 // See if we should broadcast this state to external clients?
2256 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002257
2258 if (should_broadcast)
2259 {
2260 if (log)
2261 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002262 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2263 __FUNCTION__,
2264 GetID(),
2265 StateAsCString(new_state),
2266 StateAsCString (GetState ()),
2267 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002268 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002269 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002270 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002271 PushProcessInputReader ();
2272 else
2273 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002274
Chris Lattner24943d22010-06-08 16:52:24 +00002275 BroadcastEvent (event_sp);
2276 }
2277 else
2278 {
2279 if (log)
2280 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002281 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2282 __FUNCTION__,
2283 GetID(),
2284 StateAsCString(new_state),
2285 StateAsCString (GetState ()),
2286 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002287 }
2288 }
2289}
2290
2291void *
2292Process::PrivateStateThread (void *arg)
2293{
2294 Process *proc = static_cast<Process*> (arg);
2295 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002296 return result;
2297}
2298
2299void *
2300Process::RunPrivateStateThread ()
2301{
2302 bool control_only = false;
2303 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2304
Greg Claytone005f2c2010-11-06 01:53:30 +00002305 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002306 if (log)
2307 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2308
2309 bool exit_now = false;
2310 while (!exit_now)
2311 {
2312 EventSP event_sp;
2313 WaitForEventsPrivate (NULL, event_sp, control_only);
2314 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2315 {
2316 switch (event_sp->GetType())
2317 {
2318 case eBroadcastInternalStateControlStop:
2319 exit_now = true;
2320 continue; // Go to next loop iteration so we exit without
2321 break; // doing any internal state managment below
2322
2323 case eBroadcastInternalStateControlPause:
2324 control_only = true;
2325 break;
2326
2327 case eBroadcastInternalStateControlResume:
2328 control_only = false;
2329 break;
2330 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002331
Jim Ingham3ae449a2010-11-17 02:32:00 +00002332 if (log)
2333 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2334
Chris Lattner24943d22010-06-08 16:52:24 +00002335 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002336 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002337 }
2338
2339
2340 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2341
2342 if (internal_state != eStateInvalid)
2343 {
2344 HandlePrivateEvent (event_sp);
2345 }
2346
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002347 if (internal_state == eStateInvalid ||
2348 internal_state == eStateExited ||
2349 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002350 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002351 if (log)
2352 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2353
Chris Lattner24943d22010-06-08 16:52:24 +00002354 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002355 }
Chris Lattner24943d22010-06-08 16:52:24 +00002356 }
2357
Caroline Tice926060e2010-10-29 21:48:37 +00002358 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002359 if (log)
2360 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2361
Greg Claytona4881d02011-01-22 07:12:45 +00002362 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2363 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002364 return NULL;
2365}
2366
Chris Lattner24943d22010-06-08 16:52:24 +00002367//------------------------------------------------------------------
2368// Process Event Data
2369//------------------------------------------------------------------
2370
2371Process::ProcessEventData::ProcessEventData () :
2372 EventData (),
2373 m_process_sp (),
2374 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002375 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002376 m_update_state (false),
2377 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002378{
2379}
2380
2381Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2382 EventData (),
2383 m_process_sp (process_sp),
2384 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002385 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002386 m_update_state (false),
2387 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002388{
2389}
2390
2391Process::ProcessEventData::~ProcessEventData()
2392{
2393}
2394
2395const ConstString &
2396Process::ProcessEventData::GetFlavorString ()
2397{
2398 static ConstString g_flavor ("Process::ProcessEventData");
2399 return g_flavor;
2400}
2401
2402const ConstString &
2403Process::ProcessEventData::GetFlavor () const
2404{
2405 return ProcessEventData::GetFlavorString ();
2406}
2407
Chris Lattner24943d22010-06-08 16:52:24 +00002408void
2409Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2410{
2411 // This function gets called twice for each event, once when the event gets pulled
2412 // off of the private process event queue, and once when it gets pulled off of
2413 // the public event queue. m_update_state is used to distinguish these
2414 // two cases; it is false when we're just pulling it off for private handling,
2415 // and we don't want to do the breakpoint command handling then.
2416
2417 if (!m_update_state)
2418 return;
2419
2420 m_process_sp->SetPublicState (m_state);
2421
2422 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2423 if (m_state == eStateStopped && ! m_restarted)
2424 {
2425 int num_threads = m_process_sp->GetThreadList().GetSize();
2426 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002427
Chris Lattner24943d22010-06-08 16:52:24 +00002428 for (idx = 0; idx < num_threads; ++idx)
2429 {
2430 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2431
Jim Ingham6297a3a2010-10-20 00:39:53 +00002432 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2433 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002434 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002435 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002436 }
2437 }
Greg Clayton643ee732010-08-04 01:40:35 +00002438
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002439 // The stop action might restart the target. If it does, then we want to mark that in the
2440 // event so that whoever is receiving it will know to wait for the running event and reflect
2441 // that state appropriately.
2442
Chris Lattner24943d22010-06-08 16:52:24 +00002443 if (m_process_sp->GetPrivateState() == eStateRunning)
2444 SetRestarted(true);
Jim Inghamd60d94a2011-03-11 03:53:59 +00002445 else
2446 {
2447 // Finally, if we didn't restart, run the Stop Hooks here:
2448 // They might also restart the target, so watch for that.
2449 m_process_sp->GetTarget().RunStopHooks();
2450 if (m_process_sp->GetPrivateState() == eStateRunning)
2451 SetRestarted(true);
2452 }
2453
Chris Lattner24943d22010-06-08 16:52:24 +00002454 }
2455}
2456
2457void
2458Process::ProcessEventData::Dump (Stream *s) const
2459{
2460 if (m_process_sp)
2461 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2462
2463 s->Printf("state = %s", StateAsCString(GetState()));;
2464}
2465
2466const Process::ProcessEventData *
2467Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2468{
2469 if (event_ptr)
2470 {
2471 const EventData *event_data = event_ptr->GetData();
2472 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2473 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2474 }
2475 return NULL;
2476}
2477
2478ProcessSP
2479Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2480{
2481 ProcessSP process_sp;
2482 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2483 if (data)
2484 process_sp = data->GetProcessSP();
2485 return process_sp;
2486}
2487
2488StateType
2489Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2490{
2491 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2492 if (data == NULL)
2493 return eStateInvalid;
2494 else
2495 return data->GetState();
2496}
2497
2498bool
2499Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2500{
2501 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2502 if (data == NULL)
2503 return false;
2504 else
2505 return data->GetRestarted();
2506}
2507
2508void
2509Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2510{
2511 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2512 if (data != NULL)
2513 data->SetRestarted(new_value);
2514}
2515
2516bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002517Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2518{
2519 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2520 if (data == NULL)
2521 return false;
2522 else
2523 return data->GetInterrupted ();
2524}
2525
2526void
2527Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2528{
2529 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2530 if (data != NULL)
2531 data->SetInterrupted(new_value);
2532}
2533
2534bool
Chris Lattner24943d22010-06-08 16:52:24 +00002535Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2536{
2537 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2538 if (data)
2539 {
2540 data->SetUpdateStateOnRemoval();
2541 return true;
2542 }
2543 return false;
2544}
2545
Chris Lattner24943d22010-06-08 16:52:24 +00002546void
Greg Claytona830adb2010-10-04 01:05:56 +00002547Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002548{
2549 exe_ctx.target = &m_target;
2550 exe_ctx.process = this;
2551 exe_ctx.thread = NULL;
2552 exe_ctx.frame = NULL;
2553}
2554
2555lldb::ProcessSP
2556Process::GetSP ()
2557{
2558 return GetTarget().GetProcessSP();
2559}
2560
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002561//uint32_t
2562//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2563//{
2564// return 0;
2565//}
2566//
2567//ArchSpec
2568//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2569//{
2570// return Host::GetArchSpecForExistingProcess (pid);
2571//}
2572//
2573//ArchSpec
2574//Process::GetArchSpecForExistingProcess (const char *process_name)
2575//{
2576// return Host::GetArchSpecForExistingProcess (process_name);
2577//}
2578//
Caroline Tice861efb32010-11-16 05:07:41 +00002579void
2580Process::AppendSTDOUT (const char * s, size_t len)
2581{
Greg Clayton20d338f2010-11-18 05:57:03 +00002582 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002583 m_stdout_data.append (s, len);
2584
Greg Claytonb3781332010-12-05 19:16:56 +00002585 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002586}
2587
2588void
2589Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2590{
2591 Process *process = (Process *) baton;
2592 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2593}
2594
2595size_t
2596Process::ProcessInputReaderCallback (void *baton,
2597 InputReader &reader,
2598 lldb::InputReaderAction notification,
2599 const char *bytes,
2600 size_t bytes_len)
2601{
2602 Process *process = (Process *) baton;
2603
2604 switch (notification)
2605 {
2606 case eInputReaderActivate:
2607 break;
2608
2609 case eInputReaderDeactivate:
2610 break;
2611
2612 case eInputReaderReactivate:
2613 break;
2614
2615 case eInputReaderGotToken:
2616 {
2617 Error error;
2618 process->PutSTDIN (bytes, bytes_len, error);
2619 }
2620 break;
2621
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002622 case eInputReaderInterrupt:
2623 process->Halt ();
2624 break;
2625
2626 case eInputReaderEndOfFile:
2627 process->AppendSTDOUT ("^D", 2);
2628 break;
2629
Caroline Tice861efb32010-11-16 05:07:41 +00002630 case eInputReaderDone:
2631 break;
2632
2633 }
2634
2635 return bytes_len;
2636}
2637
2638void
2639Process::ResetProcessInputReader ()
2640{
2641 m_process_input_reader.reset();
2642}
2643
2644void
2645Process::SetUpProcessInputReader (int file_descriptor)
2646{
2647 // First set up the Read Thread for reading/handling process I/O
2648
2649 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2650
2651 if (conn_ap.get())
2652 {
2653 m_stdio_communication.SetConnection (conn_ap.release());
2654 if (m_stdio_communication.IsConnected())
2655 {
2656 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2657 m_stdio_communication.StartReadThread();
2658
2659 // Now read thread is set up, set up input reader.
2660
2661 if (!m_process_input_reader.get())
2662 {
2663 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2664 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2665 this,
2666 eInputReaderGranularityByte,
2667 NULL,
2668 NULL,
2669 false));
2670
2671 if (err.Fail())
2672 m_process_input_reader.reset();
2673 }
2674 }
2675 }
2676}
2677
2678void
2679Process::PushProcessInputReader ()
2680{
2681 if (m_process_input_reader && !m_process_input_reader->IsActive())
2682 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2683}
2684
2685void
2686Process::PopProcessInputReader ()
2687{
2688 if (m_process_input_reader && m_process_input_reader->IsActive())
2689 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2690}
2691
Greg Claytond284b662011-02-18 01:44:25 +00002692// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00002693void
Caroline Tice2a456812011-03-10 22:14:10 +00002694Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002695{
Greg Claytonb3448432011-03-24 21:19:54 +00002696 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00002697
2698 int i=0;
2699 const char *name;
2700 OptionEnumValueElement option_enum;
2701 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
2702 {
2703 if (name)
2704 {
2705 option_enum.value = i;
2706 option_enum.string_value = name;
2707 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
2708 g_plugins.push_back (option_enum);
2709 }
2710 ++i;
2711 }
2712 option_enum.value = 0;
2713 option_enum.string_value = NULL;
2714 option_enum.usage = NULL;
2715 g_plugins.push_back (option_enum);
2716
2717 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
2718 {
2719 if (::strcmp (name, "plugin") == 0)
2720 {
2721 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
2722 break;
2723 }
2724 }
Greg Clayton990de7b2010-11-18 23:32:35 +00002725 UserSettingsControllerSP &usc = GetSettingsController();
2726 usc.reset (new SettingsController);
2727 UserSettingsController::InitializeSettingsController (usc,
2728 SettingsController::global_settings_table,
2729 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00002730
2731 // Now call SettingsInitialize() for each 'child' of Process settings
2732 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00002733}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002734
Greg Clayton990de7b2010-11-18 23:32:35 +00002735void
Caroline Tice2a456812011-03-10 22:14:10 +00002736Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00002737{
Caroline Tice2a456812011-03-10 22:14:10 +00002738 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
2739
2740 Thread::SettingsTerminate ();
2741
2742 // Now terminate Process Settings.
2743
Greg Clayton990de7b2010-11-18 23:32:35 +00002744 UserSettingsControllerSP &usc = GetSettingsController();
2745 UserSettingsController::FinalizeSettingsController (usc);
2746 usc.reset();
2747}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002748
Greg Clayton990de7b2010-11-18 23:32:35 +00002749UserSettingsControllerSP &
2750Process::GetSettingsController ()
2751{
2752 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002753 return g_settings_controller;
2754}
2755
Caroline Tice1ebef442010-09-27 00:30:10 +00002756void
2757Process::UpdateInstanceName ()
2758{
2759 ModuleSP module_sp = GetTarget().GetExecutableModule();
2760 if (module_sp)
2761 {
2762 StreamString sstr;
2763 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2764
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002765 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002766 sstr.GetData());
2767 }
2768}
2769
Greg Clayton427f2902010-12-14 02:59:59 +00002770ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002771Process::RunThreadPlan (ExecutionContext &exe_ctx,
2772 lldb::ThreadPlanSP &thread_plan_sp,
2773 bool stop_others,
2774 bool try_all_threads,
2775 bool discard_on_error,
2776 uint32_t single_thread_timeout_usec,
2777 Stream &errors)
2778{
2779 ExecutionResults return_value = eExecutionSetupError;
2780
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002781 if (thread_plan_sp.get() == NULL)
2782 {
2783 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00002784 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002785 }
2786
Jim Inghamac959662011-01-24 06:34:17 +00002787 if (m_private_state.GetValue() != eStateStopped)
2788 {
2789 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00002790 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00002791 }
2792
Jim Ingham360f53f2010-11-30 02:22:11 +00002793 // Save this value for restoration of the execution context after we run
2794 uint32_t tid = exe_ctx.thread->GetIndexID();
2795
2796 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2797 // so we should arrange to reset them as well.
2798
2799 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2800 lldb::StackFrameSP selected_frame_sp;
2801
2802 uint32_t selected_tid;
2803 if (selected_thread_sp != NULL)
2804 {
2805 selected_tid = selected_thread_sp->GetIndexID();
2806 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2807 }
2808 else
2809 {
2810 selected_tid = LLDB_INVALID_THREAD_ID;
2811 }
2812
2813 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2814
Jim Ingham6ae318c2011-01-23 21:14:08 +00002815 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00002816
2817 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2818 // restored on exit to the function.
2819
2820 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00002821
Jim Ingham6ae318c2011-01-23 21:14:08 +00002822 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002823 if (log)
2824 {
2825 StreamString s;
2826 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002827 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2828 exe_ctx.thread->GetIndexID(),
2829 exe_ctx.thread->GetID(),
2830 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002831 }
2832
Jim Inghamf9f40c22011-02-08 05:20:59 +00002833 bool got_event;
2834 lldb::EventSP event_sp;
2835 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00002836
2837 TimeValue* timeout_ptr = NULL;
2838 TimeValue real_timeout;
2839
Jim Inghamf9f40c22011-02-08 05:20:59 +00002840 bool first_timeout = true;
2841 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00002842
Jim Ingham360f53f2010-11-30 02:22:11 +00002843 while (1)
2844 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002845 // We usually want to resume the process if we get to the top of the loop.
2846 // The only exception is if we get two running events with no intervening
2847 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00002848
Jim Inghamf9f40c22011-02-08 05:20:59 +00002849 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00002850 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002851 // Do the initial resume and wait for the running event before going further.
2852
2853 Error resume_error = exe_ctx.process->Resume ();
2854 if (!resume_error.Success())
2855 {
2856 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00002857 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002858 break;
2859 }
2860
2861 real_timeout = TimeValue::Now();
2862 real_timeout.OffsetWithMicroSeconds(500000);
2863 timeout_ptr = &real_timeout;
2864
2865 got_event = listener.WaitForEvent(NULL, event_sp);
2866 if (!got_event)
2867 {
2868 if (log)
2869 log->Printf("Didn't get any event after initial resume, exiting.");
2870
2871 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00002872 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002873 break;
2874 }
2875
2876 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2877 if (stop_state != eStateRunning)
2878 {
2879 if (log)
2880 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2881
2882 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00002883 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002884 break;
2885 }
2886
2887 if (log)
2888 log->Printf ("Resuming succeeded.");
2889 // We need to call the function synchronously, so spin waiting for it to return.
2890 // If we get interrupted while executing, we're going to lose our context, and
2891 // won't be able to gather the result at this point.
2892 // We set the timeout AFTER the resume, since the resume takes some time and we
2893 // don't want to charge that to the timeout.
2894
2895 if (single_thread_timeout_usec != 0)
2896 {
2897 real_timeout = TimeValue::Now();
2898 if (first_timeout)
2899 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2900 else
2901 real_timeout.OffsetWithSeconds(10);
2902
2903 timeout_ptr = &real_timeout;
2904 }
2905 }
2906 else
2907 {
2908 if (log)
2909 log->Printf ("Handled an extra running event.");
2910 do_resume = true;
2911 }
2912
2913 // Now wait for the process to stop again:
2914 stop_state = lldb::eStateInvalid;
2915 event_sp.reset();
2916 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2917
2918 if (got_event)
2919 {
2920 if (event_sp.get())
2921 {
2922 bool keep_going = false;
2923 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2924 if (log)
2925 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2926
2927 switch (stop_state)
2928 {
2929 case lldb::eStateStopped:
2930 // Yay, we're done.
2931 if (log)
2932 log->Printf ("Execution completed successfully.");
Greg Claytonb3448432011-03-24 21:19:54 +00002933 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002934 break;
2935 case lldb::eStateCrashed:
2936 if (log)
2937 log->Printf ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00002938 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002939 break;
2940 case lldb::eStateRunning:
2941 do_resume = false;
2942 keep_going = true;
2943 break;
2944 default:
2945 if (log)
2946 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00002947 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002948 break;
2949 }
2950 if (keep_going)
2951 continue;
2952 else
2953 break;
2954 }
2955 else
2956 {
2957 if (log)
2958 log->Printf ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00002959 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00002960 break;
2961 }
2962 }
2963 else
2964 {
2965 // If we didn't get an event that means we've timed out...
2966 // We will interrupt the process here. Depending on what we were asked to do we will
2967 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00002968 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002969
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002970 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002971 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002972 {
2973 if (first_timeout)
2974 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2975 "trying with all threads enabled.",
2976 single_thread_timeout_usec);
2977 else
2978 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2979 "and timeout: %d timed out.",
2980 single_thread_timeout_usec);
2981 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002982 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00002983 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2984 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00002985 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002986 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002987
Jim Inghamc556b462011-01-22 01:30:53 +00002988 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00002989 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002990 {
Jim Ingham360f53f2010-11-30 02:22:11 +00002991 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00002992 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00002993
Jim Inghamf9f40c22011-02-08 05:20:59 +00002994 // If halt succeeds, it always produces a stopped event. Wait for that:
2995
2996 real_timeout = TimeValue::Now();
2997 real_timeout.OffsetWithMicroSeconds(500000);
2998
2999 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003000
3001 if (got_event)
3002 {
3003 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3004 if (log)
3005 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003006 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003007 if (stop_state == lldb::eStateStopped
3008 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003009 log->Printf (" Event was the Halt interruption event.");
3010 }
3011
Jim Inghamf9f40c22011-02-08 05:20:59 +00003012 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003013 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003014 // Between the time we initiated the Halt and the time we delivered it, the process could have
3015 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003016
Jim Inghamf9f40c22011-02-08 05:20:59 +00003017 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3018 {
3019 if (log)
3020 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3021 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003022 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003023 break;
3024 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003025
Jim Inghamf9f40c22011-02-08 05:20:59 +00003026 if (!try_all_threads)
3027 {
3028 if (log)
3029 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003030 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003031 break;
3032 }
3033
3034 if (first_timeout)
3035 {
3036 // Set all the other threads to run, and return to the top of the loop, which will continue;
3037 first_timeout = false;
3038 thread_plan_sp->SetStopOthers (false);
3039 if (log)
3040 log->Printf ("Process::RunThreadPlan(): About to resume.");
3041
3042 continue;
3043 }
3044 else
3045 {
3046 // Running all threads failed, so return Interrupted.
3047 if (log)
3048 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003049 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003050 break;
3051 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003052 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003053 }
3054 else
3055 { if (log)
3056 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
3057 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003058 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003059 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003060 }
3061 }
Jim Inghamc556b462011-01-22 01:30:53 +00003062 else
3063 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003064 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3065 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003066 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003067 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.",
3068 halt_error.AsCString());
3069 real_timeout = TimeValue::Now();
3070 real_timeout.OffsetWithMicroSeconds(500000);
3071 timeout_ptr = &real_timeout;
3072 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3073 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003074 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003075 // This is not going anywhere, bag out.
3076 if (log)
3077 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003078 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003079 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003080 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003081 else
3082 {
3083 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3084 if (log)
3085 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3086 if (stop_state == lldb::eStateStopped)
3087 {
3088 // Between the time we initiated the Halt and the time we delivered it, the process could have
3089 // already finished its job. Check that here:
3090
3091 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3092 {
3093 if (log)
3094 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3095 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003096 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003097 break;
3098 }
3099
3100 if (first_timeout)
3101 {
3102 // Set all the other threads to run, and return to the top of the loop, which will continue;
3103 first_timeout = false;
3104 thread_plan_sp->SetStopOthers (false);
3105 if (log)
3106 log->Printf ("Process::RunThreadPlan(): About to resume.");
3107
3108 continue;
3109 }
3110 else
3111 {
3112 // Running all threads failed, so return Interrupted.
3113 if (log)
3114 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003115 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003116 break;
3117 }
3118 }
3119 else
3120 {
3121 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3122 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003123 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003124 break;
3125 }
3126 }
Jim Inghamc556b462011-01-22 01:30:53 +00003127 }
3128
Jim Ingham360f53f2010-11-30 02:22:11 +00003129 }
3130
Jim Inghamf9f40c22011-02-08 05:20:59 +00003131 } // END WAIT LOOP
3132
3133 // Now do some processing on the results of the run:
3134 if (return_value == eExecutionInterrupted)
3135 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003136 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003137 {
3138 StreamString s;
3139 if (event_sp)
3140 event_sp->Dump (&s);
3141 else
3142 {
3143 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3144 }
3145
3146 StreamString ts;
3147
3148 const char *event_explanation;
3149
3150 do
3151 {
3152 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3153
3154 if (!event_data)
3155 {
3156 event_explanation = "<no event data>";
3157 break;
3158 }
3159
3160 Process *process = event_data->GetProcessSP().get();
3161
3162 if (!process)
3163 {
3164 event_explanation = "<no process>";
3165 break;
3166 }
3167
3168 ThreadList &thread_list = process->GetThreadList();
3169
3170 uint32_t num_threads = thread_list.GetSize();
3171 uint32_t thread_index;
3172
3173 ts.Printf("<%u threads> ", num_threads);
3174
3175 for (thread_index = 0;
3176 thread_index < num_threads;
3177 ++thread_index)
3178 {
3179 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3180
3181 if (!thread)
3182 {
3183 ts.Printf("<?> ");
3184 continue;
3185 }
3186
3187 ts.Printf("<0x%4.4x ", thread->GetID());
3188 RegisterContext *register_context = thread->GetRegisterContext().get();
3189
3190 if (register_context)
3191 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3192 else
3193 ts.Printf("[ip unknown] ");
3194
3195 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3196 if (stop_info_sp)
3197 {
3198 const char *stop_desc = stop_info_sp->GetDescription();
3199 if (stop_desc)
3200 ts.PutCString (stop_desc);
3201 }
3202 ts.Printf(">");
3203 }
3204
3205 event_explanation = ts.GetData();
3206 } while (0);
3207
3208 if (log)
3209 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3210
3211 if (discard_on_error && thread_plan_sp)
3212 {
3213 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3214 }
3215 }
3216 }
3217 else if (return_value == eExecutionSetupError)
3218 {
3219 if (log)
3220 log->Printf("Process::RunThreadPlan(): execution set up error.");
3221
3222 if (discard_on_error && thread_plan_sp)
3223 {
3224 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3225 }
3226 }
3227 else
3228 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003229 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3230 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003231 if (log)
3232 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003233 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003234 }
3235 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3236 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003237 if (log)
3238 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003239 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003240 }
3241 else
3242 {
3243 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003244 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003245 if (discard_on_error && thread_plan_sp)
3246 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003247 if (log)
3248 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003249 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3250 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003251 }
3252 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003253
Jim Ingham360f53f2010-11-30 02:22:11 +00003254 // Thread we ran the function in may have gone away because we ran the target
3255 // Check that it's still there.
3256 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3257 if (exe_ctx.thread)
3258 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3259
3260 // Also restore the current process'es selected frame & thread, since this function calling may
3261 // be done behind the user's back.
3262
3263 if (selected_tid != LLDB_INVALID_THREAD_ID)
3264 {
3265 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3266 {
3267 // We were able to restore the selected thread, now restore the frame:
3268 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3269 }
3270 }
3271
3272 return return_value;
3273}
3274
3275const char *
3276Process::ExecutionResultAsCString (ExecutionResults result)
3277{
3278 const char *result_name;
3279
3280 switch (result)
3281 {
Greg Claytonb3448432011-03-24 21:19:54 +00003282 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003283 result_name = "eExecutionCompleted";
3284 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003285 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003286 result_name = "eExecutionDiscarded";
3287 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003288 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003289 result_name = "eExecutionInterrupted";
3290 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003291 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003292 result_name = "eExecutionSetupError";
3293 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003294 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003295 result_name = "eExecutionTimedOut";
3296 break;
3297 }
3298 return result_name;
3299}
3300
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003301//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003302// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003303//--------------------------------------------------------------
3304
Greg Claytond0a5a232010-09-19 02:33:57 +00003305Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003306 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003307{
Greg Clayton638351a2010-12-04 00:10:17 +00003308 m_default_settings.reset (new ProcessInstanceSettings (*this,
3309 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00003310 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003311}
3312
Greg Claytond0a5a232010-09-19 02:33:57 +00003313Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003314{
3315}
3316
3317lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00003318Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003319{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003320 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3321 false,
3322 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003323 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3324 return new_settings_sp;
3325}
3326
3327//--------------------------------------------------------------
3328// class ProcessInstanceSettings
3329//--------------------------------------------------------------
3330
Greg Clayton638351a2010-12-04 00:10:17 +00003331ProcessInstanceSettings::ProcessInstanceSettings
3332(
3333 UserSettingsController &owner,
3334 bool live_instance,
3335 const char *name
3336) :
3337 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003338 m_run_args (),
3339 m_env_vars (),
3340 m_input_path (),
3341 m_output_path (),
3342 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00003343 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00003344 m_disable_stdio (false),
3345 m_inherit_host_env (true),
3346 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003347{
Caroline Tice396704b2010-09-09 18:26:37 +00003348 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3349 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3350 // 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 +00003351 // This is true for CreateInstanceName() too.
3352
3353 if (GetInstanceName () == InstanceSettings::InvalidName())
3354 {
3355 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3356 m_owner.RegisterInstanceSettings (this);
3357 }
Caroline Tice396704b2010-09-09 18:26:37 +00003358
3359 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003360 {
3361 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3362 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003363 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003364 }
3365}
3366
3367ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003368 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003369 m_run_args (rhs.m_run_args),
3370 m_env_vars (rhs.m_env_vars),
3371 m_input_path (rhs.m_input_path),
3372 m_output_path (rhs.m_output_path),
3373 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00003374 m_disable_aslr (rhs.m_disable_aslr),
3375 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003376{
3377 if (m_instance_name != InstanceSettings::GetDefaultName())
3378 {
3379 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3380 CopyInstanceSettings (pending_settings,false);
3381 m_owner.RemovePendingSettings (m_instance_name);
3382 }
3383}
3384
3385ProcessInstanceSettings::~ProcessInstanceSettings ()
3386{
3387}
3388
3389ProcessInstanceSettings&
3390ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3391{
3392 if (this != &rhs)
3393 {
3394 m_run_args = rhs.m_run_args;
3395 m_env_vars = rhs.m_env_vars;
3396 m_input_path = rhs.m_input_path;
3397 m_output_path = rhs.m_output_path;
3398 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003399 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003400 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003401 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003402 }
3403
3404 return *this;
3405}
3406
3407
3408void
3409ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3410 const char *index_value,
3411 const char *value,
3412 const ConstString &instance_name,
3413 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00003414 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003415 Error &err,
3416 bool pending)
3417{
3418 if (var_name == RunArgsVarName())
3419 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3420 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003421 {
3422 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003423 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003424 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003425 else if (var_name == InputPathVarName())
3426 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3427 else if (var_name == OutputPathVarName())
3428 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3429 else if (var_name == ErrorPathVarName())
3430 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003431 else if (var_name == DisableASLRVarName())
3432 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003433 else if (var_name == DisableSTDIOVarName ())
3434 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003435}
3436
3437void
3438ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3439 bool pending)
3440{
3441 if (new_settings.get() == NULL)
3442 return;
3443
3444 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3445
3446 m_run_args = new_process_settings->m_run_args;
3447 m_env_vars = new_process_settings->m_env_vars;
3448 m_input_path = new_process_settings->m_input_path;
3449 m_output_path = new_process_settings->m_output_path;
3450 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003451 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003452 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003453}
3454
Caroline Ticebcb5b452010-09-20 21:37:42 +00003455bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003456ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3457 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003458 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003459 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003460{
3461 if (var_name == RunArgsVarName())
3462 {
3463 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003464 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003465 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3466 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003467 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003468 }
3469 else if (var_name == EnvVarsVarName())
3470 {
Greg Clayton638351a2010-12-04 00:10:17 +00003471 GetHostEnvironmentIfNeeded ();
3472
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003473 if (m_env_vars.size() > 0)
3474 {
3475 std::map<std::string, std::string>::iterator pos;
3476 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3477 {
3478 StreamString value_str;
3479 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3480 value.AppendString (value_str.GetData());
3481 }
3482 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003483 }
3484 else if (var_name == InputPathVarName())
3485 {
3486 value.AppendString (m_input_path.c_str());
3487 }
3488 else if (var_name == OutputPathVarName())
3489 {
3490 value.AppendString (m_output_path.c_str());
3491 }
3492 else if (var_name == ErrorPathVarName())
3493 {
3494 value.AppendString (m_error_path.c_str());
3495 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003496 else if (var_name == InheritHostEnvVarName())
3497 {
3498 if (m_inherit_host_env)
3499 value.AppendString ("true");
3500 else
3501 value.AppendString ("false");
3502 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003503 else if (var_name == DisableASLRVarName())
3504 {
3505 if (m_disable_aslr)
3506 value.AppendString ("true");
3507 else
3508 value.AppendString ("false");
3509 }
Caroline Ticebd666012010-12-03 18:46:09 +00003510 else if (var_name == DisableSTDIOVarName())
3511 {
3512 if (m_disable_stdio)
3513 value.AppendString ("true");
3514 else
3515 value.AppendString ("false");
3516 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003517 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003518 {
3519 if (err)
3520 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3521 return false;
3522 }
3523 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003524}
3525
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003526const ConstString
3527ProcessInstanceSettings::CreateInstanceName ()
3528{
3529 static int instance_count = 1;
3530 StreamString sstr;
3531
3532 sstr.Printf ("process_%d", instance_count);
3533 ++instance_count;
3534
3535 const ConstString ret_val (sstr.GetData());
3536 return ret_val;
3537}
3538
3539const ConstString &
3540ProcessInstanceSettings::RunArgsVarName ()
3541{
3542 static ConstString run_args_var_name ("run-args");
3543
3544 return run_args_var_name;
3545}
3546
3547const ConstString &
3548ProcessInstanceSettings::EnvVarsVarName ()
3549{
3550 static ConstString env_vars_var_name ("env-vars");
3551
3552 return env_vars_var_name;
3553}
3554
3555const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003556ProcessInstanceSettings::InheritHostEnvVarName ()
3557{
3558 static ConstString g_name ("inherit-env");
3559
3560 return g_name;
3561}
3562
3563const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003564ProcessInstanceSettings::InputPathVarName ()
3565{
3566 static ConstString input_path_var_name ("input-path");
3567
3568 return input_path_var_name;
3569}
3570
3571const ConstString &
3572ProcessInstanceSettings::OutputPathVarName ()
3573{
Caroline Tice87097232010-09-07 18:35:40 +00003574 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003575
3576 return output_path_var_name;
3577}
3578
3579const ConstString &
3580ProcessInstanceSettings::ErrorPathVarName ()
3581{
Caroline Tice87097232010-09-07 18:35:40 +00003582 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003583
3584 return error_path_var_name;
3585}
3586
3587const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003588ProcessInstanceSettings::DisableASLRVarName ()
3589{
3590 static ConstString disable_aslr_var_name ("disable-aslr");
3591
3592 return disable_aslr_var_name;
3593}
3594
Caroline Ticebd666012010-12-03 18:46:09 +00003595const ConstString &
3596ProcessInstanceSettings::DisableSTDIOVarName ()
3597{
3598 static ConstString disable_stdio_var_name ("disable-stdio");
3599
3600 return disable_stdio_var_name;
3601}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003602
3603//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003604// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003605//--------------------------------------------------
3606
3607SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003608Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003609{
3610 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3611 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3612};
3613
3614
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003615SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003616Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003617{
Greg Clayton638351a2010-12-04 00:10:17 +00003618 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3619 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3620 { "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." },
3621 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003622 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3623 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3624 { "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 +00003625 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003626 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3627 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3628 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003629};
3630
3631
Jim Ingham7508e732010-08-09 23:31:02 +00003632