blob: 8968c755bc45fb20ebe0fb9b7ffca1cbf4fc535e [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Target/Target.h"
33#include "lldb/Target/TargetList.h"
34#include "lldb/Target/Thread.h"
35#include "lldb/Target/ThreadPlan.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
Greg Claytonfd119992011-01-07 06:08:19 +000040
41//----------------------------------------------------------------------
42// MemoryCache constructor
43//----------------------------------------------------------------------
44Process::MemoryCache::MemoryCache() :
45 m_cache_line_byte_size (512),
46 m_cache_mutex (Mutex::eMutexTypeRecursive),
47 m_cache ()
48{
49}
50
51//----------------------------------------------------------------------
52// Destructor
53//----------------------------------------------------------------------
54Process::MemoryCache::~MemoryCache()
55{
56}
57
58void
59Process::MemoryCache::Clear()
60{
61 Mutex::Locker locker (m_cache_mutex);
62 m_cache.clear();
63}
64
65void
66Process::MemoryCache::Flush (addr_t addr, size_t size)
67{
68 if (size == 0)
69 return;
70
71 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
72 const addr_t end_addr = (addr + size - 1);
73 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
74 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
75
76 Mutex::Locker locker (m_cache_mutex);
77 if (m_cache.empty())
78 return;
79
80 assert ((flush_start_addr % cache_line_byte_size) == 0);
81
82 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
83 {
84 collection::iterator pos = m_cache.find (curr_addr);
85 if (pos != m_cache.end())
86 m_cache.erase(pos);
87 }
88}
89
90size_t
91Process::MemoryCache::Read
92(
93 Process *process,
94 addr_t addr,
95 void *dst,
96 size_t dst_len,
97 Error &error
98)
99{
100 size_t bytes_left = dst_len;
101 if (dst && bytes_left > 0)
102 {
103 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
104 uint8_t *dst_buf = (uint8_t *)dst;
105 addr_t curr_addr = addr - (addr % cache_line_byte_size);
106 addr_t cache_offset = addr - curr_addr;
107 Mutex::Locker locker (m_cache_mutex);
108
109 while (bytes_left > 0)
110 {
111 collection::const_iterator pos = m_cache.find (curr_addr);
112 collection::const_iterator end = m_cache.end ();
113
114 if (pos != end)
115 {
116 size_t curr_read_size = cache_line_byte_size - cache_offset;
117 if (curr_read_size > bytes_left)
118 curr_read_size = bytes_left;
119
120 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
121
122 bytes_left -= curr_read_size;
123 curr_addr += curr_read_size + cache_offset;
124 cache_offset = 0;
125
126 if (bytes_left > 0)
127 {
128 // Get sequential cache page hits
129 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
130 {
131 assert ((curr_addr % cache_line_byte_size) == 0);
132
133 if (pos->first != curr_addr)
134 break;
135
136 curr_read_size = pos->second->GetByteSize();
137 if (curr_read_size > bytes_left)
138 curr_read_size = bytes_left;
139
140 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
141
142 bytes_left -= curr_read_size;
143 curr_addr += curr_read_size;
144
145 // We have a cache page that succeeded to read some bytes
146 // but not an entire page. If this happens, we must cap
147 // off how much data we are able to read...
148 if (pos->second->GetByteSize() != cache_line_byte_size)
149 return dst_len - bytes_left;
150 }
151 }
152 }
153
154 // We need to read from the process
155
156 if (bytes_left > 0)
157 {
158 assert ((curr_addr % cache_line_byte_size) == 0);
159 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
160 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
161 data_buffer_heap_ap->GetBytes(),
162 data_buffer_heap_ap->GetByteSize(),
163 error);
164 if (process_bytes_read == 0)
165 return dst_len - bytes_left;
166
167 if (process_bytes_read != cache_line_byte_size)
168 data_buffer_heap_ap->SetByteSize (process_bytes_read);
169 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
170 // We have read data and put it into the cache, continue through the
171 // loop again to get the data out of the cache...
172 }
173 }
174 }
175
176 return dst_len - bytes_left;
177}
178
Chris Lattner24943d22010-06-08 16:52:24 +0000179Process*
180Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
181{
182 ProcessCreateInstance create_callback = NULL;
183 if (plugin_name)
184 {
185 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
186 if (create_callback)
187 {
188 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
189 if (debugger_ap->CanDebug(target))
190 return debugger_ap.release();
191 }
192 }
193 else
194 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000196 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000197 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
198 if (debugger_ap->CanDebug(target))
199 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000200 }
201 }
202 return NULL;
203}
204
205
206//----------------------------------------------------------------------
207// Process constructor
208//----------------------------------------------------------------------
209Process::Process(Target &target, Listener &listener) :
210 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000211 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000212 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000213 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000214 m_public_state (eStateUnloaded),
215 m_private_state (eStateUnloaded),
216 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
217 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
218 m_private_state_listener ("lldb.process.internal_state_listener"),
219 m_private_state_control_wait(),
220 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
221 m_stop_id (0),
222 m_thread_index_id (0),
223 m_exit_status (-1),
224 m_exit_string (),
225 m_thread_list (this),
226 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000227 m_image_tokens (),
228 m_listener (listener),
229 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000230 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000231 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000232 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000233 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000234 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000235 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000236 m_stdout_data (),
Jim Inghamc2dc7c82011-01-29 01:49:25 +0000237 m_memory_cache (),
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000238 m_next_event_action_ap()
Chris Lattner24943d22010-06-08 16:52:24 +0000239{
Caroline Tice1ebef442010-09-27 00:30:10 +0000240 UpdateInstanceName();
241
Greg Claytone005f2c2010-11-06 01:53:30 +0000242 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000243 if (log)
244 log->Printf ("%p Process::Process()", this);
245
Greg Clayton49ce6822010-10-31 03:01:06 +0000246 SetEventName (eBroadcastBitStateChanged, "state-changed");
247 SetEventName (eBroadcastBitInterrupt, "interrupt");
248 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
249 SetEventName (eBroadcastBitSTDERR, "stderr-available");
250
Chris Lattner24943d22010-06-08 16:52:24 +0000251 listener.StartListeningForEvents (this,
252 eBroadcastBitStateChanged |
253 eBroadcastBitInterrupt |
254 eBroadcastBitSTDOUT |
255 eBroadcastBitSTDERR);
256
257 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
258 eBroadcastBitStateChanged);
259
260 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
261 eBroadcastInternalStateControlStop |
262 eBroadcastInternalStateControlPause |
263 eBroadcastInternalStateControlResume);
264}
265
266//----------------------------------------------------------------------
267// Destructor
268//----------------------------------------------------------------------
269Process::~Process()
270{
Greg Claytone005f2c2010-11-06 01:53:30 +0000271 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000272 if (log)
273 log->Printf ("%p Process::~Process()", this);
274 StopPrivateStateThread();
275}
276
277void
278Process::Finalize()
279{
280 // Do any cleanup needed prior to being destructed... Subclasses
281 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000282
283 // We need to destroy the loader before the derived Process class gets destroyed
284 // since it is very likely that undoing the loader will require access to the real process.
285 if (m_dyld_ap.get() != NULL)
286 m_dyld_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000287}
288
289void
290Process::RegisterNotificationCallbacks (const Notifications& callbacks)
291{
292 m_notifications.push_back(callbacks);
293 if (callbacks.initialize != NULL)
294 callbacks.initialize (callbacks.baton, this);
295}
296
297bool
298Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
299{
300 std::vector<Notifications>::iterator pos, end = m_notifications.end();
301 for (pos = m_notifications.begin(); pos != end; ++pos)
302 {
303 if (pos->baton == callbacks.baton &&
304 pos->initialize == callbacks.initialize &&
305 pos->process_state_changed == callbacks.process_state_changed)
306 {
307 m_notifications.erase(pos);
308 return true;
309 }
310 }
311 return false;
312}
313
314void
315Process::SynchronouslyNotifyStateChanged (StateType state)
316{
317 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
318 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
319 {
320 if (notification_pos->process_state_changed)
321 notification_pos->process_state_changed (notification_pos->baton, this, state);
322 }
323}
324
325// FIXME: We need to do some work on events before the general Listener sees them.
326// For instance if we are continuing from a breakpoint, we need to ensure that we do
327// the little "insert real insn, step & stop" trick. But we can't do that when the
328// event is delivered by the broadcaster - since that is done on the thread that is
329// waiting for new events, so if we needed more than one event for our handling, we would
330// stall. So instead we do it when we fetch the event off of the queue.
331//
332
333StateType
334Process::GetNextEvent (EventSP &event_sp)
335{
336 StateType state = eStateInvalid;
337
338 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
339 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
340
341 return state;
342}
343
344
345StateType
346Process::WaitForProcessToStop (const TimeValue *timeout)
347{
348 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
349 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
350}
351
352
353StateType
354Process::WaitForState
355(
356 const TimeValue *timeout,
357 const StateType *match_states, const uint32_t num_match_states
358)
359{
360 EventSP event_sp;
361 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000362 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000363 while (state != eStateInvalid)
364 {
Greg Claytond8c62532010-10-07 04:19:01 +0000365 // If we are exited or detached, we won't ever get back to any
366 // other valid state...
367 if (state == eStateDetached || state == eStateExited)
368 return state;
369
Chris Lattner24943d22010-06-08 16:52:24 +0000370 state = WaitForStateChangedEvents (timeout, event_sp);
371
372 for (i=0; i<num_match_states; ++i)
373 {
374 if (match_states[i] == state)
375 return state;
376 }
377 }
378 return state;
379}
380
Jim Ingham63e24d72010-10-11 23:53:14 +0000381bool
382Process::HijackProcessEvents (Listener *listener)
383{
384 if (listener != NULL)
385 {
386 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
387 }
388 else
389 return false;
390}
391
392void
393Process::RestoreProcessEvents ()
394{
395 RestoreBroadcaster();
396}
397
Jim Inghamf9f40c22011-02-08 05:20:59 +0000398bool
399Process::HijackPrivateProcessEvents (Listener *listener)
400{
401 if (listener != NULL)
402 {
403 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
404 }
405 else
406 return false;
407}
408
409void
410Process::RestorePrivateProcessEvents ()
411{
412 m_private_state_broadcaster.RestoreBroadcaster();
413}
414
Chris Lattner24943d22010-06-08 16:52:24 +0000415StateType
416Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
417{
Greg Claytone005f2c2010-11-06 01:53:30 +0000418 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000419
420 if (log)
421 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
422
423 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000424 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
425 this,
426 eBroadcastBitStateChanged,
427 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000428 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
429
430 if (log)
431 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
432 __FUNCTION__,
433 timeout,
434 StateAsCString(state));
435 return state;
436}
437
438Event *
439Process::PeekAtStateChangedEvents ()
440{
Greg Claytone005f2c2010-11-06 01:53:30 +0000441 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000442
443 if (log)
444 log->Printf ("Process::%s...", __FUNCTION__);
445
446 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000447 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
448 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000449 if (log)
450 {
451 if (event_ptr)
452 {
453 log->Printf ("Process::%s (event_ptr) => %s",
454 __FUNCTION__,
455 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
456 }
457 else
458 {
459 log->Printf ("Process::%s no events found",
460 __FUNCTION__);
461 }
462 }
463 return event_ptr;
464}
465
466StateType
467Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
468{
Greg Claytone005f2c2010-11-06 01:53:30 +0000469 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000470
471 if (log)
472 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
473
474 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000475 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
476 &m_private_state_broadcaster,
477 eBroadcastBitStateChanged,
478 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000479 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
480
481 // This is a bit of a hack, but when we wait here we could very well return
482 // to the command-line, and that could disable the log, which would render the
483 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000484 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000485 {
486 if (state == eStateInvalid)
487 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
488 else
489 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
490 }
Chris Lattner24943d22010-06-08 16:52:24 +0000491 return state;
492}
493
494bool
495Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
496{
Greg Claytone005f2c2010-11-06 01:53:30 +0000497 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000498
499 if (log)
500 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
501
502 if (control_only)
503 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
504 else
505 return m_private_state_listener.WaitForEvent(timeout, event_sp);
506}
507
508bool
509Process::IsRunning () const
510{
511 return StateIsRunningState (m_public_state.GetValue());
512}
513
514int
515Process::GetExitStatus ()
516{
517 if (m_public_state.GetValue() == eStateExited)
518 return m_exit_status;
519 return -1;
520}
521
Greg Clayton638351a2010-12-04 00:10:17 +0000522
523void
524Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
525{
526 if (m_inherit_host_env && !m_got_host_env)
527 {
528 m_got_host_env = true;
529 StringList host_env;
530 const size_t host_env_count = Host::GetEnvironment (host_env);
531 for (size_t idx=0; idx<host_env_count; idx++)
532 {
533 const char *env_entry = host_env.GetStringAtIndex (idx);
534 if (env_entry)
535 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000536 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000537 if (equal_pos)
538 {
539 std::string key (env_entry, equal_pos - env_entry);
540 std::string value (equal_pos + 1);
541 if (m_env_vars.find (key) == m_env_vars.end())
542 m_env_vars[key] = value;
543 }
544 }
545 }
546 }
547}
548
549
550size_t
551Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
552{
553 GetHostEnvironmentIfNeeded ();
554
555 dictionary::const_iterator pos, end = m_env_vars.end();
556 for (pos = m_env_vars.begin(); pos != end; ++pos)
557 {
558 std::string env_var_equal_value (pos->first);
559 env_var_equal_value.append(1, '=');
560 env_var_equal_value.append (pos->second);
561 env.AppendArgument (env_var_equal_value.c_str());
562 }
563 return env.GetArgumentCount();
564}
565
566
Chris Lattner24943d22010-06-08 16:52:24 +0000567const char *
568Process::GetExitDescription ()
569{
570 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
571 return m_exit_string.c_str();
572 return NULL;
573}
574
Greg Clayton72e1c782011-01-22 23:43:18 +0000575bool
Chris Lattner24943d22010-06-08 16:52:24 +0000576Process::SetExitStatus (int status, const char *cstr)
577{
Greg Clayton68ca8232011-01-25 02:58:48 +0000578 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
579 if (log)
580 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
581 status, status,
582 cstr ? "\"" : "",
583 cstr ? cstr : "NULL",
584 cstr ? "\"" : "");
585
Greg Clayton72e1c782011-01-22 23:43:18 +0000586 // We were already in the exited state
587 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +0000588 {
Greg Clayton644ddfb2011-01-26 23:47:29 +0000589 if (log)
590 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +0000591 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +0000592 }
Greg Clayton72e1c782011-01-22 23:43:18 +0000593
594 m_exit_status = status;
595 if (cstr)
596 m_exit_string = cstr;
597 else
598 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000599
Greg Clayton72e1c782011-01-22 23:43:18 +0000600 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +0000601
Greg Clayton72e1c782011-01-22 23:43:18 +0000602 SetPrivateState (eStateExited);
603 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000604}
605
606// This static callback can be used to watch for local child processes on
607// the current host. The the child process exits, the process will be
608// found in the global target list (we want to be completely sure that the
609// lldb_private::Process doesn't go away before we can deliver the signal.
610bool
611Process::SetProcessExitStatus
612(
613 void *callback_baton,
614 lldb::pid_t pid,
615 int signo, // Zero for no signal
616 int exit_status // Exit value of process if signal is zero
617)
618{
619 if (signo == 0 || exit_status)
620 {
Greg Clayton63094e02010-06-23 01:19:29 +0000621 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000622 if (target_sp)
623 {
624 ProcessSP process_sp (target_sp->GetProcessSP());
625 if (process_sp)
626 {
627 const char *signal_cstr = NULL;
628 if (signo)
629 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
630
631 process_sp->SetExitStatus (exit_status, signal_cstr);
632 }
633 }
634 return true;
635 }
636 return false;
637}
638
639
640uint32_t
641Process::GetNextThreadIndexID ()
642{
643 return ++m_thread_index_id;
644}
645
646StateType
647Process::GetState()
648{
649 // If any other threads access this we will need a mutex for it
650 return m_public_state.GetValue ();
651}
652
653void
654Process::SetPublicState (StateType new_state)
655{
Greg Clayton68ca8232011-01-25 02:58:48 +0000656 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000657 if (log)
658 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
659 m_public_state.SetValue (new_state);
660}
661
662StateType
663Process::GetPrivateState ()
664{
665 return m_private_state.GetValue();
666}
667
668void
669Process::SetPrivateState (StateType new_state)
670{
Greg Clayton68ca8232011-01-25 02:58:48 +0000671 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000672 bool state_changed = false;
673
674 if (log)
675 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
676
677 Mutex::Locker locker(m_private_state.GetMutex());
678
679 const StateType old_state = m_private_state.GetValueNoLock ();
680 state_changed = old_state != new_state;
681 if (state_changed)
682 {
683 m_private_state.SetValueNoLock (new_state);
684 if (StateIsStoppedState(new_state))
685 {
686 m_stop_id++;
Greg Claytonfd119992011-01-07 06:08:19 +0000687 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000688 if (log)
689 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
690 }
691 // Use our target to get a shared pointer to ourselves...
692 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
693 }
694 else
695 {
696 if (log)
697 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
698 }
699}
700
701
702uint32_t
703Process::GetStopID() const
704{
705 return m_stop_id;
706}
707
708addr_t
709Process::GetImageInfoAddress()
710{
711 return LLDB_INVALID_ADDRESS;
712}
713
Greg Clayton0baa3942010-11-04 01:54:29 +0000714//----------------------------------------------------------------------
715// LoadImage
716//
717// This function provides a default implementation that works for most
718// unix variants. Any Process subclasses that need to do shared library
719// loading differently should override LoadImage and UnloadImage and
720// do what is needed.
721//----------------------------------------------------------------------
722uint32_t
723Process::LoadImage (const FileSpec &image_spec, Error &error)
724{
725 DynamicLoader *loader = GetDynamicLoader();
726 if (loader)
727 {
728 error = loader->CanLoadImage();
729 if (error.Fail())
730 return LLDB_INVALID_IMAGE_TOKEN;
731 }
732
733 if (error.Success())
734 {
735 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
736 if (thread_sp == NULL)
737 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
738
739 if (thread_sp)
740 {
741 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
742
743 if (frame_sp)
744 {
745 ExecutionContext exe_ctx;
746 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000747 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000748 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000749 StreamString expr;
750 char path[PATH_MAX];
751 image_spec.GetPath(path, sizeof(path));
752 expr.Printf("dlopen (\"%s\", 2)", path);
753 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000754 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000755 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000756 if (result_valobj_sp->GetError().Success())
757 {
758 Scalar scalar;
759 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
760 {
761 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
762 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
763 {
764 uint32_t image_token = m_image_tokens.size();
765 m_image_tokens.push_back (image_ptr);
766 return image_token;
767 }
768 }
769 }
770 }
771 }
772 }
773 return LLDB_INVALID_IMAGE_TOKEN;
774}
775
776//----------------------------------------------------------------------
777// UnloadImage
778//
779// This function provides a default implementation that works for most
780// unix variants. Any Process subclasses that need to do shared library
781// loading differently should override LoadImage and UnloadImage and
782// do what is needed.
783//----------------------------------------------------------------------
784Error
785Process::UnloadImage (uint32_t image_token)
786{
787 Error error;
788 if (image_token < m_image_tokens.size())
789 {
790 const addr_t image_addr = m_image_tokens[image_token];
791 if (image_addr == LLDB_INVALID_ADDRESS)
792 {
793 error.SetErrorString("image already unloaded");
794 }
795 else
796 {
797 DynamicLoader *loader = GetDynamicLoader();
798 if (loader)
799 error = loader->CanLoadImage();
800
801 if (error.Success())
802 {
803 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
804 if (thread_sp == NULL)
805 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
806
807 if (thread_sp)
808 {
809 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
810
811 if (frame_sp)
812 {
813 ExecutionContext exe_ctx;
814 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000815 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000816 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000817 StreamString expr;
818 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
819 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000820 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000821 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000822 if (result_valobj_sp->GetError().Success())
823 {
824 Scalar scalar;
825 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
826 {
827 if (scalar.UInt(1))
828 {
829 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
830 }
831 else
832 {
833 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
834 }
835 }
836 }
837 else
838 {
839 error = result_valobj_sp->GetError();
840 }
841 }
842 }
843 }
844 }
845 }
846 else
847 {
848 error.SetErrorString("invalid image token");
849 }
850 return error;
851}
852
Chris Lattner24943d22010-06-08 16:52:24 +0000853const ABI *
854Process::GetABI()
855{
Chris Lattner24943d22010-06-08 16:52:24 +0000856 if (m_abi_sp.get() == NULL)
Greg Clayton395fc332011-02-15 21:59:32 +0000857 m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
Chris Lattner24943d22010-06-08 16:52:24 +0000858
859 return m_abi_sp.get();
860}
861
Jim Ingham642036f2010-09-23 02:01:19 +0000862LanguageRuntime *
863Process::GetLanguageRuntime(lldb::LanguageType language)
864{
865 LanguageRuntimeCollection::iterator pos;
866 pos = m_language_runtimes.find (language);
867 if (pos == m_language_runtimes.end())
868 {
869 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
870
871 m_language_runtimes[language]
872 = runtime;
873 return runtime.get();
874 }
875 else
876 return (*pos).second.get();
877}
878
879CPPLanguageRuntime *
880Process::GetCPPLanguageRuntime ()
881{
882 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
883 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
884 return static_cast<CPPLanguageRuntime *> (runtime);
885 return NULL;
886}
887
888ObjCLanguageRuntime *
889Process::GetObjCLanguageRuntime ()
890{
891 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
892 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
893 return static_cast<ObjCLanguageRuntime *> (runtime);
894 return NULL;
895}
896
Chris Lattner24943d22010-06-08 16:52:24 +0000897BreakpointSiteList &
898Process::GetBreakpointSiteList()
899{
900 return m_breakpoint_site_list;
901}
902
903const BreakpointSiteList &
904Process::GetBreakpointSiteList() const
905{
906 return m_breakpoint_site_list;
907}
908
909
910void
911Process::DisableAllBreakpointSites ()
912{
913 m_breakpoint_site_list.SetEnabledForAll (false);
914}
915
916Error
917Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
918{
919 Error error (DisableBreakpointSiteByID (break_id));
920
921 if (error.Success())
922 m_breakpoint_site_list.Remove(break_id);
923
924 return error;
925}
926
927Error
928Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
929{
930 Error error;
931 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
932 if (bp_site_sp)
933 {
934 if (bp_site_sp->IsEnabled())
935 error = DisableBreakpoint (bp_site_sp.get());
936 }
937 else
938 {
939 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
940 }
941
942 return error;
943}
944
945Error
946Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
947{
948 Error error;
949 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
950 if (bp_site_sp)
951 {
952 if (!bp_site_sp->IsEnabled())
953 error = EnableBreakpoint (bp_site_sp.get());
954 }
955 else
956 {
957 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
958 }
959 return error;
960}
961
Stephen Wilson3fd1f362010-07-17 00:56:13 +0000962lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +0000963Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
964{
Greg Claytoneea26402010-09-14 23:36:40 +0000965 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +0000966 if (load_addr != LLDB_INVALID_ADDRESS)
967 {
968 BreakpointSiteSP bp_site_sp;
969
970 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
971 // create a new breakpoint site and add it.
972
973 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
974
975 if (bp_site_sp)
976 {
977 bp_site_sp->AddOwner (owner);
978 owner->SetBreakpointSite (bp_site_sp);
979 return bp_site_sp->GetID();
980 }
981 else
982 {
983 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
984 if (bp_site_sp)
985 {
986 if (EnableBreakpoint (bp_site_sp.get()).Success())
987 {
988 owner->SetBreakpointSite (bp_site_sp);
989 return m_breakpoint_site_list.Add (bp_site_sp);
990 }
991 }
992 }
993 }
994 // We failed to enable the breakpoint
995 return LLDB_INVALID_BREAK_ID;
996
997}
998
999void
1000Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1001{
1002 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1003 if (num_owners == 0)
1004 {
1005 DisableBreakpoint(bp_site_sp.get());
1006 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1007 }
1008}
1009
1010
1011size_t
1012Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1013{
1014 size_t bytes_removed = 0;
1015 addr_t intersect_addr;
1016 size_t intersect_size;
1017 size_t opcode_offset;
1018 size_t idx;
1019 BreakpointSiteSP bp;
1020
1021 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1022 {
1023 if (bp->GetType() == BreakpointSite::eSoftware)
1024 {
1025 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1026 {
1027 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1028 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1029 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1030 size_t buf_offset = intersect_addr - bp_addr;
1031 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1032 }
1033 }
1034 }
1035 return bytes_removed;
1036}
1037
1038
1039Error
1040Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1041{
1042 Error error;
1043 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001044 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001045 const addr_t bp_addr = bp_site->GetLoadAddress();
1046 if (log)
1047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1048 if (bp_site->IsEnabled())
1049 {
1050 if (log)
1051 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1052 return error;
1053 }
1054
1055 if (bp_addr == LLDB_INVALID_ADDRESS)
1056 {
1057 error.SetErrorString("BreakpointSite contains an invalid load address.");
1058 return error;
1059 }
1060 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1061 // trap for the breakpoint site
1062 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1063
1064 if (bp_opcode_size == 0)
1065 {
1066 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1067 }
1068 else
1069 {
1070 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1071
1072 if (bp_opcode_bytes == NULL)
1073 {
1074 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1075 return error;
1076 }
1077
1078 // Save the original opcode by reading it
1079 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1080 {
1081 // Write a software breakpoint in place of the original opcode
1082 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1083 {
1084 uint8_t verify_bp_opcode_bytes[64];
1085 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1086 {
1087 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1088 {
1089 bp_site->SetEnabled(true);
1090 bp_site->SetType (BreakpointSite::eSoftware);
1091 if (log)
1092 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1093 bp_site->GetID(),
1094 (uint64_t)bp_addr);
1095 }
1096 else
1097 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1098 }
1099 else
1100 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1101 }
1102 else
1103 error.SetErrorString("Unable to write breakpoint trap to memory.");
1104 }
1105 else
1106 error.SetErrorString("Unable to read memory at breakpoint address.");
1107 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001108 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001109 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1110 bp_site->GetID(),
1111 (uint64_t)bp_addr,
1112 error.AsCString());
1113 return error;
1114}
1115
1116Error
1117Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1118{
1119 Error error;
1120 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001121 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001122 addr_t bp_addr = bp_site->GetLoadAddress();
1123 lldb::user_id_t breakID = bp_site->GetID();
1124 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001125 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001126
1127 if (bp_site->IsHardware())
1128 {
1129 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1130 }
1131 else if (bp_site->IsEnabled())
1132 {
1133 const size_t break_op_size = bp_site->GetByteSize();
1134 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1135 if (break_op_size > 0)
1136 {
1137 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001138 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001139 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001140 bool break_op_found = false;
1141
1142 // Read the breakpoint opcode
1143 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1144 {
1145 bool verify = false;
1146 // Make sure we have the a breakpoint opcode exists at this address
1147 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1148 {
1149 break_op_found = true;
1150 // We found a valid breakpoint opcode at this address, now restore
1151 // the saved opcode.
1152 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1153 {
1154 verify = true;
1155 }
1156 else
1157 error.SetErrorString("Memory write failed when restoring original opcode.");
1158 }
1159 else
1160 {
1161 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1162 // Set verify to true and so we can check if the original opcode has already been restored
1163 verify = true;
1164 }
1165
1166 if (verify)
1167 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001168 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001169 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001170 // Verify that our original opcode made it back to the inferior
1171 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1172 {
1173 // compare the memory we just read with the original opcode
1174 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1175 {
1176 // SUCCESS
1177 bp_site->SetEnabled(false);
1178 if (log)
1179 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1180 return error;
1181 }
1182 else
1183 {
1184 if (break_op_found)
1185 error.SetErrorString("Failed to restore original opcode.");
1186 }
1187 }
1188 else
1189 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1190 }
1191 }
1192 else
1193 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1194 }
1195 }
1196 else
1197 {
1198 if (log)
1199 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1200 return error;
1201 }
1202
1203 if (log)
1204 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1205 bp_site->GetID(),
1206 (uint64_t)bp_addr,
1207 error.AsCString());
1208 return error;
1209
1210}
1211
Greg Claytonfd119992011-01-07 06:08:19 +00001212// Comment out line below to disable memory caching
1213#define ENABLE_MEMORY_CACHING
1214// Uncomment to verify memory caching works after making changes to caching code
1215//#define VERIFY_MEMORY_READS
1216
1217#if defined (ENABLE_MEMORY_CACHING)
1218
1219#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001220
1221size_t
1222Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1223{
Greg Claytonfd119992011-01-07 06:08:19 +00001224 // Memory caching is enabled, with debug verification
1225 if (buf && size)
1226 {
1227 // Uncomment the line below to make sure memory caching is working.
1228 // I ran this through the test suite and got no assertions, so I am
1229 // pretty confident this is working well. If any changes are made to
1230 // memory caching, uncomment the line below and test your changes!
1231
1232 // Verify all memory reads by using the cache first, then redundantly
1233 // reading the same memory from the inferior and comparing to make sure
1234 // everything is exactly the same.
1235 std::string verify_buf (size, '\0');
1236 assert (verify_buf.size() == size);
1237 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1238 Error verify_error;
1239 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1240 assert (cache_bytes_read == verify_bytes_read);
1241 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1242 assert (verify_error.Success() == error.Success());
1243 return cache_bytes_read;
1244 }
1245 return 0;
1246}
1247
1248#else // #if defined (VERIFY_MEMORY_READS)
1249
1250size_t
1251Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1252{
1253 // Memory caching enabled, no verification
1254 return m_memory_cache.Read (this, addr, buf, size, error);
1255}
1256
1257#endif // #else for #if defined (VERIFY_MEMORY_READS)
1258
1259#else // #if defined (ENABLE_MEMORY_CACHING)
1260
1261size_t
1262Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1263{
1264 // Memory caching is disabled
1265 return ReadMemoryFromInferior (addr, buf, size, error);
1266}
1267
1268#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1269
1270
1271size_t
1272Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1273{
Chris Lattner24943d22010-06-08 16:52:24 +00001274 if (buf == NULL || size == 0)
1275 return 0;
1276
1277 size_t bytes_read = 0;
1278 uint8_t *bytes = (uint8_t *)buf;
1279
1280 while (bytes_read < size)
1281 {
1282 const size_t curr_size = size - bytes_read;
1283 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1284 bytes + bytes_read,
1285 curr_size,
1286 error);
1287 bytes_read += curr_bytes_read;
1288 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1289 break;
1290 }
1291
1292 // Replace any software breakpoint opcodes that fall into this range back
1293 // into "buf" before we return
1294 if (bytes_read > 0)
1295 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1296 return bytes_read;
1297}
1298
Greg Claytonf72fdee2010-12-16 20:01:20 +00001299uint64_t
1300Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1301{
1302 if (integer_byte_size > sizeof(uint64_t))
1303 {
1304 error.SetErrorString ("unsupported integer size");
1305 }
1306 else
1307 {
1308 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton395fc332011-02-15 21:59:32 +00001309 DataExtractor data (tmp,
1310 integer_byte_size,
1311 m_target.GetArchitecture().GetByteOrder(),
1312 m_target.GetArchitecture().GetAddressByteSize());
Greg Claytonf72fdee2010-12-16 20:01:20 +00001313 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1314 {
1315 uint32_t offset = 0;
1316 return data.GetMaxU64 (&offset, integer_byte_size);
1317 }
1318 }
1319 // Any plug-in that doesn't return success a memory read with the number
1320 // of bytes that were requested should be setting the error
1321 assert (error.Fail());
1322 return 0;
1323}
1324
Chris Lattner24943d22010-06-08 16:52:24 +00001325size_t
1326Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1327{
1328 size_t bytes_written = 0;
1329 const uint8_t *bytes = (const uint8_t *)buf;
1330
1331 while (bytes_written < size)
1332 {
1333 const size_t curr_size = size - bytes_written;
1334 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1335 bytes + bytes_written,
1336 curr_size,
1337 error);
1338 bytes_written += curr_bytes_written;
1339 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1340 break;
1341 }
1342 return bytes_written;
1343}
1344
1345size_t
1346Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1347{
Greg Claytonfd119992011-01-07 06:08:19 +00001348#if defined (ENABLE_MEMORY_CACHING)
1349 m_memory_cache.Flush (addr, size);
1350#endif
1351
Chris Lattner24943d22010-06-08 16:52:24 +00001352 if (buf == NULL || size == 0)
1353 return 0;
1354 // We need to write any data that would go where any current software traps
1355 // (enabled software breakpoints) any software traps (breakpoints) that we
1356 // may have placed in our tasks memory.
1357
1358 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1359 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1360
1361 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1362 return DoWriteMemory(addr, buf, size, error);
1363
1364 BreakpointSiteList::collection::const_iterator pos;
1365 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001366 addr_t intersect_addr = 0;
1367 size_t intersect_size = 0;
1368 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001369 const uint8_t *ubuf = (const uint8_t *)buf;
1370
1371 for (pos = iter; pos != end; ++pos)
1372 {
1373 BreakpointSiteSP bp;
1374 bp = pos->second;
1375
1376 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1377 assert(addr <= intersect_addr && intersect_addr < addr + size);
1378 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1379 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1380
1381 // Check for bytes before this breakpoint
1382 const addr_t curr_addr = addr + bytes_written;
1383 if (intersect_addr > curr_addr)
1384 {
1385 // There are some bytes before this breakpoint that we need to
1386 // just write to memory
1387 size_t curr_size = intersect_addr - curr_addr;
1388 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1389 ubuf + bytes_written,
1390 curr_size,
1391 error);
1392 bytes_written += curr_bytes_written;
1393 if (curr_bytes_written != curr_size)
1394 {
1395 // We weren't able to write all of the requested bytes, we
1396 // are done looping and will return the number of bytes that
1397 // we have written so far.
1398 break;
1399 }
1400 }
1401
1402 // Now write any bytes that would cover up any software breakpoints
1403 // directly into the breakpoint opcode buffer
1404 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1405 bytes_written += intersect_size;
1406 }
1407
1408 // Write any remaining bytes after the last breakpoint if we have any left
1409 if (bytes_written < size)
1410 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1411 ubuf + bytes_written,
1412 size - bytes_written,
1413 error);
1414
1415 return bytes_written;
1416}
1417
1418addr_t
1419Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1420{
1421 // Fixme: we should track the blocks we've allocated, and clean them up...
1422 // We could even do our own allocator here if that ends up being more efficient.
Greg Clayton2860ba92011-01-23 19:58:49 +00001423 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1424 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1425 if (log)
Greg Claytonb349adc2011-01-24 06:30:45 +00001426 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001427 size,
1428 permissions & ePermissionsReadable ? 'r' : '-',
1429 permissions & ePermissionsWritable ? 'w' : '-',
1430 permissions & ePermissionsExecutable ? 'x' : '-',
1431 (uint64_t)allocated_addr,
1432 m_stop_id);
1433 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001434}
1435
1436Error
1437Process::DeallocateMemory (addr_t ptr)
1438{
Greg Clayton2860ba92011-01-23 19:58:49 +00001439 Error error(DoDeallocateMemory (ptr));
1440
1441 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1442 if (log)
1443 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1444 ptr,
1445 error.AsCString("SUCCESS"),
1446 m_stop_id);
1447 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001448}
1449
1450
1451Error
1452Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1453{
1454 Error error;
1455 error.SetErrorString("watchpoints are not supported");
1456 return error;
1457}
1458
1459Error
1460Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1461{
1462 Error error;
1463 error.SetErrorString("watchpoints are not supported");
1464 return error;
1465}
1466
1467StateType
1468Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1469{
1470 StateType state;
1471 // Now wait for the process to launch and return control to us, and then
1472 // call DidLaunch:
1473 while (1)
1474 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001475 event_sp.reset();
1476 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1477
1478 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001479 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001480
1481 // If state is invalid, then we timed out
1482 if (state == eStateInvalid)
1483 break;
1484
1485 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001486 HandlePrivateEvent (event_sp);
1487 }
1488 return state;
1489}
1490
1491Error
1492Process::Launch
1493(
1494 char const *argv[],
1495 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001496 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001497 const char *stdin_path,
1498 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001499 const char *stderr_path,
1500 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001501)
1502{
1503 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001504 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00001505 m_dyld_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001506 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001507
1508 Module *exe_module = m_target.GetExecutableModule().get();
1509 if (exe_module)
1510 {
1511 char exec_file_path[PATH_MAX];
1512 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1513 if (exe_module->GetFileSpec().Exists())
1514 {
1515 error = WillLaunch (exe_module);
1516 if (error.Success())
1517 {
Greg Claytond8c62532010-10-07 04:19:01 +00001518 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001519 // The args coming in should not contain the application name, the
1520 // lldb_private::Process class will add this in case the executable
1521 // gets resolved to a different file than was given on the command
1522 // line (like when an applicaiton bundle is specified and will
1523 // resolve to the contained exectuable file, or the file given was
1524 // a symlink or other file system link that resolves to a different
1525 // file).
1526
1527 // Get the resolved exectuable path
1528
1529 // Make a new argument vector
1530 std::vector<const char *> exec_path_plus_argv;
1531 // Append the resolved executable path
1532 exec_path_plus_argv.push_back (exec_file_path);
1533
1534 // Push all args if there are any
1535 if (argv)
1536 {
1537 for (int i = 0; argv[i]; ++i)
1538 exec_path_plus_argv.push_back(argv[i]);
1539 }
1540
1541 // Push a NULL to terminate the args.
1542 exec_path_plus_argv.push_back(NULL);
1543
1544 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001545 error = DoLaunch (exe_module,
1546 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1547 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001548 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001549 stdin_path,
1550 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001551 stderr_path,
1552 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001553
1554 if (error.Fail())
1555 {
1556 if (GetID() != LLDB_INVALID_PROCESS_ID)
1557 {
1558 SetID (LLDB_INVALID_PROCESS_ID);
1559 const char *error_string = error.AsCString();
1560 if (error_string == NULL)
1561 error_string = "launch failed";
1562 SetExitStatus (-1, error_string);
1563 }
1564 }
1565 else
1566 {
1567 EventSP event_sp;
1568 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1569
1570 if (state == eStateStopped || state == eStateCrashed)
1571 {
Greg Clayton75c703d2011-02-16 04:46:07 +00001572
Chris Lattner24943d22010-06-08 16:52:24 +00001573 DidLaunch ();
1574
Greg Clayton75c703d2011-02-16 04:46:07 +00001575 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1576 if (m_dyld_ap.get())
1577 m_dyld_ap->DidLaunch();
1578
Chris Lattner24943d22010-06-08 16:52:24 +00001579 // This delays passing the stopped event to listeners till DidLaunch gets
1580 // a chance to complete...
1581 HandlePrivateEvent (event_sp);
1582 StartPrivateStateThread ();
1583 }
1584 else if (state == eStateExited)
1585 {
1586 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1587 // not likely to work, and return an invalid pid.
1588 HandlePrivateEvent (event_sp);
1589 }
1590 }
1591 }
1592 }
1593 else
1594 {
1595 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1596 }
1597 }
1598 return error;
1599}
1600
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001601Process::NextEventAction::EventActionResult
1602Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001603{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001604 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1605 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00001606 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001607 case eStateRunning:
1608 return eEventActionRetry;
1609
1610 case eStateStopped:
1611 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00001612 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001613 // During attach, prior to sending the eStateStopped event,
1614 // lldb_private::Process subclasses must set the process must set
1615 // the new process ID.
1616 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00001617 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001618 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00001619 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001620
1621
1622 break;
1623 default:
1624 case eStateExited:
1625 case eStateInvalid:
1626 m_exit_string.assign ("No valid Process");
1627 return eEventActionExit;
1628 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001629 }
1630}
Chris Lattner24943d22010-06-08 16:52:24 +00001631
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001632Process::NextEventAction::EventActionResult
1633Process::AttachCompletionHandler::HandleBeingInterrupted()
1634{
1635 return eEventActionSuccess;
1636}
1637
1638const char *
1639Process::AttachCompletionHandler::GetExitString ()
1640{
1641 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00001642}
1643
1644Error
1645Process::Attach (lldb::pid_t attach_pid)
1646{
1647
Chris Lattner24943d22010-06-08 16:52:24 +00001648 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001649 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001650
Jim Ingham7508e732010-08-09 23:31:02 +00001651 // Find the process and its architecture. Make sure it matches the architecture
1652 // of the current Target, and if not adjust it.
1653
1654 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1655 if (attach_spec != GetTarget().GetArchitecture())
1656 {
1657 // Set the architecture on the target.
1658 GetTarget().SetArchitecture(attach_spec);
1659 }
1660
Greg Clayton75c703d2011-02-16 04:46:07 +00001661 m_dyld_ap.reset();
1662
Greg Clayton54e7afa2010-07-09 20:39:50 +00001663 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001664 if (error.Success())
1665 {
Greg Claytond8c62532010-10-07 04:19:01 +00001666 SetPublicState (eStateAttaching);
1667
Greg Clayton54e7afa2010-07-09 20:39:50 +00001668 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001669 if (error.Success())
1670 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001671 SetNextEventAction(new Process::AttachCompletionHandler(this));
1672 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001673 }
1674 else
1675 {
1676 if (GetID() != LLDB_INVALID_PROCESS_ID)
1677 {
1678 SetID (LLDB_INVALID_PROCESS_ID);
1679 const char *error_string = error.AsCString();
1680 if (error_string == NULL)
1681 error_string = "attach failed";
1682
1683 SetExitStatus(-1, error_string);
1684 }
1685 }
1686 }
1687 return error;
1688}
1689
1690Error
1691Process::Attach (const char *process_name, bool wait_for_launch)
1692{
Chris Lattner24943d22010-06-08 16:52:24 +00001693 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001694 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001695
1696 // Find the process and its architecture. Make sure it matches the architecture
1697 // of the current Target, and if not adjust it.
1698
Jim Inghamea294182010-08-17 21:54:19 +00001699 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001700 {
Jim Inghamea294182010-08-17 21:54:19 +00001701 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Claytonc1d37752010-10-18 01:45:30 +00001702 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Inghamea294182010-08-17 21:54:19 +00001703 {
1704 // Set the architecture on the target.
1705 GetTarget().SetArchitecture(attach_spec);
1706 }
Jim Ingham7508e732010-08-09 23:31:02 +00001707 }
Greg Clayton75c703d2011-02-16 04:46:07 +00001708
1709 m_dyld_ap.reset();
Jim Inghamea294182010-08-17 21:54:19 +00001710
Greg Clayton54e7afa2010-07-09 20:39:50 +00001711 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner24943d22010-06-08 16:52:24 +00001712 if (error.Success())
1713 {
Greg Claytond8c62532010-10-07 04:19:01 +00001714 SetPublicState (eStateAttaching);
Greg Clayton54e7afa2010-07-09 20:39:50 +00001715 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner24943d22010-06-08 16:52:24 +00001716 if (error.Fail())
1717 {
1718 if (GetID() != LLDB_INVALID_PROCESS_ID)
1719 {
1720 SetID (LLDB_INVALID_PROCESS_ID);
1721 const char *error_string = error.AsCString();
1722 if (error_string == NULL)
1723 error_string = "attach failed";
1724
1725 SetExitStatus(-1, error_string);
1726 }
1727 }
1728 else
1729 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001730 SetNextEventAction(new Process::AttachCompletionHandler(this));
1731 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001732 }
1733 }
1734 return error;
1735}
1736
Greg Clayton75c703d2011-02-16 04:46:07 +00001737void
1738Process::CompleteAttach ()
1739{
1740 // Let the process subclass figure out at much as it can about the process
1741 // before we go looking for a dynamic loader plug-in.
1742 DidAttach();
1743
1744 // We have complete the attach, now it is time to find the dynamic loader
1745 // plug-in
1746 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, false));
1747 if (m_dyld_ap.get())
1748 m_dyld_ap->DidAttach();
1749
1750 // Figure out which one is the executable, and set that in our target:
1751 ModuleList &modules = m_target.GetImages();
1752
1753 size_t num_modules = modules.GetSize();
1754 for (int i = 0; i < num_modules; i++)
1755 {
1756 ModuleSP module_sp (modules.GetModuleAtIndex(i));
1757 if (module_sp->IsExecutable())
1758 {
1759 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
1760 if (target_exe_module_sp != module_sp)
1761 m_target.SetExecutableModule (module_sp, false);
1762 break;
1763 }
1764 }
1765}
1766
Chris Lattner24943d22010-06-08 16:52:24 +00001767Error
Greg Claytone71e2582011-02-04 01:58:07 +00001768Process::ConnectRemote (const char *remote_url)
1769{
Greg Claytone71e2582011-02-04 01:58:07 +00001770 m_abi_sp.reset();
1771 m_process_input_reader.reset();
1772
1773 // Find the process and its architecture. Make sure it matches the architecture
1774 // of the current Target, and if not adjust it.
1775
1776 Error error (DoConnectRemote (remote_url));
1777 if (error.Success())
1778 {
1779 SetNextEventAction(new Process::AttachCompletionHandler(this));
1780 StartPrivateStateThread();
1781// TimeValue timeout;
1782// timeout = TimeValue::Now();
1783// timeout.OffsetWithMicroSeconds(000);
1784// EventSP event_sp;
1785// StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1786//
1787// if (state == eStateStopped || state == eStateCrashed)
1788// {
1789// DidLaunch ();
1790//
1791// // This delays passing the stopped event to listeners till DidLaunch gets
1792// // a chance to complete...
1793// HandlePrivateEvent (event_sp);
1794// StartPrivateStateThread ();
1795// }
1796// else if (state == eStateExited)
1797// {
1798// // We exited while trying to launch somehow. Don't call DidLaunch as that's
1799// // not likely to work, and return an invalid pid.
1800// HandlePrivateEvent (event_sp);
1801// }
1802//
1803// StartPrivateStateThread();
1804 }
1805 return error;
1806}
1807
1808
1809Error
Chris Lattner24943d22010-06-08 16:52:24 +00001810Process::Resume ()
1811{
Greg Claytone005f2c2010-11-06 01:53:30 +00001812 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001813 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00001814 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1815 m_stop_id,
1816 StateAsCString(m_public_state.GetValue()),
1817 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00001818
1819 Error error (WillResume());
1820 // Tell the process it is about to resume before the thread list
1821 if (error.Success())
1822 {
Johnny Chen9c11d472010-12-02 20:53:05 +00001823 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00001824 // can let all of our threads know that they are about to be
1825 // resumed. Threads will each be called with
1826 // Thread::WillResume(StateType) where StateType contains the state
1827 // that they are supposed to have when the process is resumed
1828 // (suspended/running/stepping). Threads should also check
1829 // their resume signal in lldb::Thread::GetResumeSignal()
1830 // to see if they are suppoed to start back up with a signal.
1831 if (m_thread_list.WillResume())
1832 {
1833 error = DoResume();
1834 if (error.Success())
1835 {
1836 DidResume();
1837 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00001838 if (log)
1839 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00001840 }
1841 }
1842 else
1843 {
Jim Inghamac959662011-01-24 06:34:17 +00001844 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00001845 }
1846 }
Jim Inghamac959662011-01-24 06:34:17 +00001847 else if (log)
1848 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00001849 return error;
1850}
1851
1852Error
1853Process::Halt ()
1854{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001855 // Pause our private state thread so we can ensure no one else eats
1856 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00001857 Listener halt_listener ("lldb.process.halt_listener");
1858 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00001859
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001860 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001861 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001862
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001863 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001864 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001865
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001866 bool caused_stop = false;
1867
1868 // Ask the process subclass to actually halt our process
1869 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00001870 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00001871 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001872 if (m_public_state.GetValue() == eStateAttaching)
1873 {
1874 SetExitStatus(SIGKILL, "Cancelled async attach.");
1875 Destroy ();
1876 }
1877 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00001878 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001879 // If "caused_stop" is true, then DoHalt stopped the process. If
1880 // "caused_stop" is false, the process was already stopped.
1881 // If the DoHalt caused the process to stop, then we want to catch
1882 // this event and set the interrupted bool to true before we pass
1883 // this along so clients know that the process was interrupted by
1884 // a halt command.
1885 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00001886 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00001887 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001888 TimeValue timeout_time;
1889 timeout_time = TimeValue::Now();
1890 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001891 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1892 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001893
Jim Inghamf9f40c22011-02-08 05:20:59 +00001894 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00001895 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001896 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00001897 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00001898 }
1899 else
1900 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001901 if (StateIsStoppedState (state))
1902 {
1903 // We caused the process to interrupt itself, so mark this
1904 // as such in the stop event so clients can tell an interrupted
1905 // process from a natural stop
1906 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1907 }
1908 else
1909 {
1910 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1911 if (log)
1912 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1913 error.SetErrorString ("Did not get stopped event after halt.");
1914 }
Greg Clayton20d338f2010-11-18 05:57:03 +00001915 }
1916 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001917 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00001918 }
1919 }
Chris Lattner24943d22010-06-08 16:52:24 +00001920 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001921 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00001922 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001923
1924 // Post any event we might have consumed. If all goes well, we will have
1925 // stopped the process, intercepted the event and set the interrupted
1926 // bool in the event. Post it to the private event queue and that will end up
1927 // correctly setting the state.
1928 if (event_sp)
1929 m_private_state_broadcaster.BroadcastEvent(event_sp);
1930
Chris Lattner24943d22010-06-08 16:52:24 +00001931 return error;
1932}
1933
1934Error
1935Process::Detach ()
1936{
1937 Error error (WillDetach());
1938
1939 if (error.Success())
1940 {
1941 DisableAllBreakpointSites();
1942 error = DoDetach();
1943 if (error.Success())
1944 {
1945 DidDetach();
1946 StopPrivateStateThread();
1947 }
1948 }
1949 return error;
1950}
1951
1952Error
1953Process::Destroy ()
1954{
1955 Error error (WillDestroy());
1956 if (error.Success())
1957 {
1958 DisableAllBreakpointSites();
1959 error = DoDestroy();
1960 if (error.Success())
1961 {
1962 DidDestroy();
1963 StopPrivateStateThread();
1964 }
Caroline Tice861efb32010-11-16 05:07:41 +00001965 m_stdio_communication.StopReadThread();
1966 m_stdio_communication.Disconnect();
1967 if (m_process_input_reader && m_process_input_reader->IsActive())
1968 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1969 if (m_process_input_reader)
1970 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001971 }
1972 return error;
1973}
1974
1975Error
1976Process::Signal (int signal)
1977{
1978 Error error (WillSignal());
1979 if (error.Success())
1980 {
1981 error = DoSignal(signal);
1982 if (error.Success())
1983 DidSignal();
1984 }
1985 return error;
1986}
1987
Greg Clayton395fc332011-02-15 21:59:32 +00001988lldb::ByteOrder
1989Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00001990{
Greg Clayton395fc332011-02-15 21:59:32 +00001991 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00001992}
1993
1994uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00001995Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00001996{
Greg Clayton395fc332011-02-15 21:59:32 +00001997 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00001998}
1999
Greg Clayton395fc332011-02-15 21:59:32 +00002000
Chris Lattner24943d22010-06-08 16:52:24 +00002001bool
2002Process::ShouldBroadcastEvent (Event *event_ptr)
2003{
2004 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2005 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002006 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002007
2008 switch (state)
2009 {
Greg Claytone71e2582011-02-04 01:58:07 +00002010 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002011 case eStateAttaching:
2012 case eStateLaunching:
2013 case eStateDetached:
2014 case eStateExited:
2015 case eStateUnloaded:
2016 // These events indicate changes in the state of the debugging session, always report them.
2017 return_value = true;
2018 break;
2019 case eStateInvalid:
2020 // We stopped for no apparent reason, don't report it.
2021 return_value = false;
2022 break;
2023 case eStateRunning:
2024 case eStateStepping:
2025 // If we've started the target running, we handle the cases where we
2026 // are already running and where there is a transition from stopped to
2027 // running differently.
2028 // running -> running: Automatically suppress extra running events
2029 // stopped -> running: Report except when there is one or more no votes
2030 // and no yes votes.
2031 SynchronouslyNotifyStateChanged (state);
2032 switch (m_public_state.GetValue())
2033 {
2034 case eStateRunning:
2035 case eStateStepping:
2036 // We always suppress multiple runnings with no PUBLIC stop in between.
2037 return_value = false;
2038 break;
2039 default:
2040 // TODO: make this work correctly. For now always report
2041 // run if we aren't running so we don't miss any runnning
2042 // events. If I run the lldb/test/thread/a.out file and
2043 // break at main.cpp:58, run and hit the breakpoints on
2044 // multiple threads, then somehow during the stepping over
2045 // of all breakpoints no run gets reported.
2046 return_value = true;
2047
2048 // This is a transition from stop to run.
2049 switch (m_thread_list.ShouldReportRun (event_ptr))
2050 {
2051 case eVoteYes:
2052 case eVoteNoOpinion:
2053 return_value = true;
2054 break;
2055 case eVoteNo:
2056 return_value = false;
2057 break;
2058 }
2059 break;
2060 }
2061 break;
2062 case eStateStopped:
2063 case eStateCrashed:
2064 case eStateSuspended:
2065 {
2066 // We've stopped. First see if we're going to restart the target.
2067 // If we are going to stop, then we always broadcast the event.
2068 // 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 +00002069 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002070 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002071 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002072 if (log)
2073 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002074 return true;
2075 }
2076 else
2077 {
Chris Lattner24943d22010-06-08 16:52:24 +00002078 RefreshStateAfterStop ();
2079
2080 if (m_thread_list.ShouldStop (event_ptr) == false)
2081 {
2082 switch (m_thread_list.ShouldReportStop (event_ptr))
2083 {
2084 case eVoteYes:
2085 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002086 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002087 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002088 case eVoteNo:
2089 return_value = false;
2090 break;
2091 }
2092
2093 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002094 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002095 Resume ();
2096 }
2097 else
2098 {
2099 return_value = true;
2100 SynchronouslyNotifyStateChanged (state);
2101 }
2102 }
2103 }
2104 }
2105
2106 if (log)
2107 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2108 return return_value;
2109}
2110
Chris Lattner24943d22010-06-08 16:52:24 +00002111
2112bool
2113Process::StartPrivateStateThread ()
2114{
Greg Claytone005f2c2010-11-06 01:53:30 +00002115 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002116
2117 if (log)
2118 log->Printf ("Process::%s ( )", __FUNCTION__);
2119
2120 // Create a thread that watches our internal state and controls which
2121 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002122 char thread_name[1024];
2123 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2124 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002125 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002126}
2127
2128void
2129Process::PausePrivateStateThread ()
2130{
2131 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2132}
2133
2134void
2135Process::ResumePrivateStateThread ()
2136{
2137 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2138}
2139
2140void
2141Process::StopPrivateStateThread ()
2142{
2143 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2144}
2145
2146void
2147Process::ControlPrivateStateThread (uint32_t signal)
2148{
Greg Claytone005f2c2010-11-06 01:53:30 +00002149 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002150
2151 assert (signal == eBroadcastInternalStateControlStop ||
2152 signal == eBroadcastInternalStateControlPause ||
2153 signal == eBroadcastInternalStateControlResume);
2154
2155 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002156 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002157
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002158 // Signal the private state thread. First we should copy this is case the
2159 // thread starts exiting since the private state thread will NULL this out
2160 // when it exits
2161 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002162 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002163 {
2164 TimeValue timeout_time;
2165 bool timed_out;
2166
2167 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2168
2169 timeout_time = TimeValue::Now();
2170 timeout_time.OffsetWithSeconds(2);
2171 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2172 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2173
2174 if (signal == eBroadcastInternalStateControlStop)
2175 {
2176 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002177 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002178
2179 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002180 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002181 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002182 }
2183 }
2184}
2185
2186void
2187Process::HandlePrivateEvent (EventSP &event_sp)
2188{
Greg Claytone005f2c2010-11-06 01:53:30 +00002189 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002190
Greg Clayton68ca8232011-01-25 02:58:48 +00002191 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002192
2193 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002194 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002195 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002196 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002197 switch (action_result)
2198 {
2199 case NextEventAction::eEventActionSuccess:
2200 SetNextEventAction(NULL);
2201 break;
2202 case NextEventAction::eEventActionRetry:
2203 break;
2204 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002205 // Handle Exiting Here. If we already got an exited event,
2206 // we should just propagate it. Otherwise, swallow this event,
2207 // and set our state to exit so the next event will kill us.
2208 if (new_state != eStateExited)
2209 {
2210 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002211 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002212 SetNextEventAction(NULL);
2213 return;
2214 }
2215 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002216 break;
2217 }
2218 }
2219
Chris Lattner24943d22010-06-08 16:52:24 +00002220 // See if we should broadcast this state to external clients?
2221 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002222
2223 if (should_broadcast)
2224 {
2225 if (log)
2226 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002227 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2228 __FUNCTION__,
2229 GetID(),
2230 StateAsCString(new_state),
2231 StateAsCString (GetState ()),
2232 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002233 }
Greg Clayton68ca8232011-01-25 02:58:48 +00002234 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002235 PushProcessInputReader ();
2236 else
2237 PopProcessInputReader ();
Chris Lattner24943d22010-06-08 16:52:24 +00002238 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2239 BroadcastEvent (event_sp);
2240 }
2241 else
2242 {
2243 if (log)
2244 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002245 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2246 __FUNCTION__,
2247 GetID(),
2248 StateAsCString(new_state),
2249 StateAsCString (GetState ()),
2250 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002251 }
2252 }
2253}
2254
2255void *
2256Process::PrivateStateThread (void *arg)
2257{
2258 Process *proc = static_cast<Process*> (arg);
2259 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002260 return result;
2261}
2262
2263void *
2264Process::RunPrivateStateThread ()
2265{
2266 bool control_only = false;
2267 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2268
Greg Claytone005f2c2010-11-06 01:53:30 +00002269 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002270 if (log)
2271 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2272
2273 bool exit_now = false;
2274 while (!exit_now)
2275 {
2276 EventSP event_sp;
2277 WaitForEventsPrivate (NULL, event_sp, control_only);
2278 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2279 {
2280 switch (event_sp->GetType())
2281 {
2282 case eBroadcastInternalStateControlStop:
2283 exit_now = true;
2284 continue; // Go to next loop iteration so we exit without
2285 break; // doing any internal state managment below
2286
2287 case eBroadcastInternalStateControlPause:
2288 control_only = true;
2289 break;
2290
2291 case eBroadcastInternalStateControlResume:
2292 control_only = false;
2293 break;
2294 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002295
Jim Ingham3ae449a2010-11-17 02:32:00 +00002296 if (log)
2297 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2298
Chris Lattner24943d22010-06-08 16:52:24 +00002299 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002300 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002301 }
2302
2303
2304 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2305
2306 if (internal_state != eStateInvalid)
2307 {
2308 HandlePrivateEvent (event_sp);
2309 }
2310
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002311 if (internal_state == eStateInvalid ||
2312 internal_state == eStateExited ||
2313 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002314 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002315 if (log)
2316 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2317
Chris Lattner24943d22010-06-08 16:52:24 +00002318 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002319 }
Chris Lattner24943d22010-06-08 16:52:24 +00002320 }
2321
Caroline Tice926060e2010-10-29 21:48:37 +00002322 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002323 if (log)
2324 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2325
Greg Claytona4881d02011-01-22 07:12:45 +00002326 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2327 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002328 return NULL;
2329}
2330
Chris Lattner24943d22010-06-08 16:52:24 +00002331//------------------------------------------------------------------
2332// Process Event Data
2333//------------------------------------------------------------------
2334
2335Process::ProcessEventData::ProcessEventData () :
2336 EventData (),
2337 m_process_sp (),
2338 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002339 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002340 m_update_state (false),
2341 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002342{
2343}
2344
2345Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2346 EventData (),
2347 m_process_sp (process_sp),
2348 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002349 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002350 m_update_state (false),
2351 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002352{
2353}
2354
2355Process::ProcessEventData::~ProcessEventData()
2356{
2357}
2358
2359const ConstString &
2360Process::ProcessEventData::GetFlavorString ()
2361{
2362 static ConstString g_flavor ("Process::ProcessEventData");
2363 return g_flavor;
2364}
2365
2366const ConstString &
2367Process::ProcessEventData::GetFlavor () const
2368{
2369 return ProcessEventData::GetFlavorString ();
2370}
2371
Chris Lattner24943d22010-06-08 16:52:24 +00002372void
2373Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2374{
2375 // This function gets called twice for each event, once when the event gets pulled
2376 // off of the private process event queue, and once when it gets pulled off of
2377 // the public event queue. m_update_state is used to distinguish these
2378 // two cases; it is false when we're just pulling it off for private handling,
2379 // and we don't want to do the breakpoint command handling then.
2380
2381 if (!m_update_state)
2382 return;
2383
2384 m_process_sp->SetPublicState (m_state);
2385
2386 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2387 if (m_state == eStateStopped && ! m_restarted)
2388 {
2389 int num_threads = m_process_sp->GetThreadList().GetSize();
2390 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002391
Chris Lattner24943d22010-06-08 16:52:24 +00002392 for (idx = 0; idx < num_threads; ++idx)
2393 {
2394 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2395
Jim Ingham6297a3a2010-10-20 00:39:53 +00002396 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2397 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002398 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002399 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002400 }
2401 }
Greg Clayton643ee732010-08-04 01:40:35 +00002402
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002403 // The stop action might restart the target. If it does, then we want to mark that in the
2404 // event so that whoever is receiving it will know to wait for the running event and reflect
2405 // that state appropriately.
2406
Chris Lattner24943d22010-06-08 16:52:24 +00002407 if (m_process_sp->GetPrivateState() == eStateRunning)
2408 SetRestarted(true);
2409 }
2410}
2411
2412void
2413Process::ProcessEventData::Dump (Stream *s) const
2414{
2415 if (m_process_sp)
2416 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2417
2418 s->Printf("state = %s", StateAsCString(GetState()));;
2419}
2420
2421const Process::ProcessEventData *
2422Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2423{
2424 if (event_ptr)
2425 {
2426 const EventData *event_data = event_ptr->GetData();
2427 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2428 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2429 }
2430 return NULL;
2431}
2432
2433ProcessSP
2434Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2435{
2436 ProcessSP process_sp;
2437 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2438 if (data)
2439 process_sp = data->GetProcessSP();
2440 return process_sp;
2441}
2442
2443StateType
2444Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2445{
2446 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2447 if (data == NULL)
2448 return eStateInvalid;
2449 else
2450 return data->GetState();
2451}
2452
2453bool
2454Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2455{
2456 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2457 if (data == NULL)
2458 return false;
2459 else
2460 return data->GetRestarted();
2461}
2462
2463void
2464Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2465{
2466 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2467 if (data != NULL)
2468 data->SetRestarted(new_value);
2469}
2470
2471bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002472Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2473{
2474 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2475 if (data == NULL)
2476 return false;
2477 else
2478 return data->GetInterrupted ();
2479}
2480
2481void
2482Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2483{
2484 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2485 if (data != NULL)
2486 data->SetInterrupted(new_value);
2487}
2488
2489bool
Chris Lattner24943d22010-06-08 16:52:24 +00002490Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2491{
2492 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2493 if (data)
2494 {
2495 data->SetUpdateStateOnRemoval();
2496 return true;
2497 }
2498 return false;
2499}
2500
Chris Lattner24943d22010-06-08 16:52:24 +00002501void
Greg Claytona830adb2010-10-04 01:05:56 +00002502Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002503{
2504 exe_ctx.target = &m_target;
2505 exe_ctx.process = this;
2506 exe_ctx.thread = NULL;
2507 exe_ctx.frame = NULL;
2508}
2509
2510lldb::ProcessSP
2511Process::GetSP ()
2512{
2513 return GetTarget().GetProcessSP();
2514}
2515
Jim Ingham7508e732010-08-09 23:31:02 +00002516uint32_t
2517Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2518{
2519 return 0;
2520}
2521
2522ArchSpec
2523Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2524{
2525 return Host::GetArchSpecForExistingProcess (pid);
2526}
2527
2528ArchSpec
2529Process::GetArchSpecForExistingProcess (const char *process_name)
2530{
2531 return Host::GetArchSpecForExistingProcess (process_name);
2532}
2533
Caroline Tice861efb32010-11-16 05:07:41 +00002534void
2535Process::AppendSTDOUT (const char * s, size_t len)
2536{
Greg Clayton20d338f2010-11-18 05:57:03 +00002537 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002538 m_stdout_data.append (s, len);
2539
Greg Claytonb3781332010-12-05 19:16:56 +00002540 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002541}
2542
2543void
2544Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2545{
2546 Process *process = (Process *) baton;
2547 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2548}
2549
2550size_t
2551Process::ProcessInputReaderCallback (void *baton,
2552 InputReader &reader,
2553 lldb::InputReaderAction notification,
2554 const char *bytes,
2555 size_t bytes_len)
2556{
2557 Process *process = (Process *) baton;
2558
2559 switch (notification)
2560 {
2561 case eInputReaderActivate:
2562 break;
2563
2564 case eInputReaderDeactivate:
2565 break;
2566
2567 case eInputReaderReactivate:
2568 break;
2569
2570 case eInputReaderGotToken:
2571 {
2572 Error error;
2573 process->PutSTDIN (bytes, bytes_len, error);
2574 }
2575 break;
2576
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002577 case eInputReaderInterrupt:
2578 process->Halt ();
2579 break;
2580
2581 case eInputReaderEndOfFile:
2582 process->AppendSTDOUT ("^D", 2);
2583 break;
2584
Caroline Tice861efb32010-11-16 05:07:41 +00002585 case eInputReaderDone:
2586 break;
2587
2588 }
2589
2590 return bytes_len;
2591}
2592
2593void
2594Process::ResetProcessInputReader ()
2595{
2596 m_process_input_reader.reset();
2597}
2598
2599void
2600Process::SetUpProcessInputReader (int file_descriptor)
2601{
2602 // First set up the Read Thread for reading/handling process I/O
2603
2604 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2605
2606 if (conn_ap.get())
2607 {
2608 m_stdio_communication.SetConnection (conn_ap.release());
2609 if (m_stdio_communication.IsConnected())
2610 {
2611 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2612 m_stdio_communication.StartReadThread();
2613
2614 // Now read thread is set up, set up input reader.
2615
2616 if (!m_process_input_reader.get())
2617 {
2618 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2619 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2620 this,
2621 eInputReaderGranularityByte,
2622 NULL,
2623 NULL,
2624 false));
2625
2626 if (err.Fail())
2627 m_process_input_reader.reset();
2628 }
2629 }
2630 }
2631}
2632
2633void
2634Process::PushProcessInputReader ()
2635{
2636 if (m_process_input_reader && !m_process_input_reader->IsActive())
2637 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2638}
2639
2640void
2641Process::PopProcessInputReader ()
2642{
2643 if (m_process_input_reader && m_process_input_reader->IsActive())
2644 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2645}
2646
Greg Clayton990de7b2010-11-18 23:32:35 +00002647
2648void
2649Process::Initialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002650{
Greg Clayton990de7b2010-11-18 23:32:35 +00002651 UserSettingsControllerSP &usc = GetSettingsController();
2652 usc.reset (new SettingsController);
2653 UserSettingsController::InitializeSettingsController (usc,
2654 SettingsController::global_settings_table,
2655 SettingsController::instance_settings_table);
2656}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002657
Greg Clayton990de7b2010-11-18 23:32:35 +00002658void
2659Process::Terminate ()
2660{
2661 UserSettingsControllerSP &usc = GetSettingsController();
2662 UserSettingsController::FinalizeSettingsController (usc);
2663 usc.reset();
2664}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002665
Greg Clayton990de7b2010-11-18 23:32:35 +00002666UserSettingsControllerSP &
2667Process::GetSettingsController ()
2668{
2669 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002670 return g_settings_controller;
2671}
2672
Caroline Tice1ebef442010-09-27 00:30:10 +00002673void
2674Process::UpdateInstanceName ()
2675{
2676 ModuleSP module_sp = GetTarget().GetExecutableModule();
2677 if (module_sp)
2678 {
2679 StreamString sstr;
2680 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2681
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002682 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002683 sstr.GetData());
2684 }
2685}
2686
Greg Clayton427f2902010-12-14 02:59:59 +00002687ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002688Process::RunThreadPlan (ExecutionContext &exe_ctx,
2689 lldb::ThreadPlanSP &thread_plan_sp,
2690 bool stop_others,
2691 bool try_all_threads,
2692 bool discard_on_error,
2693 uint32_t single_thread_timeout_usec,
2694 Stream &errors)
2695{
2696 ExecutionResults return_value = eExecutionSetupError;
2697
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002698 if (thread_plan_sp.get() == NULL)
2699 {
2700 errors.Printf("RunThreadPlan called with empty thread plan.");
2701 return lldb::eExecutionSetupError;
2702 }
2703
Jim Inghamac959662011-01-24 06:34:17 +00002704 if (m_private_state.GetValue() != eStateStopped)
2705 {
2706 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00002707 return lldb::eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00002708 }
2709
Jim Ingham360f53f2010-11-30 02:22:11 +00002710 // Save this value for restoration of the execution context after we run
2711 uint32_t tid = exe_ctx.thread->GetIndexID();
2712
2713 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2714 // so we should arrange to reset them as well.
2715
2716 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2717 lldb::StackFrameSP selected_frame_sp;
2718
2719 uint32_t selected_tid;
2720 if (selected_thread_sp != NULL)
2721 {
2722 selected_tid = selected_thread_sp->GetIndexID();
2723 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2724 }
2725 else
2726 {
2727 selected_tid = LLDB_INVALID_THREAD_ID;
2728 }
2729
2730 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2731
Jim Ingham6ae318c2011-01-23 21:14:08 +00002732 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00002733
2734 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2735 // restored on exit to the function.
2736
2737 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00002738
Jim Ingham6ae318c2011-01-23 21:14:08 +00002739 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002740 if (log)
2741 {
2742 StreamString s;
2743 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002744 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2745 exe_ctx.thread->GetIndexID(),
2746 exe_ctx.thread->GetID(),
2747 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002748 }
2749
Jim Inghamf9f40c22011-02-08 05:20:59 +00002750 bool got_event;
2751 lldb::EventSP event_sp;
2752 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00002753
2754 TimeValue* timeout_ptr = NULL;
2755 TimeValue real_timeout;
2756
Jim Inghamf9f40c22011-02-08 05:20:59 +00002757 bool first_timeout = true;
2758 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00002759
Jim Ingham360f53f2010-11-30 02:22:11 +00002760 while (1)
2761 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002762 // We usually want to resume the process if we get to the top of the loop.
2763 // The only exception is if we get two running events with no intervening
2764 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00002765
Jim Inghamf9f40c22011-02-08 05:20:59 +00002766 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00002767 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002768 // Do the initial resume and wait for the running event before going further.
2769
2770 Error resume_error = exe_ctx.process->Resume ();
2771 if (!resume_error.Success())
2772 {
2773 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2774 return_value = lldb::eExecutionSetupError;
2775 break;
2776 }
2777
2778 real_timeout = TimeValue::Now();
2779 real_timeout.OffsetWithMicroSeconds(500000);
2780 timeout_ptr = &real_timeout;
2781
2782 got_event = listener.WaitForEvent(NULL, event_sp);
2783 if (!got_event)
2784 {
2785 if (log)
2786 log->Printf("Didn't get any event after initial resume, exiting.");
2787
2788 errors.Printf("Didn't get any event after initial resume, exiting.");
2789 return_value = lldb::eExecutionSetupError;
2790 break;
2791 }
2792
2793 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2794 if (stop_state != eStateRunning)
2795 {
2796 if (log)
2797 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2798
2799 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2800 return_value = lldb::eExecutionSetupError;
2801 break;
2802 }
2803
2804 if (log)
2805 log->Printf ("Resuming succeeded.");
2806 // We need to call the function synchronously, so spin waiting for it to return.
2807 // If we get interrupted while executing, we're going to lose our context, and
2808 // won't be able to gather the result at this point.
2809 // We set the timeout AFTER the resume, since the resume takes some time and we
2810 // don't want to charge that to the timeout.
2811
2812 if (single_thread_timeout_usec != 0)
2813 {
2814 real_timeout = TimeValue::Now();
2815 if (first_timeout)
2816 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2817 else
2818 real_timeout.OffsetWithSeconds(10);
2819
2820 timeout_ptr = &real_timeout;
2821 }
2822 }
2823 else
2824 {
2825 if (log)
2826 log->Printf ("Handled an extra running event.");
2827 do_resume = true;
2828 }
2829
2830 // Now wait for the process to stop again:
2831 stop_state = lldb::eStateInvalid;
2832 event_sp.reset();
2833 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2834
2835 if (got_event)
2836 {
2837 if (event_sp.get())
2838 {
2839 bool keep_going = false;
2840 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2841 if (log)
2842 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2843
2844 switch (stop_state)
2845 {
2846 case lldb::eStateStopped:
2847 // Yay, we're done.
2848 if (log)
2849 log->Printf ("Execution completed successfully.");
2850 return_value = lldb::eExecutionCompleted;
2851 break;
2852 case lldb::eStateCrashed:
2853 if (log)
2854 log->Printf ("Execution crashed.");
2855 return_value = lldb::eExecutionInterrupted;
2856 break;
2857 case lldb::eStateRunning:
2858 do_resume = false;
2859 keep_going = true;
2860 break;
2861 default:
2862 if (log)
2863 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
2864 return_value = lldb::eExecutionInterrupted;
2865 break;
2866 }
2867 if (keep_going)
2868 continue;
2869 else
2870 break;
2871 }
2872 else
2873 {
2874 if (log)
2875 log->Printf ("got_event was true, but the event pointer was null. How odd...");
2876 return_value = lldb::eExecutionInterrupted;
2877 break;
2878 }
2879 }
2880 else
2881 {
2882 // If we didn't get an event that means we've timed out...
2883 // We will interrupt the process here. Depending on what we were asked to do we will
2884 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00002885 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002886
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002887 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00002888 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002889 {
2890 if (first_timeout)
2891 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2892 "trying with all threads enabled.",
2893 single_thread_timeout_usec);
2894 else
2895 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2896 "and timeout: %d timed out.",
2897 single_thread_timeout_usec);
2898 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002899 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00002900 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2901 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00002902 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002903 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002904
Jim Inghamc556b462011-01-22 01:30:53 +00002905 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00002906 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00002907 {
Jim Ingham360f53f2010-11-30 02:22:11 +00002908 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00002909 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00002910
Jim Inghamf9f40c22011-02-08 05:20:59 +00002911 // If halt succeeds, it always produces a stopped event. Wait for that:
2912
2913 real_timeout = TimeValue::Now();
2914 real_timeout.OffsetWithMicroSeconds(500000);
2915
2916 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00002917
2918 if (got_event)
2919 {
2920 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2921 if (log)
2922 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002923 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00002924 if (stop_state == lldb::eStateStopped
2925 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00002926 log->Printf (" Event was the Halt interruption event.");
2927 }
2928
Jim Inghamf9f40c22011-02-08 05:20:59 +00002929 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00002930 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002931 // Between the time we initiated the Halt and the time we delivered it, the process could have
2932 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00002933
Jim Inghamf9f40c22011-02-08 05:20:59 +00002934 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2935 {
2936 if (log)
2937 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
2938 "Exiting wait loop.");
2939 return_value = lldb::eExecutionCompleted;
2940 break;
2941 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002942
Jim Inghamf9f40c22011-02-08 05:20:59 +00002943 if (!try_all_threads)
2944 {
2945 if (log)
2946 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
2947 return_value = lldb::eExecutionInterrupted;
2948 break;
2949 }
2950
2951 if (first_timeout)
2952 {
2953 // Set all the other threads to run, and return to the top of the loop, which will continue;
2954 first_timeout = false;
2955 thread_plan_sp->SetStopOthers (false);
2956 if (log)
2957 log->Printf ("Process::RunThreadPlan(): About to resume.");
2958
2959 continue;
2960 }
2961 else
2962 {
2963 // Running all threads failed, so return Interrupted.
2964 if (log)
2965 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
2966 return_value = lldb::eExecutionInterrupted;
2967 break;
2968 }
Jim Ingham360f53f2010-11-30 02:22:11 +00002969 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00002970 }
2971 else
2972 { if (log)
2973 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
2974 "I'm getting out of here passing Interrupted.");
2975 return_value = lldb::eExecutionInterrupted;
2976 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00002977 }
2978 }
Jim Inghamc556b462011-01-22 01:30:53 +00002979 else
2980 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002981 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
2982 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00002983 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002984 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.",
2985 halt_error.AsCString());
2986 real_timeout = TimeValue::Now();
2987 real_timeout.OffsetWithMicroSeconds(500000);
2988 timeout_ptr = &real_timeout;
2989 got_event = listener.WaitForEvent(&real_timeout, event_sp);
2990 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00002991 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002992 // This is not going anywhere, bag out.
2993 if (log)
2994 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
2995 return_value = lldb::eExecutionInterrupted;
2996 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00002997 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00002998 else
2999 {
3000 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3001 if (log)
3002 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3003 if (stop_state == lldb::eStateStopped)
3004 {
3005 // Between the time we initiated the Halt and the time we delivered it, the process could have
3006 // already finished its job. Check that here:
3007
3008 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3009 {
3010 if (log)
3011 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3012 "Exiting wait loop.");
3013 return_value = lldb::eExecutionCompleted;
3014 break;
3015 }
3016
3017 if (first_timeout)
3018 {
3019 // Set all the other threads to run, and return to the top of the loop, which will continue;
3020 first_timeout = false;
3021 thread_plan_sp->SetStopOthers (false);
3022 if (log)
3023 log->Printf ("Process::RunThreadPlan(): About to resume.");
3024
3025 continue;
3026 }
3027 else
3028 {
3029 // Running all threads failed, so return Interrupted.
3030 if (log)
3031 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3032 return_value = lldb::eExecutionInterrupted;
3033 break;
3034 }
3035 }
3036 else
3037 {
3038 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3039 " a stopped event, instead got %s.", StateAsCString(stop_state));
3040 return_value = lldb::eExecutionInterrupted;
3041 break;
3042 }
3043 }
Jim Inghamc556b462011-01-22 01:30:53 +00003044 }
3045
Jim Ingham360f53f2010-11-30 02:22:11 +00003046 }
3047
Jim Inghamf9f40c22011-02-08 05:20:59 +00003048 } // END WAIT LOOP
3049
3050 // Now do some processing on the results of the run:
3051 if (return_value == eExecutionInterrupted)
3052 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003053 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003054 {
3055 StreamString s;
3056 if (event_sp)
3057 event_sp->Dump (&s);
3058 else
3059 {
3060 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3061 }
3062
3063 StreamString ts;
3064
3065 const char *event_explanation;
3066
3067 do
3068 {
3069 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3070
3071 if (!event_data)
3072 {
3073 event_explanation = "<no event data>";
3074 break;
3075 }
3076
3077 Process *process = event_data->GetProcessSP().get();
3078
3079 if (!process)
3080 {
3081 event_explanation = "<no process>";
3082 break;
3083 }
3084
3085 ThreadList &thread_list = process->GetThreadList();
3086
3087 uint32_t num_threads = thread_list.GetSize();
3088 uint32_t thread_index;
3089
3090 ts.Printf("<%u threads> ", num_threads);
3091
3092 for (thread_index = 0;
3093 thread_index < num_threads;
3094 ++thread_index)
3095 {
3096 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3097
3098 if (!thread)
3099 {
3100 ts.Printf("<?> ");
3101 continue;
3102 }
3103
3104 ts.Printf("<0x%4.4x ", thread->GetID());
3105 RegisterContext *register_context = thread->GetRegisterContext().get();
3106
3107 if (register_context)
3108 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3109 else
3110 ts.Printf("[ip unknown] ");
3111
3112 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3113 if (stop_info_sp)
3114 {
3115 const char *stop_desc = stop_info_sp->GetDescription();
3116 if (stop_desc)
3117 ts.PutCString (stop_desc);
3118 }
3119 ts.Printf(">");
3120 }
3121
3122 event_explanation = ts.GetData();
3123 } while (0);
3124
3125 if (log)
3126 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3127
3128 if (discard_on_error && thread_plan_sp)
3129 {
3130 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3131 }
3132 }
3133 }
3134 else if (return_value == eExecutionSetupError)
3135 {
3136 if (log)
3137 log->Printf("Process::RunThreadPlan(): execution set up error.");
3138
3139 if (discard_on_error && thread_plan_sp)
3140 {
3141 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3142 }
3143 }
3144 else
3145 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003146 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3147 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003148 if (log)
3149 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton427f2902010-12-14 02:59:59 +00003150 return_value = lldb::eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003151 }
3152 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3153 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003154 if (log)
3155 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton427f2902010-12-14 02:59:59 +00003156 return_value = lldb::eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003157 }
3158 else
3159 {
3160 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003161 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003162 if (discard_on_error && thread_plan_sp)
3163 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003164 if (log)
3165 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003166 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3167 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003168 }
3169 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003170
Jim Ingham360f53f2010-11-30 02:22:11 +00003171 // Thread we ran the function in may have gone away because we ran the target
3172 // Check that it's still there.
3173 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3174 if (exe_ctx.thread)
3175 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3176
3177 // Also restore the current process'es selected frame & thread, since this function calling may
3178 // be done behind the user's back.
3179
3180 if (selected_tid != LLDB_INVALID_THREAD_ID)
3181 {
3182 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3183 {
3184 // We were able to restore the selected thread, now restore the frame:
3185 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3186 }
3187 }
3188
3189 return return_value;
3190}
3191
3192const char *
3193Process::ExecutionResultAsCString (ExecutionResults result)
3194{
3195 const char *result_name;
3196
3197 switch (result)
3198 {
Greg Clayton427f2902010-12-14 02:59:59 +00003199 case lldb::eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003200 result_name = "eExecutionCompleted";
3201 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003202 case lldb::eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003203 result_name = "eExecutionDiscarded";
3204 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003205 case lldb::eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003206 result_name = "eExecutionInterrupted";
3207 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003208 case lldb::eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003209 result_name = "eExecutionSetupError";
3210 break;
Greg Clayton427f2902010-12-14 02:59:59 +00003211 case lldb::eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003212 result_name = "eExecutionTimedOut";
3213 break;
3214 }
3215 return result_name;
3216}
3217
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003218//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003219// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003220//--------------------------------------------------------------
3221
Greg Claytond0a5a232010-09-19 02:33:57 +00003222Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003223 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003224{
Greg Clayton638351a2010-12-04 00:10:17 +00003225 m_default_settings.reset (new ProcessInstanceSettings (*this,
3226 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00003227 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003228}
3229
Greg Claytond0a5a232010-09-19 02:33:57 +00003230Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003231{
3232}
3233
3234lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00003235Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003236{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003237 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3238 false,
3239 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003240 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3241 return new_settings_sp;
3242}
3243
3244//--------------------------------------------------------------
3245// class ProcessInstanceSettings
3246//--------------------------------------------------------------
3247
Greg Clayton638351a2010-12-04 00:10:17 +00003248ProcessInstanceSettings::ProcessInstanceSettings
3249(
3250 UserSettingsController &owner,
3251 bool live_instance,
3252 const char *name
3253) :
3254 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003255 m_run_args (),
3256 m_env_vars (),
3257 m_input_path (),
3258 m_output_path (),
3259 m_error_path (),
3260 m_plugin (),
Caroline Ticebd666012010-12-03 18:46:09 +00003261 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00003262 m_disable_stdio (false),
3263 m_inherit_host_env (true),
3264 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003265{
Caroline Tice396704b2010-09-09 18:26:37 +00003266 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3267 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3268 // 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 +00003269 // This is true for CreateInstanceName() too.
3270
3271 if (GetInstanceName () == InstanceSettings::InvalidName())
3272 {
3273 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3274 m_owner.RegisterInstanceSettings (this);
3275 }
Caroline Tice396704b2010-09-09 18:26:37 +00003276
3277 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003278 {
3279 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3280 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003281 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003282 }
3283}
3284
3285ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003286 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003287 m_run_args (rhs.m_run_args),
3288 m_env_vars (rhs.m_env_vars),
3289 m_input_path (rhs.m_input_path),
3290 m_output_path (rhs.m_output_path),
3291 m_error_path (rhs.m_error_path),
3292 m_plugin (rhs.m_plugin),
Caroline Ticebd666012010-12-03 18:46:09 +00003293 m_disable_aslr (rhs.m_disable_aslr),
3294 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003295{
3296 if (m_instance_name != InstanceSettings::GetDefaultName())
3297 {
3298 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3299 CopyInstanceSettings (pending_settings,false);
3300 m_owner.RemovePendingSettings (m_instance_name);
3301 }
3302}
3303
3304ProcessInstanceSettings::~ProcessInstanceSettings ()
3305{
3306}
3307
3308ProcessInstanceSettings&
3309ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3310{
3311 if (this != &rhs)
3312 {
3313 m_run_args = rhs.m_run_args;
3314 m_env_vars = rhs.m_env_vars;
3315 m_input_path = rhs.m_input_path;
3316 m_output_path = rhs.m_output_path;
3317 m_error_path = rhs.m_error_path;
3318 m_plugin = rhs.m_plugin;
3319 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003320 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003321 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003322 }
3323
3324 return *this;
3325}
3326
3327
3328void
3329ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3330 const char *index_value,
3331 const char *value,
3332 const ConstString &instance_name,
3333 const SettingEntry &entry,
3334 lldb::VarSetOperationType op,
3335 Error &err,
3336 bool pending)
3337{
3338 if (var_name == RunArgsVarName())
3339 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3340 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003341 {
3342 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003343 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003344 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003345 else if (var_name == InputPathVarName())
3346 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3347 else if (var_name == OutputPathVarName())
3348 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3349 else if (var_name == ErrorPathVarName())
3350 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3351 else if (var_name == PluginVarName())
3352 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003353 else if (var_name == InheritHostEnvVarName())
3354 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003355 else if (var_name == DisableASLRVarName())
3356 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003357 else if (var_name == DisableSTDIOVarName ())
3358 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003359}
3360
3361void
3362ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3363 bool pending)
3364{
3365 if (new_settings.get() == NULL)
3366 return;
3367
3368 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3369
3370 m_run_args = new_process_settings->m_run_args;
3371 m_env_vars = new_process_settings->m_env_vars;
3372 m_input_path = new_process_settings->m_input_path;
3373 m_output_path = new_process_settings->m_output_path;
3374 m_error_path = new_process_settings->m_error_path;
3375 m_plugin = new_process_settings->m_plugin;
3376 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003377 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003378}
3379
Caroline Ticebcb5b452010-09-20 21:37:42 +00003380bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003381ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3382 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003383 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003384 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003385{
3386 if (var_name == RunArgsVarName())
3387 {
3388 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003389 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003390 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3391 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003392 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003393 }
3394 else if (var_name == EnvVarsVarName())
3395 {
Greg Clayton638351a2010-12-04 00:10:17 +00003396 GetHostEnvironmentIfNeeded ();
3397
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003398 if (m_env_vars.size() > 0)
3399 {
3400 std::map<std::string, std::string>::iterator pos;
3401 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3402 {
3403 StreamString value_str;
3404 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3405 value.AppendString (value_str.GetData());
3406 }
3407 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003408 }
3409 else if (var_name == InputPathVarName())
3410 {
3411 value.AppendString (m_input_path.c_str());
3412 }
3413 else if (var_name == OutputPathVarName())
3414 {
3415 value.AppendString (m_output_path.c_str());
3416 }
3417 else if (var_name == ErrorPathVarName())
3418 {
3419 value.AppendString (m_error_path.c_str());
3420 }
3421 else if (var_name == PluginVarName())
3422 {
3423 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3424 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003425 else if (var_name == InheritHostEnvVarName())
3426 {
3427 if (m_inherit_host_env)
3428 value.AppendString ("true");
3429 else
3430 value.AppendString ("false");
3431 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003432 else if (var_name == DisableASLRVarName())
3433 {
3434 if (m_disable_aslr)
3435 value.AppendString ("true");
3436 else
3437 value.AppendString ("false");
3438 }
Caroline Ticebd666012010-12-03 18:46:09 +00003439 else if (var_name == DisableSTDIOVarName())
3440 {
3441 if (m_disable_stdio)
3442 value.AppendString ("true");
3443 else
3444 value.AppendString ("false");
3445 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003446 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003447 {
3448 if (err)
3449 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3450 return false;
3451 }
3452 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003453}
3454
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003455const ConstString
3456ProcessInstanceSettings::CreateInstanceName ()
3457{
3458 static int instance_count = 1;
3459 StreamString sstr;
3460
3461 sstr.Printf ("process_%d", instance_count);
3462 ++instance_count;
3463
3464 const ConstString ret_val (sstr.GetData());
3465 return ret_val;
3466}
3467
3468const ConstString &
3469ProcessInstanceSettings::RunArgsVarName ()
3470{
3471 static ConstString run_args_var_name ("run-args");
3472
3473 return run_args_var_name;
3474}
3475
3476const ConstString &
3477ProcessInstanceSettings::EnvVarsVarName ()
3478{
3479 static ConstString env_vars_var_name ("env-vars");
3480
3481 return env_vars_var_name;
3482}
3483
3484const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003485ProcessInstanceSettings::InheritHostEnvVarName ()
3486{
3487 static ConstString g_name ("inherit-env");
3488
3489 return g_name;
3490}
3491
3492const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003493ProcessInstanceSettings::InputPathVarName ()
3494{
3495 static ConstString input_path_var_name ("input-path");
3496
3497 return input_path_var_name;
3498}
3499
3500const ConstString &
3501ProcessInstanceSettings::OutputPathVarName ()
3502{
Caroline Tice87097232010-09-07 18:35:40 +00003503 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003504
3505 return output_path_var_name;
3506}
3507
3508const ConstString &
3509ProcessInstanceSettings::ErrorPathVarName ()
3510{
Caroline Tice87097232010-09-07 18:35:40 +00003511 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003512
3513 return error_path_var_name;
3514}
3515
3516const ConstString &
3517ProcessInstanceSettings::PluginVarName ()
3518{
3519 static ConstString plugin_var_name ("plugin");
3520
3521 return plugin_var_name;
3522}
3523
3524
3525const ConstString &
3526ProcessInstanceSettings::DisableASLRVarName ()
3527{
3528 static ConstString disable_aslr_var_name ("disable-aslr");
3529
3530 return disable_aslr_var_name;
3531}
3532
Caroline Ticebd666012010-12-03 18:46:09 +00003533const ConstString &
3534ProcessInstanceSettings::DisableSTDIOVarName ()
3535{
3536 static ConstString disable_stdio_var_name ("disable-stdio");
3537
3538 return disable_stdio_var_name;
3539}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003540
3541//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003542// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003543//--------------------------------------------------
3544
3545SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003546Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003547{
3548 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3549 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3550};
3551
3552
3553lldb::OptionEnumValueElement
Greg Claytond0a5a232010-09-19 02:33:57 +00003554Process::SettingsController::g_plugins[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003555{
Caroline Ticef2c330d2010-09-09 18:01:59 +00003556 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3557 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3558 { 0, NULL, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003559};
3560
3561SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003562Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003563{
Greg Clayton638351a2010-12-04 00:10:17 +00003564 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3565 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3566 { "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." },
3567 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003568 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3569 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3570 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3571 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003572 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3573 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3574 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003575};
3576
3577
Jim Ingham7508e732010-08-09 23:31:02 +00003578