blob: cf019e61328552a3fff540be4ebb9af1c83bad47 [file] [log] [blame]
Chris Lattner30fdc8d2010-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 Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham22777012010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000031#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Clayton58be07b2011-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 Lattner30fdc8d2010-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 Claytonc982c762010-07-09 20:39:50 +0000195 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000196 {
Greg Claytonc982c762010-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 Lattner30fdc8d2010-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 Claytoncfd1ace2010-10-31 03:01:06 +0000211 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000212 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213 m_target (target),
Chris Lattner30fdc8d2010-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 Clayton3af9ea52010-11-18 05:57:03 +0000227 m_image_tokens (),
228 m_listener (listener),
229 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000230 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000231 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000232 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000233 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000234 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000235 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000236 m_stdout_data (),
Jim Inghambb3a2832011-01-29 01:49:25 +0000237 m_memory_cache (),
Greg Clayton513c26c2011-01-29 07:10:55 +0000238 m_next_event_action_ap()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239{
Caroline Tice1559a462010-09-27 00:30:10 +0000240 UpdateInstanceName();
241
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000242 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000243 if (log)
244 log->Printf ("%p Process::Process()", this);
245
Greg Claytoncfd1ace2010-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 Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000271 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-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.
282}
283
284void
285Process::RegisterNotificationCallbacks (const Notifications& callbacks)
286{
287 m_notifications.push_back(callbacks);
288 if (callbacks.initialize != NULL)
289 callbacks.initialize (callbacks.baton, this);
290}
291
292bool
293Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
294{
295 std::vector<Notifications>::iterator pos, end = m_notifications.end();
296 for (pos = m_notifications.begin(); pos != end; ++pos)
297 {
298 if (pos->baton == callbacks.baton &&
299 pos->initialize == callbacks.initialize &&
300 pos->process_state_changed == callbacks.process_state_changed)
301 {
302 m_notifications.erase(pos);
303 return true;
304 }
305 }
306 return false;
307}
308
309void
310Process::SynchronouslyNotifyStateChanged (StateType state)
311{
312 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
313 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
314 {
315 if (notification_pos->process_state_changed)
316 notification_pos->process_state_changed (notification_pos->baton, this, state);
317 }
318}
319
320// FIXME: We need to do some work on events before the general Listener sees them.
321// For instance if we are continuing from a breakpoint, we need to ensure that we do
322// the little "insert real insn, step & stop" trick. But we can't do that when the
323// event is delivered by the broadcaster - since that is done on the thread that is
324// waiting for new events, so if we needed more than one event for our handling, we would
325// stall. So instead we do it when we fetch the event off of the queue.
326//
327
328StateType
329Process::GetNextEvent (EventSP &event_sp)
330{
331 StateType state = eStateInvalid;
332
333 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
334 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
335
336 return state;
337}
338
339
340StateType
341Process::WaitForProcessToStop (const TimeValue *timeout)
342{
343 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
344 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
345}
346
347
348StateType
349Process::WaitForState
350(
351 const TimeValue *timeout,
352 const StateType *match_states, const uint32_t num_match_states
353)
354{
355 EventSP event_sp;
356 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000357 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358 while (state != eStateInvalid)
359 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000360 // If we are exited or detached, we won't ever get back to any
361 // other valid state...
362 if (state == eStateDetached || state == eStateExited)
363 return state;
364
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000365 state = WaitForStateChangedEvents (timeout, event_sp);
366
367 for (i=0; i<num_match_states; ++i)
368 {
369 if (match_states[i] == state)
370 return state;
371 }
372 }
373 return state;
374}
375
Jim Ingham30f9b212010-10-11 23:53:14 +0000376bool
377Process::HijackProcessEvents (Listener *listener)
378{
379 if (listener != NULL)
380 {
381 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
382 }
383 else
384 return false;
385}
386
387void
388Process::RestoreProcessEvents ()
389{
390 RestoreBroadcaster();
391}
392
Jim Ingham0f16e732011-02-08 05:20:59 +0000393bool
394Process::HijackPrivateProcessEvents (Listener *listener)
395{
396 if (listener != NULL)
397 {
398 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
399 }
400 else
401 return false;
402}
403
404void
405Process::RestorePrivateProcessEvents ()
406{
407 m_private_state_broadcaster.RestoreBroadcaster();
408}
409
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410StateType
411Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
412{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000413 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414
415 if (log)
416 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
417
418 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000419 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
420 this,
421 eBroadcastBitStateChanged,
422 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
424
425 if (log)
426 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
427 __FUNCTION__,
428 timeout,
429 StateAsCString(state));
430 return state;
431}
432
433Event *
434Process::PeekAtStateChangedEvents ()
435{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000436 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437
438 if (log)
439 log->Printf ("Process::%s...", __FUNCTION__);
440
441 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000442 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
443 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444 if (log)
445 {
446 if (event_ptr)
447 {
448 log->Printf ("Process::%s (event_ptr) => %s",
449 __FUNCTION__,
450 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
451 }
452 else
453 {
454 log->Printf ("Process::%s no events found",
455 __FUNCTION__);
456 }
457 }
458 return event_ptr;
459}
460
461StateType
462Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
463{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000464 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465
466 if (log)
467 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
468
469 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000470 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
471 &m_private_state_broadcaster,
472 eBroadcastBitStateChanged,
473 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
475
476 // This is a bit of a hack, but when we wait here we could very well return
477 // to the command-line, and that could disable the log, which would render the
478 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000480 {
481 if (state == eStateInvalid)
482 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
483 else
484 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000486 return state;
487}
488
489bool
490Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
491{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000492 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493
494 if (log)
495 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
496
497 if (control_only)
498 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
499 else
500 return m_private_state_listener.WaitForEvent(timeout, event_sp);
501}
502
503bool
504Process::IsRunning () const
505{
506 return StateIsRunningState (m_public_state.GetValue());
507}
508
509int
510Process::GetExitStatus ()
511{
512 if (m_public_state.GetValue() == eStateExited)
513 return m_exit_status;
514 return -1;
515}
516
Greg Clayton85851dd2010-12-04 00:10:17 +0000517
518void
519Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
520{
521 if (m_inherit_host_env && !m_got_host_env)
522 {
523 m_got_host_env = true;
524 StringList host_env;
525 const size_t host_env_count = Host::GetEnvironment (host_env);
526 for (size_t idx=0; idx<host_env_count; idx++)
527 {
528 const char *env_entry = host_env.GetStringAtIndex (idx);
529 if (env_entry)
530 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000531 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000532 if (equal_pos)
533 {
534 std::string key (env_entry, equal_pos - env_entry);
535 std::string value (equal_pos + 1);
536 if (m_env_vars.find (key) == m_env_vars.end())
537 m_env_vars[key] = value;
538 }
539 }
540 }
541 }
542}
543
544
545size_t
546Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
547{
548 GetHostEnvironmentIfNeeded ();
549
550 dictionary::const_iterator pos, end = m_env_vars.end();
551 for (pos = m_env_vars.begin(); pos != end; ++pos)
552 {
553 std::string env_var_equal_value (pos->first);
554 env_var_equal_value.append(1, '=');
555 env_var_equal_value.append (pos->second);
556 env.AppendArgument (env_var_equal_value.c_str());
557 }
558 return env.GetArgumentCount();
559}
560
561
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562const char *
563Process::GetExitDescription ()
564{
565 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
566 return m_exit_string.c_str();
567 return NULL;
568}
569
Greg Clayton6779606a2011-01-22 23:43:18 +0000570bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000571Process::SetExitStatus (int status, const char *cstr)
572{
Greg Clayton414f5d32011-01-25 02:58:48 +0000573 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
574 if (log)
575 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
576 status, status,
577 cstr ? "\"" : "",
578 cstr ? cstr : "NULL",
579 cstr ? "\"" : "");
580
Greg Clayton6779606a2011-01-22 23:43:18 +0000581 // We were already in the exited state
582 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000583 {
Greg Clayton385d6032011-01-26 23:47:29 +0000584 if (log)
585 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000586 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000587 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000588
589 m_exit_status = status;
590 if (cstr)
591 m_exit_string = cstr;
592 else
593 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000594
Greg Clayton6779606a2011-01-22 23:43:18 +0000595 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000596
Greg Clayton6779606a2011-01-22 23:43:18 +0000597 SetPrivateState (eStateExited);
598 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599}
600
601// This static callback can be used to watch for local child processes on
602// the current host. The the child process exits, the process will be
603// found in the global target list (we want to be completely sure that the
604// lldb_private::Process doesn't go away before we can deliver the signal.
605bool
606Process::SetProcessExitStatus
607(
608 void *callback_baton,
609 lldb::pid_t pid,
610 int signo, // Zero for no signal
611 int exit_status // Exit value of process if signal is zero
612)
613{
614 if (signo == 0 || exit_status)
615 {
Greg Clayton66111032010-06-23 01:19:29 +0000616 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617 if (target_sp)
618 {
619 ProcessSP process_sp (target_sp->GetProcessSP());
620 if (process_sp)
621 {
622 const char *signal_cstr = NULL;
623 if (signo)
624 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
625
626 process_sp->SetExitStatus (exit_status, signal_cstr);
627 }
628 }
629 return true;
630 }
631 return false;
632}
633
634
635uint32_t
636Process::GetNextThreadIndexID ()
637{
638 return ++m_thread_index_id;
639}
640
641StateType
642Process::GetState()
643{
644 // If any other threads access this we will need a mutex for it
645 return m_public_state.GetValue ();
646}
647
648void
649Process::SetPublicState (StateType new_state)
650{
Greg Clayton414f5d32011-01-25 02:58:48 +0000651 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 if (log)
653 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
654 m_public_state.SetValue (new_state);
655}
656
657StateType
658Process::GetPrivateState ()
659{
660 return m_private_state.GetValue();
661}
662
663void
664Process::SetPrivateState (StateType new_state)
665{
Greg Clayton414f5d32011-01-25 02:58:48 +0000666 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667 bool state_changed = false;
668
669 if (log)
670 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
671
672 Mutex::Locker locker(m_private_state.GetMutex());
673
674 const StateType old_state = m_private_state.GetValueNoLock ();
675 state_changed = old_state != new_state;
676 if (state_changed)
677 {
678 m_private_state.SetValueNoLock (new_state);
679 if (StateIsStoppedState(new_state))
680 {
681 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000682 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 if (log)
684 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
685 }
686 // Use our target to get a shared pointer to ourselves...
687 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
688 }
689 else
690 {
691 if (log)
692 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
693 }
694}
695
696
697uint32_t
698Process::GetStopID() const
699{
700 return m_stop_id;
701}
702
703addr_t
704Process::GetImageInfoAddress()
705{
706 return LLDB_INVALID_ADDRESS;
707}
708
Greg Clayton8f343b02010-11-04 01:54:29 +0000709//----------------------------------------------------------------------
710// LoadImage
711//
712// This function provides a default implementation that works for most
713// unix variants. Any Process subclasses that need to do shared library
714// loading differently should override LoadImage and UnloadImage and
715// do what is needed.
716//----------------------------------------------------------------------
717uint32_t
718Process::LoadImage (const FileSpec &image_spec, Error &error)
719{
720 DynamicLoader *loader = GetDynamicLoader();
721 if (loader)
722 {
723 error = loader->CanLoadImage();
724 if (error.Fail())
725 return LLDB_INVALID_IMAGE_TOKEN;
726 }
727
728 if (error.Success())
729 {
730 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
731 if (thread_sp == NULL)
732 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
733
734 if (thread_sp)
735 {
736 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
737
738 if (frame_sp)
739 {
740 ExecutionContext exe_ctx;
741 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000742 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000743 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000744 StreamString expr;
745 char path[PATH_MAX];
746 image_spec.GetPath(path, sizeof(path));
747 expr.Printf("dlopen (\"%s\", 2)", path);
748 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000749 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000750 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000751 if (result_valobj_sp->GetError().Success())
752 {
753 Scalar scalar;
754 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
755 {
756 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
757 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
758 {
759 uint32_t image_token = m_image_tokens.size();
760 m_image_tokens.push_back (image_ptr);
761 return image_token;
762 }
763 }
764 }
765 }
766 }
767 }
768 return LLDB_INVALID_IMAGE_TOKEN;
769}
770
771//----------------------------------------------------------------------
772// UnloadImage
773//
774// This function provides a default implementation that works for most
775// unix variants. Any Process subclasses that need to do shared library
776// loading differently should override LoadImage and UnloadImage and
777// do what is needed.
778//----------------------------------------------------------------------
779Error
780Process::UnloadImage (uint32_t image_token)
781{
782 Error error;
783 if (image_token < m_image_tokens.size())
784 {
785 const addr_t image_addr = m_image_tokens[image_token];
786 if (image_addr == LLDB_INVALID_ADDRESS)
787 {
788 error.SetErrorString("image already unloaded");
789 }
790 else
791 {
792 DynamicLoader *loader = GetDynamicLoader();
793 if (loader)
794 error = loader->CanLoadImage();
795
796 if (error.Success())
797 {
798 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
799 if (thread_sp == NULL)
800 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
801
802 if (thread_sp)
803 {
804 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
805
806 if (frame_sp)
807 {
808 ExecutionContext exe_ctx;
809 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000810 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000811 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000812 StreamString expr;
813 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
814 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000815 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000816 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000817 if (result_valobj_sp->GetError().Success())
818 {
819 Scalar scalar;
820 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
821 {
822 if (scalar.UInt(1))
823 {
824 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
825 }
826 else
827 {
828 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
829 }
830 }
831 }
832 else
833 {
834 error = result_valobj_sp->GetError();
835 }
836 }
837 }
838 }
839 }
840 }
841 else
842 {
843 error.SetErrorString("invalid image token");
844 }
845 return error;
846}
847
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848DynamicLoader *
849Process::GetDynamicLoader()
850{
851 return NULL;
852}
853
854const ABI *
855Process::GetABI()
856{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000857 if (m_abi_sp.get() == NULL)
Greg Clayton514487e2011-02-15 21:59:32 +0000858 m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000859
860 return m_abi_sp.get();
861}
862
Jim Ingham22777012010-09-23 02:01:19 +0000863LanguageRuntime *
864Process::GetLanguageRuntime(lldb::LanguageType language)
865{
866 LanguageRuntimeCollection::iterator pos;
867 pos = m_language_runtimes.find (language);
868 if (pos == m_language_runtimes.end())
869 {
870 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
871
872 m_language_runtimes[language]
873 = runtime;
874 return runtime.get();
875 }
876 else
877 return (*pos).second.get();
878}
879
880CPPLanguageRuntime *
881Process::GetCPPLanguageRuntime ()
882{
883 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
884 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
885 return static_cast<CPPLanguageRuntime *> (runtime);
886 return NULL;
887}
888
889ObjCLanguageRuntime *
890Process::GetObjCLanguageRuntime ()
891{
892 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
893 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
894 return static_cast<ObjCLanguageRuntime *> (runtime);
895 return NULL;
896}
897
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000898BreakpointSiteList &
899Process::GetBreakpointSiteList()
900{
901 return m_breakpoint_site_list;
902}
903
904const BreakpointSiteList &
905Process::GetBreakpointSiteList() const
906{
907 return m_breakpoint_site_list;
908}
909
910
911void
912Process::DisableAllBreakpointSites ()
913{
914 m_breakpoint_site_list.SetEnabledForAll (false);
915}
916
917Error
918Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
919{
920 Error error (DisableBreakpointSiteByID (break_id));
921
922 if (error.Success())
923 m_breakpoint_site_list.Remove(break_id);
924
925 return error;
926}
927
928Error
929Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
930{
931 Error error;
932 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
933 if (bp_site_sp)
934 {
935 if (bp_site_sp->IsEnabled())
936 error = DisableBreakpoint (bp_site_sp.get());
937 }
938 else
939 {
940 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
941 }
942
943 return error;
944}
945
946Error
947Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
948{
949 Error error;
950 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
951 if (bp_site_sp)
952 {
953 if (!bp_site_sp->IsEnabled())
954 error = EnableBreakpoint (bp_site_sp.get());
955 }
956 else
957 {
958 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
959 }
960 return error;
961}
962
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000963lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
965{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000966 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967 if (load_addr != LLDB_INVALID_ADDRESS)
968 {
969 BreakpointSiteSP bp_site_sp;
970
971 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
972 // create a new breakpoint site and add it.
973
974 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
975
976 if (bp_site_sp)
977 {
978 bp_site_sp->AddOwner (owner);
979 owner->SetBreakpointSite (bp_site_sp);
980 return bp_site_sp->GetID();
981 }
982 else
983 {
984 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
985 if (bp_site_sp)
986 {
987 if (EnableBreakpoint (bp_site_sp.get()).Success())
988 {
989 owner->SetBreakpointSite (bp_site_sp);
990 return m_breakpoint_site_list.Add (bp_site_sp);
991 }
992 }
993 }
994 }
995 // We failed to enable the breakpoint
996 return LLDB_INVALID_BREAK_ID;
997
998}
999
1000void
1001Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1002{
1003 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1004 if (num_owners == 0)
1005 {
1006 DisableBreakpoint(bp_site_sp.get());
1007 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1008 }
1009}
1010
1011
1012size_t
1013Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1014{
1015 size_t bytes_removed = 0;
1016 addr_t intersect_addr;
1017 size_t intersect_size;
1018 size_t opcode_offset;
1019 size_t idx;
1020 BreakpointSiteSP bp;
1021
1022 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1023 {
1024 if (bp->GetType() == BreakpointSite::eSoftware)
1025 {
1026 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1027 {
1028 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1029 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1030 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1031 size_t buf_offset = intersect_addr - bp_addr;
1032 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1033 }
1034 }
1035 }
1036 return bytes_removed;
1037}
1038
1039
1040Error
1041Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1042{
1043 Error error;
1044 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001045 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046 const addr_t bp_addr = bp_site->GetLoadAddress();
1047 if (log)
1048 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1049 if (bp_site->IsEnabled())
1050 {
1051 if (log)
1052 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1053 return error;
1054 }
1055
1056 if (bp_addr == LLDB_INVALID_ADDRESS)
1057 {
1058 error.SetErrorString("BreakpointSite contains an invalid load address.");
1059 return error;
1060 }
1061 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1062 // trap for the breakpoint site
1063 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1064
1065 if (bp_opcode_size == 0)
1066 {
1067 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1068 }
1069 else
1070 {
1071 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1072
1073 if (bp_opcode_bytes == NULL)
1074 {
1075 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1076 return error;
1077 }
1078
1079 // Save the original opcode by reading it
1080 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1081 {
1082 // Write a software breakpoint in place of the original opcode
1083 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1084 {
1085 uint8_t verify_bp_opcode_bytes[64];
1086 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1087 {
1088 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1089 {
1090 bp_site->SetEnabled(true);
1091 bp_site->SetType (BreakpointSite::eSoftware);
1092 if (log)
1093 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1094 bp_site->GetID(),
1095 (uint64_t)bp_addr);
1096 }
1097 else
1098 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1099 }
1100 else
1101 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1102 }
1103 else
1104 error.SetErrorString("Unable to write breakpoint trap to memory.");
1105 }
1106 else
1107 error.SetErrorString("Unable to read memory at breakpoint address.");
1108 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001109 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1111 bp_site->GetID(),
1112 (uint64_t)bp_addr,
1113 error.AsCString());
1114 return error;
1115}
1116
1117Error
1118Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1119{
1120 Error error;
1121 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001122 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 addr_t bp_addr = bp_site->GetLoadAddress();
1124 lldb::user_id_t breakID = bp_site->GetID();
1125 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001126 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127
1128 if (bp_site->IsHardware())
1129 {
1130 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1131 }
1132 else if (bp_site->IsEnabled())
1133 {
1134 const size_t break_op_size = bp_site->GetByteSize();
1135 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1136 if (break_op_size > 0)
1137 {
1138 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001139 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001140 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 bool break_op_found = false;
1142
1143 // Read the breakpoint opcode
1144 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1145 {
1146 bool verify = false;
1147 // Make sure we have the a breakpoint opcode exists at this address
1148 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1149 {
1150 break_op_found = true;
1151 // We found a valid breakpoint opcode at this address, now restore
1152 // the saved opcode.
1153 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1154 {
1155 verify = true;
1156 }
1157 else
1158 error.SetErrorString("Memory write failed when restoring original opcode.");
1159 }
1160 else
1161 {
1162 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1163 // Set verify to true and so we can check if the original opcode has already been restored
1164 verify = true;
1165 }
1166
1167 if (verify)
1168 {
Greg Claytonc982c762010-07-09 20:39:50 +00001169 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001170 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 // Verify that our original opcode made it back to the inferior
1172 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1173 {
1174 // compare the memory we just read with the original opcode
1175 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1176 {
1177 // SUCCESS
1178 bp_site->SetEnabled(false);
1179 if (log)
1180 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1181 return error;
1182 }
1183 else
1184 {
1185 if (break_op_found)
1186 error.SetErrorString("Failed to restore original opcode.");
1187 }
1188 }
1189 else
1190 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1191 }
1192 }
1193 else
1194 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1195 }
1196 }
1197 else
1198 {
1199 if (log)
1200 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1201 return error;
1202 }
1203
1204 if (log)
1205 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1206 bp_site->GetID(),
1207 (uint64_t)bp_addr,
1208 error.AsCString());
1209 return error;
1210
1211}
1212
Greg Clayton58be07b2011-01-07 06:08:19 +00001213// Comment out line below to disable memory caching
1214#define ENABLE_MEMORY_CACHING
1215// Uncomment to verify memory caching works after making changes to caching code
1216//#define VERIFY_MEMORY_READS
1217
1218#if defined (ENABLE_MEMORY_CACHING)
1219
1220#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001221
1222size_t
1223Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1224{
Greg Clayton58be07b2011-01-07 06:08:19 +00001225 // Memory caching is enabled, with debug verification
1226 if (buf && size)
1227 {
1228 // Uncomment the line below to make sure memory caching is working.
1229 // I ran this through the test suite and got no assertions, so I am
1230 // pretty confident this is working well. If any changes are made to
1231 // memory caching, uncomment the line below and test your changes!
1232
1233 // Verify all memory reads by using the cache first, then redundantly
1234 // reading the same memory from the inferior and comparing to make sure
1235 // everything is exactly the same.
1236 std::string verify_buf (size, '\0');
1237 assert (verify_buf.size() == size);
1238 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1239 Error verify_error;
1240 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1241 assert (cache_bytes_read == verify_bytes_read);
1242 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1243 assert (verify_error.Success() == error.Success());
1244 return cache_bytes_read;
1245 }
1246 return 0;
1247}
1248
1249#else // #if defined (VERIFY_MEMORY_READS)
1250
1251size_t
1252Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1253{
1254 // Memory caching enabled, no verification
1255 return m_memory_cache.Read (this, addr, buf, size, error);
1256}
1257
1258#endif // #else for #if defined (VERIFY_MEMORY_READS)
1259
1260#else // #if defined (ENABLE_MEMORY_CACHING)
1261
1262size_t
1263Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1264{
1265 // Memory caching is disabled
1266 return ReadMemoryFromInferior (addr, buf, size, error);
1267}
1268
1269#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1270
1271
1272size_t
1273Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1274{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275 if (buf == NULL || size == 0)
1276 return 0;
1277
1278 size_t bytes_read = 0;
1279 uint8_t *bytes = (uint8_t *)buf;
1280
1281 while (bytes_read < size)
1282 {
1283 const size_t curr_size = size - bytes_read;
1284 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1285 bytes + bytes_read,
1286 curr_size,
1287 error);
1288 bytes_read += curr_bytes_read;
1289 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1290 break;
1291 }
1292
1293 // Replace any software breakpoint opcodes that fall into this range back
1294 // into "buf" before we return
1295 if (bytes_read > 0)
1296 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1297 return bytes_read;
1298}
1299
Greg Clayton58a4c462010-12-16 20:01:20 +00001300uint64_t
1301Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1302{
1303 if (integer_byte_size > sizeof(uint64_t))
1304 {
1305 error.SetErrorString ("unsupported integer size");
1306 }
1307 else
1308 {
1309 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton514487e2011-02-15 21:59:32 +00001310 DataExtractor data (tmp,
1311 integer_byte_size,
1312 m_target.GetArchitecture().GetByteOrder(),
1313 m_target.GetArchitecture().GetAddressByteSize());
Greg Clayton58a4c462010-12-16 20:01:20 +00001314 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1315 {
1316 uint32_t offset = 0;
1317 return data.GetMaxU64 (&offset, integer_byte_size);
1318 }
1319 }
1320 // Any plug-in that doesn't return success a memory read with the number
1321 // of bytes that were requested should be setting the error
1322 assert (error.Fail());
1323 return 0;
1324}
1325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326size_t
1327Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1328{
1329 size_t bytes_written = 0;
1330 const uint8_t *bytes = (const uint8_t *)buf;
1331
1332 while (bytes_written < size)
1333 {
1334 const size_t curr_size = size - bytes_written;
1335 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1336 bytes + bytes_written,
1337 curr_size,
1338 error);
1339 bytes_written += curr_bytes_written;
1340 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1341 break;
1342 }
1343 return bytes_written;
1344}
1345
1346size_t
1347Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1348{
Greg Clayton58be07b2011-01-07 06:08:19 +00001349#if defined (ENABLE_MEMORY_CACHING)
1350 m_memory_cache.Flush (addr, size);
1351#endif
1352
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 if (buf == NULL || size == 0)
1354 return 0;
1355 // We need to write any data that would go where any current software traps
1356 // (enabled software breakpoints) any software traps (breakpoints) that we
1357 // may have placed in our tasks memory.
1358
1359 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1360 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1361
1362 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1363 return DoWriteMemory(addr, buf, size, error);
1364
1365 BreakpointSiteList::collection::const_iterator pos;
1366 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001367 addr_t intersect_addr = 0;
1368 size_t intersect_size = 0;
1369 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370 const uint8_t *ubuf = (const uint8_t *)buf;
1371
1372 for (pos = iter; pos != end; ++pos)
1373 {
1374 BreakpointSiteSP bp;
1375 bp = pos->second;
1376
1377 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1378 assert(addr <= intersect_addr && intersect_addr < addr + size);
1379 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1380 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1381
1382 // Check for bytes before this breakpoint
1383 const addr_t curr_addr = addr + bytes_written;
1384 if (intersect_addr > curr_addr)
1385 {
1386 // There are some bytes before this breakpoint that we need to
1387 // just write to memory
1388 size_t curr_size = intersect_addr - curr_addr;
1389 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1390 ubuf + bytes_written,
1391 curr_size,
1392 error);
1393 bytes_written += curr_bytes_written;
1394 if (curr_bytes_written != curr_size)
1395 {
1396 // We weren't able to write all of the requested bytes, we
1397 // are done looping and will return the number of bytes that
1398 // we have written so far.
1399 break;
1400 }
1401 }
1402
1403 // Now write any bytes that would cover up any software breakpoints
1404 // directly into the breakpoint opcode buffer
1405 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1406 bytes_written += intersect_size;
1407 }
1408
1409 // Write any remaining bytes after the last breakpoint if we have any left
1410 if (bytes_written < size)
1411 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1412 ubuf + bytes_written,
1413 size - bytes_written,
1414 error);
1415
1416 return bytes_written;
1417}
1418
1419addr_t
1420Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1421{
1422 // Fixme: we should track the blocks we've allocated, and clean them up...
1423 // We could even do our own allocator here if that ends up being more efficient.
Greg Claytonb2daec92011-01-23 19:58:49 +00001424 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1425 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1426 if (log)
Greg Clayton2ad66702011-01-24 06:30:45 +00001427 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001428 size,
1429 permissions & ePermissionsReadable ? 'r' : '-',
1430 permissions & ePermissionsWritable ? 'w' : '-',
1431 permissions & ePermissionsExecutable ? 'x' : '-',
1432 (uint64_t)allocated_addr,
1433 m_stop_id);
1434 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435}
1436
1437Error
1438Process::DeallocateMemory (addr_t ptr)
1439{
Greg Claytonb2daec92011-01-23 19:58:49 +00001440 Error error(DoDeallocateMemory (ptr));
1441
1442 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1443 if (log)
1444 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1445 ptr,
1446 error.AsCString("SUCCESS"),
1447 m_stop_id);
1448 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449}
1450
1451
1452Error
1453Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1454{
1455 Error error;
1456 error.SetErrorString("watchpoints are not supported");
1457 return error;
1458}
1459
1460Error
1461Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1462{
1463 Error error;
1464 error.SetErrorString("watchpoints are not supported");
1465 return error;
1466}
1467
1468StateType
1469Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1470{
1471 StateType state;
1472 // Now wait for the process to launch and return control to us, and then
1473 // call DidLaunch:
1474 while (1)
1475 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001476 event_sp.reset();
1477 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1478
1479 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00001481
1482 // If state is invalid, then we timed out
1483 if (state == eStateInvalid)
1484 break;
1485
1486 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 HandlePrivateEvent (event_sp);
1488 }
1489 return state;
1490}
1491
1492Error
1493Process::Launch
1494(
1495 char const *argv[],
1496 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001497 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 const char *stdin_path,
1499 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001500 const char *stderr_path,
1501 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502)
1503{
1504 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001506 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-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 Clayton05faeb72010-10-07 04:19:01 +00001518 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-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 Clayton471b31c2010-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 Claytonf681b942010-08-31 18:35:14 +00001548 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001549 stdin_path,
1550 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001551 stderr_path,
1552 working_directory);
Chris Lattner30fdc8d2010-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 {
1572 DidLaunch ();
1573
1574 // This delays passing the stopped event to listeners till DidLaunch gets
1575 // a chance to complete...
1576 HandlePrivateEvent (event_sp);
1577 StartPrivateStateThread ();
1578 }
1579 else if (state == eStateExited)
1580 {
1581 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1582 // not likely to work, and return an invalid pid.
1583 HandlePrivateEvent (event_sp);
1584 }
1585 }
1586 }
1587 }
1588 else
1589 {
1590 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1591 }
1592 }
1593 return error;
1594}
1595
Jim Inghambb3a2832011-01-29 01:49:25 +00001596Process::NextEventAction::EventActionResult
1597Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001598{
Jim Inghambb3a2832011-01-29 01:49:25 +00001599 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1600 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00001601 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001602 case eStateRunning:
1603 return eEventActionRetry;
1604
1605 case eStateStopped:
1606 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00001607 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001608 // During attach, prior to sending the eStateStopped event,
1609 // lldb_private::Process subclasses must set the process must set
1610 // the new process ID.
1611 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
1612 m_process->DidAttach ();
1613 // Figure out which one is the executable, and set that in our target:
1614 ModuleList &modules = m_process->GetTarget().GetImages();
1615
1616 size_t num_modules = modules.GetSize();
1617 for (int i = 0; i < num_modules; i++)
Jim Ingham5aee1622010-08-09 23:31:02 +00001618 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001619 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1620 if (module_sp->IsExecutable())
Jim Ingham5aee1622010-08-09 23:31:02 +00001621 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001622 ModuleSP exec_module = m_process->GetTarget().GetExecutableModule();
1623 if (!exec_module || exec_module != module_sp)
1624 {
1625
1626 m_process->GetTarget().SetExecutableModule (module_sp, false);
1627 }
1628 break;
Jim Ingham5aee1622010-08-09 23:31:02 +00001629 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001630 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001631 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00001632 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001633
1634
1635 break;
1636 default:
1637 case eStateExited:
1638 case eStateInvalid:
1639 m_exit_string.assign ("No valid Process");
1640 return eEventActionExit;
1641 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00001642 }
1643}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001644
Jim Inghambb3a2832011-01-29 01:49:25 +00001645Process::NextEventAction::EventActionResult
1646Process::AttachCompletionHandler::HandleBeingInterrupted()
1647{
1648 return eEventActionSuccess;
1649}
1650
1651const char *
1652Process::AttachCompletionHandler::GetExitString ()
1653{
1654 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655}
1656
1657Error
1658Process::Attach (lldb::pid_t attach_pid)
1659{
1660
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001662 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663
Jim Ingham5aee1622010-08-09 23:31:02 +00001664 // Find the process and its architecture. Make sure it matches the architecture
1665 // of the current Target, and if not adjust it.
1666
1667 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1668 if (attach_spec != GetTarget().GetArchitecture())
1669 {
1670 // Set the architecture on the target.
1671 GetTarget().SetArchitecture(attach_spec);
1672 }
1673
Greg Claytonc982c762010-07-09 20:39:50 +00001674 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001675 if (error.Success())
1676 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001677 SetPublicState (eStateAttaching);
1678
Greg Claytonc982c762010-07-09 20:39:50 +00001679 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680 if (error.Success())
1681 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001682 SetNextEventAction(new Process::AttachCompletionHandler(this));
1683 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 }
1685 else
1686 {
1687 if (GetID() != LLDB_INVALID_PROCESS_ID)
1688 {
1689 SetID (LLDB_INVALID_PROCESS_ID);
1690 const char *error_string = error.AsCString();
1691 if (error_string == NULL)
1692 error_string = "attach failed";
1693
1694 SetExitStatus(-1, error_string);
1695 }
1696 }
1697 }
1698 return error;
1699}
1700
1701Error
1702Process::Attach (const char *process_name, bool wait_for_launch)
1703{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001704 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001705 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001706
1707 // Find the process and its architecture. Make sure it matches the architecture
1708 // of the current Target, and if not adjust it.
1709
Jim Ingham2ecb7422010-08-17 21:54:19 +00001710 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001711 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001712 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001713 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001714 {
1715 // Set the architecture on the target.
1716 GetTarget().SetArchitecture(attach_spec);
1717 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001718 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001719
Greg Claytonc982c762010-07-09 20:39:50 +00001720 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001721 if (error.Success())
1722 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001723 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001724 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001725 if (error.Fail())
1726 {
1727 if (GetID() != LLDB_INVALID_PROCESS_ID)
1728 {
1729 SetID (LLDB_INVALID_PROCESS_ID);
1730 const char *error_string = error.AsCString();
1731 if (error_string == NULL)
1732 error_string = "attach failed";
1733
1734 SetExitStatus(-1, error_string);
1735 }
1736 }
1737 else
1738 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001739 SetNextEventAction(new Process::AttachCompletionHandler(this));
1740 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741 }
1742 }
1743 return error;
1744}
1745
1746Error
Greg Claytonb766a732011-02-04 01:58:07 +00001747Process::ConnectRemote (const char *remote_url)
1748{
Greg Claytonb766a732011-02-04 01:58:07 +00001749 m_abi_sp.reset();
1750 m_process_input_reader.reset();
1751
1752 // Find the process and its architecture. Make sure it matches the architecture
1753 // of the current Target, and if not adjust it.
1754
1755 Error error (DoConnectRemote (remote_url));
1756 if (error.Success())
1757 {
1758 SetNextEventAction(new Process::AttachCompletionHandler(this));
1759 StartPrivateStateThread();
1760// TimeValue timeout;
1761// timeout = TimeValue::Now();
1762// timeout.OffsetWithMicroSeconds(000);
1763// EventSP event_sp;
1764// StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1765//
1766// if (state == eStateStopped || state == eStateCrashed)
1767// {
1768// DidLaunch ();
1769//
1770// // This delays passing the stopped event to listeners till DidLaunch gets
1771// // a chance to complete...
1772// HandlePrivateEvent (event_sp);
1773// StartPrivateStateThread ();
1774// }
1775// else if (state == eStateExited)
1776// {
1777// // We exited while trying to launch somehow. Don't call DidLaunch as that's
1778// // not likely to work, and return an invalid pid.
1779// HandlePrivateEvent (event_sp);
1780// }
1781//
1782// StartPrivateStateThread();
1783 }
1784 return error;
1785}
1786
1787
1788Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789Process::Resume ()
1790{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001791 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00001793 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
1794 m_stop_id,
1795 StateAsCString(m_public_state.GetValue()),
1796 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797
1798 Error error (WillResume());
1799 // Tell the process it is about to resume before the thread list
1800 if (error.Success())
1801 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001802 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 // can let all of our threads know that they are about to be
1804 // resumed. Threads will each be called with
1805 // Thread::WillResume(StateType) where StateType contains the state
1806 // that they are supposed to have when the process is resumed
1807 // (suspended/running/stepping). Threads should also check
1808 // their resume signal in lldb::Thread::GetResumeSignal()
1809 // to see if they are suppoed to start back up with a signal.
1810 if (m_thread_list.WillResume())
1811 {
1812 error = DoResume();
1813 if (error.Success())
1814 {
1815 DidResume();
1816 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00001817 if (log)
1818 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 }
1820 }
1821 else
1822 {
Jim Ingham444586b2011-01-24 06:34:17 +00001823 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 }
1825 }
Jim Ingham444586b2011-01-24 06:34:17 +00001826 else if (log)
1827 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 return error;
1829}
1830
1831Error
1832Process::Halt ()
1833{
Jim Inghambb3a2832011-01-29 01:49:25 +00001834 // Pause our private state thread so we can ensure no one else eats
1835 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00001836 Listener halt_listener ("lldb.process.halt_listener");
1837 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001838
Jim Inghambb3a2832011-01-29 01:49:25 +00001839 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00001840 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00001841
Greg Clayton513c26c2011-01-29 07:10:55 +00001842 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00001843 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001844
Greg Clayton513c26c2011-01-29 07:10:55 +00001845 bool caused_stop = false;
1846
1847 // Ask the process subclass to actually halt our process
1848 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001850 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001851 if (m_public_state.GetValue() == eStateAttaching)
1852 {
1853 SetExitStatus(SIGKILL, "Cancelled async attach.");
1854 Destroy ();
1855 }
1856 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001857 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001858 // If "caused_stop" is true, then DoHalt stopped the process. If
1859 // "caused_stop" is false, the process was already stopped.
1860 // If the DoHalt caused the process to stop, then we want to catch
1861 // this event and set the interrupted bool to true before we pass
1862 // this along so clients know that the process was interrupted by
1863 // a halt command.
1864 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001865 {
Jim Ingham0f16e732011-02-08 05:20:59 +00001866 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00001867 TimeValue timeout_time;
1868 timeout_time = TimeValue::Now();
1869 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00001870 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
1871 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00001872
Jim Ingham0f16e732011-02-08 05:20:59 +00001873 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001874 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001875 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00001876 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00001877 }
1878 else
1879 {
Jim Inghambb3a2832011-01-29 01:49:25 +00001880 if (StateIsStoppedState (state))
1881 {
1882 // We caused the process to interrupt itself, so mark this
1883 // as such in the stop event so clients can tell an interrupted
1884 // process from a natural stop
1885 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1886 }
1887 else
1888 {
1889 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1890 if (log)
1891 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1892 error.SetErrorString ("Did not get stopped event after halt.");
1893 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001894 }
1895 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001896 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001897 }
1898 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001899 }
Jim Inghambb3a2832011-01-29 01:49:25 +00001900 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00001901 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00001902
1903 // Post any event we might have consumed. If all goes well, we will have
1904 // stopped the process, intercepted the event and set the interrupted
1905 // bool in the event. Post it to the private event queue and that will end up
1906 // correctly setting the state.
1907 if (event_sp)
1908 m_private_state_broadcaster.BroadcastEvent(event_sp);
1909
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001910 return error;
1911}
1912
1913Error
1914Process::Detach ()
1915{
1916 Error error (WillDetach());
1917
1918 if (error.Success())
1919 {
1920 DisableAllBreakpointSites();
1921 error = DoDetach();
1922 if (error.Success())
1923 {
1924 DidDetach();
1925 StopPrivateStateThread();
1926 }
1927 }
1928 return error;
1929}
1930
1931Error
1932Process::Destroy ()
1933{
1934 Error error (WillDestroy());
1935 if (error.Success())
1936 {
1937 DisableAllBreakpointSites();
1938 error = DoDestroy();
1939 if (error.Success())
1940 {
1941 DidDestroy();
1942 StopPrivateStateThread();
1943 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001944 m_stdio_communication.StopReadThread();
1945 m_stdio_communication.Disconnect();
1946 if (m_process_input_reader && m_process_input_reader->IsActive())
1947 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1948 if (m_process_input_reader)
1949 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 }
1951 return error;
1952}
1953
1954Error
1955Process::Signal (int signal)
1956{
1957 Error error (WillSignal());
1958 if (error.Success())
1959 {
1960 error = DoSignal(signal);
1961 if (error.Success())
1962 DidSignal();
1963 }
1964 return error;
1965}
1966
Greg Clayton514487e2011-02-15 21:59:32 +00001967lldb::ByteOrder
1968Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001969{
Greg Clayton514487e2011-02-15 21:59:32 +00001970 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001971}
1972
1973uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00001974Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001975{
Greg Clayton514487e2011-02-15 21:59:32 +00001976 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977}
1978
Greg Clayton514487e2011-02-15 21:59:32 +00001979
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980bool
1981Process::ShouldBroadcastEvent (Event *event_ptr)
1982{
1983 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1984 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001985 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986
1987 switch (state)
1988 {
Greg Claytonb766a732011-02-04 01:58:07 +00001989 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990 case eStateAttaching:
1991 case eStateLaunching:
1992 case eStateDetached:
1993 case eStateExited:
1994 case eStateUnloaded:
1995 // These events indicate changes in the state of the debugging session, always report them.
1996 return_value = true;
1997 break;
1998 case eStateInvalid:
1999 // We stopped for no apparent reason, don't report it.
2000 return_value = false;
2001 break;
2002 case eStateRunning:
2003 case eStateStepping:
2004 // If we've started the target running, we handle the cases where we
2005 // are already running and where there is a transition from stopped to
2006 // running differently.
2007 // running -> running: Automatically suppress extra running events
2008 // stopped -> running: Report except when there is one or more no votes
2009 // and no yes votes.
2010 SynchronouslyNotifyStateChanged (state);
2011 switch (m_public_state.GetValue())
2012 {
2013 case eStateRunning:
2014 case eStateStepping:
2015 // We always suppress multiple runnings with no PUBLIC stop in between.
2016 return_value = false;
2017 break;
2018 default:
2019 // TODO: make this work correctly. For now always report
2020 // run if we aren't running so we don't miss any runnning
2021 // events. If I run the lldb/test/thread/a.out file and
2022 // break at main.cpp:58, run and hit the breakpoints on
2023 // multiple threads, then somehow during the stepping over
2024 // of all breakpoints no run gets reported.
2025 return_value = true;
2026
2027 // This is a transition from stop to run.
2028 switch (m_thread_list.ShouldReportRun (event_ptr))
2029 {
2030 case eVoteYes:
2031 case eVoteNoOpinion:
2032 return_value = true;
2033 break;
2034 case eVoteNo:
2035 return_value = false;
2036 break;
2037 }
2038 break;
2039 }
2040 break;
2041 case eStateStopped:
2042 case eStateCrashed:
2043 case eStateSuspended:
2044 {
2045 // We've stopped. First see if we're going to restart the target.
2046 // If we are going to stop, then we always broadcast the event.
2047 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00002048 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002049 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002050 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002051 if (log)
2052 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002053 return true;
2054 }
2055 else
2056 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002057 RefreshStateAfterStop ();
2058
2059 if (m_thread_list.ShouldStop (event_ptr) == false)
2060 {
2061 switch (m_thread_list.ShouldReportStop (event_ptr))
2062 {
2063 case eVoteYes:
2064 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002065 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002067 case eVoteNo:
2068 return_value = false;
2069 break;
2070 }
2071
2072 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002073 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 Resume ();
2075 }
2076 else
2077 {
2078 return_value = true;
2079 SynchronouslyNotifyStateChanged (state);
2080 }
2081 }
2082 }
2083 }
2084
2085 if (log)
2086 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2087 return return_value;
2088}
2089
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090
2091bool
2092Process::StartPrivateStateThread ()
2093{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002094 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095
2096 if (log)
2097 log->Printf ("Process::%s ( )", __FUNCTION__);
2098
2099 // Create a thread that watches our internal state and controls which
2100 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002101 char thread_name[1024];
2102 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2103 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002104 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105}
2106
2107void
2108Process::PausePrivateStateThread ()
2109{
2110 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2111}
2112
2113void
2114Process::ResumePrivateStateThread ()
2115{
2116 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2117}
2118
2119void
2120Process::StopPrivateStateThread ()
2121{
2122 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2123}
2124
2125void
2126Process::ControlPrivateStateThread (uint32_t signal)
2127{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002128 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129
2130 assert (signal == eBroadcastInternalStateControlStop ||
2131 signal == eBroadcastInternalStateControlPause ||
2132 signal == eBroadcastInternalStateControlResume);
2133
2134 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002135 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002137 // Signal the private state thread. First we should copy this is case the
2138 // thread starts exiting since the private state thread will NULL this out
2139 // when it exits
2140 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002141 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 {
2143 TimeValue timeout_time;
2144 bool timed_out;
2145
2146 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2147
2148 timeout_time = TimeValue::Now();
2149 timeout_time.OffsetWithSeconds(2);
2150 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2151 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2152
2153 if (signal == eBroadcastInternalStateControlStop)
2154 {
2155 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002156 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002157
2158 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002159 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002160 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 }
2162 }
2163}
2164
2165void
2166Process::HandlePrivateEvent (EventSP &event_sp)
2167{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002168 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002169
Greg Clayton414f5d32011-01-25 02:58:48 +00002170 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002171
2172 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002173 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002174 {
Jim Ingham754ab982011-01-29 04:05:41 +00002175 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002176 switch (action_result)
2177 {
2178 case NextEventAction::eEventActionSuccess:
2179 SetNextEventAction(NULL);
2180 break;
2181 case NextEventAction::eEventActionRetry:
2182 break;
2183 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002184 // Handle Exiting Here. If we already got an exited event,
2185 // we should just propagate it. Otherwise, swallow this event,
2186 // and set our state to exit so the next event will kill us.
2187 if (new_state != eStateExited)
2188 {
2189 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002190 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002191 SetNextEventAction(NULL);
2192 return;
2193 }
2194 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002195 break;
2196 }
2197 }
2198
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199 // See if we should broadcast this state to external clients?
2200 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201
2202 if (should_broadcast)
2203 {
2204 if (log)
2205 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002206 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2207 __FUNCTION__,
2208 GetID(),
2209 StateAsCString(new_state),
2210 StateAsCString (GetState ()),
2211 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212 }
Greg Clayton414f5d32011-01-25 02:58:48 +00002213 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002214 PushProcessInputReader ();
2215 else
2216 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2218 BroadcastEvent (event_sp);
2219 }
2220 else
2221 {
2222 if (log)
2223 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002224 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2225 __FUNCTION__,
2226 GetID(),
2227 StateAsCString(new_state),
2228 StateAsCString (GetState ()),
2229 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 }
2231 }
2232}
2233
2234void *
2235Process::PrivateStateThread (void *arg)
2236{
2237 Process *proc = static_cast<Process*> (arg);
2238 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 return result;
2240}
2241
2242void *
2243Process::RunPrivateStateThread ()
2244{
2245 bool control_only = false;
2246 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2247
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002248 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 if (log)
2250 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2251
2252 bool exit_now = false;
2253 while (!exit_now)
2254 {
2255 EventSP event_sp;
2256 WaitForEventsPrivate (NULL, event_sp, control_only);
2257 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2258 {
2259 switch (event_sp->GetType())
2260 {
2261 case eBroadcastInternalStateControlStop:
2262 exit_now = true;
2263 continue; // Go to next loop iteration so we exit without
2264 break; // doing any internal state managment below
2265
2266 case eBroadcastInternalStateControlPause:
2267 control_only = true;
2268 break;
2269
2270 case eBroadcastInternalStateControlResume:
2271 control_only = false;
2272 break;
2273 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002274
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002275 if (log)
2276 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2277
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002279 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280 }
2281
2282
2283 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2284
2285 if (internal_state != eStateInvalid)
2286 {
2287 HandlePrivateEvent (event_sp);
2288 }
2289
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002290 if (internal_state == eStateInvalid ||
2291 internal_state == eStateExited ||
2292 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002293 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002294 if (log)
2295 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2296
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 }
2300
Caroline Tice20ad3c42010-10-29 21:48:37 +00002301 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002302 if (log)
2303 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2304
Greg Clayton6ed95942011-01-22 07:12:45 +00002305 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2306 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 return NULL;
2308}
2309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310//------------------------------------------------------------------
2311// Process Event Data
2312//------------------------------------------------------------------
2313
2314Process::ProcessEventData::ProcessEventData () :
2315 EventData (),
2316 m_process_sp (),
2317 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002318 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002319 m_update_state (false),
2320 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321{
2322}
2323
2324Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2325 EventData (),
2326 m_process_sp (process_sp),
2327 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002328 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002329 m_update_state (false),
2330 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331{
2332}
2333
2334Process::ProcessEventData::~ProcessEventData()
2335{
2336}
2337
2338const ConstString &
2339Process::ProcessEventData::GetFlavorString ()
2340{
2341 static ConstString g_flavor ("Process::ProcessEventData");
2342 return g_flavor;
2343}
2344
2345const ConstString &
2346Process::ProcessEventData::GetFlavor () const
2347{
2348 return ProcessEventData::GetFlavorString ();
2349}
2350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351void
2352Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2353{
2354 // This function gets called twice for each event, once when the event gets pulled
2355 // off of the private process event queue, and once when it gets pulled off of
2356 // the public event queue. m_update_state is used to distinguish these
2357 // two cases; it is false when we're just pulling it off for private handling,
2358 // and we don't want to do the breakpoint command handling then.
2359
2360 if (!m_update_state)
2361 return;
2362
2363 m_process_sp->SetPublicState (m_state);
2364
2365 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2366 if (m_state == eStateStopped && ! m_restarted)
2367 {
2368 int num_threads = m_process_sp->GetThreadList().GetSize();
2369 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002370
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371 for (idx = 0; idx < num_threads; ++idx)
2372 {
2373 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2374
Jim Inghamb15bfc72010-10-20 00:39:53 +00002375 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2376 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002378 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379 }
2380 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002381
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002382 // The stop action might restart the target. If it does, then we want to mark that in the
2383 // event so that whoever is receiving it will know to wait for the running event and reflect
2384 // that state appropriately.
2385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 if (m_process_sp->GetPrivateState() == eStateRunning)
2387 SetRestarted(true);
2388 }
2389}
2390
2391void
2392Process::ProcessEventData::Dump (Stream *s) const
2393{
2394 if (m_process_sp)
2395 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2396
2397 s->Printf("state = %s", StateAsCString(GetState()));;
2398}
2399
2400const Process::ProcessEventData *
2401Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2402{
2403 if (event_ptr)
2404 {
2405 const EventData *event_data = event_ptr->GetData();
2406 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2407 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2408 }
2409 return NULL;
2410}
2411
2412ProcessSP
2413Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2414{
2415 ProcessSP process_sp;
2416 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2417 if (data)
2418 process_sp = data->GetProcessSP();
2419 return process_sp;
2420}
2421
2422StateType
2423Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2424{
2425 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2426 if (data == NULL)
2427 return eStateInvalid;
2428 else
2429 return data->GetState();
2430}
2431
2432bool
2433Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2434{
2435 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2436 if (data == NULL)
2437 return false;
2438 else
2439 return data->GetRestarted();
2440}
2441
2442void
2443Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2444{
2445 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2446 if (data != NULL)
2447 data->SetRestarted(new_value);
2448}
2449
2450bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002451Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2452{
2453 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2454 if (data == NULL)
2455 return false;
2456 else
2457 return data->GetInterrupted ();
2458}
2459
2460void
2461Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2462{
2463 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2464 if (data != NULL)
2465 data->SetInterrupted(new_value);
2466}
2467
2468bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2470{
2471 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2472 if (data)
2473 {
2474 data->SetUpdateStateOnRemoval();
2475 return true;
2476 }
2477 return false;
2478}
2479
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480void
Greg Clayton0603aa92010-10-04 01:05:56 +00002481Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482{
2483 exe_ctx.target = &m_target;
2484 exe_ctx.process = this;
2485 exe_ctx.thread = NULL;
2486 exe_ctx.frame = NULL;
2487}
2488
2489lldb::ProcessSP
2490Process::GetSP ()
2491{
2492 return GetTarget().GetProcessSP();
2493}
2494
Jim Ingham5aee1622010-08-09 23:31:02 +00002495uint32_t
2496Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2497{
2498 return 0;
2499}
2500
2501ArchSpec
2502Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2503{
2504 return Host::GetArchSpecForExistingProcess (pid);
2505}
2506
2507ArchSpec
2508Process::GetArchSpecForExistingProcess (const char *process_name)
2509{
2510 return Host::GetArchSpecForExistingProcess (process_name);
2511}
2512
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002513void
2514Process::AppendSTDOUT (const char * s, size_t len)
2515{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002516 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002517 m_stdout_data.append (s, len);
2518
Greg Claytona9ff3062010-12-05 19:16:56 +00002519 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002520}
2521
2522void
2523Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2524{
2525 Process *process = (Process *) baton;
2526 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2527}
2528
2529size_t
2530Process::ProcessInputReaderCallback (void *baton,
2531 InputReader &reader,
2532 lldb::InputReaderAction notification,
2533 const char *bytes,
2534 size_t bytes_len)
2535{
2536 Process *process = (Process *) baton;
2537
2538 switch (notification)
2539 {
2540 case eInputReaderActivate:
2541 break;
2542
2543 case eInputReaderDeactivate:
2544 break;
2545
2546 case eInputReaderReactivate:
2547 break;
2548
2549 case eInputReaderGotToken:
2550 {
2551 Error error;
2552 process->PutSTDIN (bytes, bytes_len, error);
2553 }
2554 break;
2555
Caroline Ticeefed6132010-11-19 20:47:54 +00002556 case eInputReaderInterrupt:
2557 process->Halt ();
2558 break;
2559
2560 case eInputReaderEndOfFile:
2561 process->AppendSTDOUT ("^D", 2);
2562 break;
2563
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002564 case eInputReaderDone:
2565 break;
2566
2567 }
2568
2569 return bytes_len;
2570}
2571
2572void
2573Process::ResetProcessInputReader ()
2574{
2575 m_process_input_reader.reset();
2576}
2577
2578void
2579Process::SetUpProcessInputReader (int file_descriptor)
2580{
2581 // First set up the Read Thread for reading/handling process I/O
2582
2583 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2584
2585 if (conn_ap.get())
2586 {
2587 m_stdio_communication.SetConnection (conn_ap.release());
2588 if (m_stdio_communication.IsConnected())
2589 {
2590 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2591 m_stdio_communication.StartReadThread();
2592
2593 // Now read thread is set up, set up input reader.
2594
2595 if (!m_process_input_reader.get())
2596 {
2597 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2598 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2599 this,
2600 eInputReaderGranularityByte,
2601 NULL,
2602 NULL,
2603 false));
2604
2605 if (err.Fail())
2606 m_process_input_reader.reset();
2607 }
2608 }
2609 }
2610}
2611
2612void
2613Process::PushProcessInputReader ()
2614{
2615 if (m_process_input_reader && !m_process_input_reader->IsActive())
2616 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2617}
2618
2619void
2620Process::PopProcessInputReader ()
2621{
2622 if (m_process_input_reader && m_process_input_reader->IsActive())
2623 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2624}
2625
Greg Clayton99d0faf2010-11-18 23:32:35 +00002626
2627void
2628Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002629{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002630 UserSettingsControllerSP &usc = GetSettingsController();
2631 usc.reset (new SettingsController);
2632 UserSettingsController::InitializeSettingsController (usc,
2633 SettingsController::global_settings_table,
2634 SettingsController::instance_settings_table);
2635}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002636
Greg Clayton99d0faf2010-11-18 23:32:35 +00002637void
2638Process::Terminate ()
2639{
2640 UserSettingsControllerSP &usc = GetSettingsController();
2641 UserSettingsController::FinalizeSettingsController (usc);
2642 usc.reset();
2643}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002644
Greg Clayton99d0faf2010-11-18 23:32:35 +00002645UserSettingsControllerSP &
2646Process::GetSettingsController ()
2647{
2648 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002649 return g_settings_controller;
2650}
2651
Caroline Tice1559a462010-09-27 00:30:10 +00002652void
2653Process::UpdateInstanceName ()
2654{
2655 ModuleSP module_sp = GetTarget().GetExecutableModule();
2656 if (module_sp)
2657 {
2658 StreamString sstr;
2659 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2660
Greg Claytondbe54502010-11-19 03:46:01 +00002661 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002662 sstr.GetData());
2663 }
2664}
2665
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002666ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002667Process::RunThreadPlan (ExecutionContext &exe_ctx,
2668 lldb::ThreadPlanSP &thread_plan_sp,
2669 bool stop_others,
2670 bool try_all_threads,
2671 bool discard_on_error,
2672 uint32_t single_thread_timeout_usec,
2673 Stream &errors)
2674{
2675 ExecutionResults return_value = eExecutionSetupError;
2676
Jim Ingham77787032011-01-20 02:03:18 +00002677 if (thread_plan_sp.get() == NULL)
2678 {
2679 errors.Printf("RunThreadPlan called with empty thread plan.");
2680 return lldb::eExecutionSetupError;
2681 }
2682
Jim Ingham444586b2011-01-24 06:34:17 +00002683 if (m_private_state.GetValue() != eStateStopped)
2684 {
2685 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham0f16e732011-02-08 05:20:59 +00002686 return lldb::eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00002687 }
2688
Jim Inghamf48169b2010-11-30 02:22:11 +00002689 // Save this value for restoration of the execution context after we run
2690 uint32_t tid = exe_ctx.thread->GetIndexID();
2691
2692 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2693 // so we should arrange to reset them as well.
2694
2695 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2696 lldb::StackFrameSP selected_frame_sp;
2697
2698 uint32_t selected_tid;
2699 if (selected_thread_sp != NULL)
2700 {
2701 selected_tid = selected_thread_sp->GetIndexID();
2702 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2703 }
2704 else
2705 {
2706 selected_tid = LLDB_INVALID_THREAD_ID;
2707 }
2708
2709 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2710
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002711 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00002712
2713 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
2714 // restored on exit to the function.
2715
2716 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00002717
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002718 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00002719 if (log)
2720 {
2721 StreamString s;
2722 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham0f16e732011-02-08 05:20:59 +00002723 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
2724 exe_ctx.thread->GetIndexID(),
2725 exe_ctx.thread->GetID(),
2726 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00002727 }
2728
Jim Ingham0f16e732011-02-08 05:20:59 +00002729 bool got_event;
2730 lldb::EventSP event_sp;
2731 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00002732
2733 TimeValue* timeout_ptr = NULL;
2734 TimeValue real_timeout;
2735
Jim Ingham0f16e732011-02-08 05:20:59 +00002736 bool first_timeout = true;
2737 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00002738
Jim Inghamf48169b2010-11-30 02:22:11 +00002739 while (1)
2740 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002741 // We usually want to resume the process if we get to the top of the loop.
2742 // The only exception is if we get two running events with no intervening
2743 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00002744
Jim Ingham0f16e732011-02-08 05:20:59 +00002745 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00002746 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002747 // Do the initial resume and wait for the running event before going further.
2748
2749 Error resume_error = exe_ctx.process->Resume ();
2750 if (!resume_error.Success())
2751 {
2752 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2753 return_value = lldb::eExecutionSetupError;
2754 break;
2755 }
2756
2757 real_timeout = TimeValue::Now();
2758 real_timeout.OffsetWithMicroSeconds(500000);
2759 timeout_ptr = &real_timeout;
2760
2761 got_event = listener.WaitForEvent(NULL, event_sp);
2762 if (!got_event)
2763 {
2764 if (log)
2765 log->Printf("Didn't get any event after initial resume, exiting.");
2766
2767 errors.Printf("Didn't get any event after initial resume, exiting.");
2768 return_value = lldb::eExecutionSetupError;
2769 break;
2770 }
2771
2772 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2773 if (stop_state != eStateRunning)
2774 {
2775 if (log)
2776 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2777
2778 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
2779 return_value = lldb::eExecutionSetupError;
2780 break;
2781 }
2782
2783 if (log)
2784 log->Printf ("Resuming succeeded.");
2785 // We need to call the function synchronously, so spin waiting for it to return.
2786 // If we get interrupted while executing, we're going to lose our context, and
2787 // won't be able to gather the result at this point.
2788 // We set the timeout AFTER the resume, since the resume takes some time and we
2789 // don't want to charge that to the timeout.
2790
2791 if (single_thread_timeout_usec != 0)
2792 {
2793 real_timeout = TimeValue::Now();
2794 if (first_timeout)
2795 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2796 else
2797 real_timeout.OffsetWithSeconds(10);
2798
2799 timeout_ptr = &real_timeout;
2800 }
2801 }
2802 else
2803 {
2804 if (log)
2805 log->Printf ("Handled an extra running event.");
2806 do_resume = true;
2807 }
2808
2809 // Now wait for the process to stop again:
2810 stop_state = lldb::eStateInvalid;
2811 event_sp.reset();
2812 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2813
2814 if (got_event)
2815 {
2816 if (event_sp.get())
2817 {
2818 bool keep_going = false;
2819 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2820 if (log)
2821 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
2822
2823 switch (stop_state)
2824 {
2825 case lldb::eStateStopped:
2826 // Yay, we're done.
2827 if (log)
2828 log->Printf ("Execution completed successfully.");
2829 return_value = lldb::eExecutionCompleted;
2830 break;
2831 case lldb::eStateCrashed:
2832 if (log)
2833 log->Printf ("Execution crashed.");
2834 return_value = lldb::eExecutionInterrupted;
2835 break;
2836 case lldb::eStateRunning:
2837 do_resume = false;
2838 keep_going = true;
2839 break;
2840 default:
2841 if (log)
2842 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
2843 return_value = lldb::eExecutionInterrupted;
2844 break;
2845 }
2846 if (keep_going)
2847 continue;
2848 else
2849 break;
2850 }
2851 else
2852 {
2853 if (log)
2854 log->Printf ("got_event was true, but the event pointer was null. How odd...");
2855 return_value = lldb::eExecutionInterrupted;
2856 break;
2857 }
2858 }
2859 else
2860 {
2861 // If we didn't get an event that means we've timed out...
2862 // We will interrupt the process here. Depending on what we were asked to do we will
2863 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00002864 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00002865
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002866 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002867 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00002868 {
2869 if (first_timeout)
2870 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2871 "trying with all threads enabled.",
2872 single_thread_timeout_usec);
2873 else
2874 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
2875 "and timeout: %d timed out.",
2876 single_thread_timeout_usec);
2877 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002878 else
Jim Ingham0f16e732011-02-08 05:20:59 +00002879 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
2880 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00002881 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002882 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002883
Jim Inghame22e88b2011-01-22 01:30:53 +00002884 Error halt_error = exe_ctx.process->Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00002885 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002886 {
Jim Inghamf48169b2010-11-30 02:22:11 +00002887 if (log)
Greg Clayton414f5d32011-01-25 02:58:48 +00002888 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00002889
Jim Ingham0f16e732011-02-08 05:20:59 +00002890 // If halt succeeds, it always produces a stopped event. Wait for that:
2891
2892 real_timeout = TimeValue::Now();
2893 real_timeout.OffsetWithMicroSeconds(500000);
2894
2895 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00002896
2897 if (got_event)
2898 {
2899 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2900 if (log)
2901 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002902 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00002903 if (stop_state == lldb::eStateStopped
2904 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00002905 log->Printf (" Event was the Halt interruption event.");
2906 }
2907
Jim Ingham0f16e732011-02-08 05:20:59 +00002908 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00002909 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002910 // Between the time we initiated the Halt and the time we delivered it, the process could have
2911 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00002912
Jim Ingham0f16e732011-02-08 05:20:59 +00002913 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2914 {
2915 if (log)
2916 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
2917 "Exiting wait loop.");
2918 return_value = lldb::eExecutionCompleted;
2919 break;
2920 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002921
Jim Ingham0f16e732011-02-08 05:20:59 +00002922 if (!try_all_threads)
2923 {
2924 if (log)
2925 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
2926 return_value = lldb::eExecutionInterrupted;
2927 break;
2928 }
2929
2930 if (first_timeout)
2931 {
2932 // Set all the other threads to run, and return to the top of the loop, which will continue;
2933 first_timeout = false;
2934 thread_plan_sp->SetStopOthers (false);
2935 if (log)
2936 log->Printf ("Process::RunThreadPlan(): About to resume.");
2937
2938 continue;
2939 }
2940 else
2941 {
2942 // Running all threads failed, so return Interrupted.
2943 if (log)
2944 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
2945 return_value = lldb::eExecutionInterrupted;
2946 break;
2947 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002948 }
Jim Ingham0f16e732011-02-08 05:20:59 +00002949 }
2950 else
2951 { if (log)
2952 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
2953 "I'm getting out of here passing Interrupted.");
2954 return_value = lldb::eExecutionInterrupted;
2955 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00002956 }
2957 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002958 else
2959 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002960 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
2961 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00002962 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00002963 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.",
2964 halt_error.AsCString());
2965 real_timeout = TimeValue::Now();
2966 real_timeout.OffsetWithMicroSeconds(500000);
2967 timeout_ptr = &real_timeout;
2968 got_event = listener.WaitForEvent(&real_timeout, event_sp);
2969 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002970 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002971 // This is not going anywhere, bag out.
2972 if (log)
2973 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
2974 return_value = lldb::eExecutionInterrupted;
2975 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00002976 }
Jim Ingham0f16e732011-02-08 05:20:59 +00002977 else
2978 {
2979 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2980 if (log)
2981 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
2982 if (stop_state == lldb::eStateStopped)
2983 {
2984 // Between the time we initiated the Halt and the time we delivered it, the process could have
2985 // already finished its job. Check that here:
2986
2987 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2988 {
2989 if (log)
2990 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
2991 "Exiting wait loop.");
2992 return_value = lldb::eExecutionCompleted;
2993 break;
2994 }
2995
2996 if (first_timeout)
2997 {
2998 // Set all the other threads to run, and return to the top of the loop, which will continue;
2999 first_timeout = false;
3000 thread_plan_sp->SetStopOthers (false);
3001 if (log)
3002 log->Printf ("Process::RunThreadPlan(): About to resume.");
3003
3004 continue;
3005 }
3006 else
3007 {
3008 // Running all threads failed, so return Interrupted.
3009 if (log)
3010 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3011 return_value = lldb::eExecutionInterrupted;
3012 break;
3013 }
3014 }
3015 else
3016 {
3017 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3018 " a stopped event, instead got %s.", StateAsCString(stop_state));
3019 return_value = lldb::eExecutionInterrupted;
3020 break;
3021 }
3022 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003023 }
3024
Jim Inghamf48169b2010-11-30 02:22:11 +00003025 }
3026
Jim Ingham0f16e732011-02-08 05:20:59 +00003027 } // END WAIT LOOP
3028
3029 // Now do some processing on the results of the run:
3030 if (return_value == eExecutionInterrupted)
3031 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003032 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003033 {
3034 StreamString s;
3035 if (event_sp)
3036 event_sp->Dump (&s);
3037 else
3038 {
3039 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3040 }
3041
3042 StreamString ts;
3043
3044 const char *event_explanation;
3045
3046 do
3047 {
3048 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3049
3050 if (!event_data)
3051 {
3052 event_explanation = "<no event data>";
3053 break;
3054 }
3055
3056 Process *process = event_data->GetProcessSP().get();
3057
3058 if (!process)
3059 {
3060 event_explanation = "<no process>";
3061 break;
3062 }
3063
3064 ThreadList &thread_list = process->GetThreadList();
3065
3066 uint32_t num_threads = thread_list.GetSize();
3067 uint32_t thread_index;
3068
3069 ts.Printf("<%u threads> ", num_threads);
3070
3071 for (thread_index = 0;
3072 thread_index < num_threads;
3073 ++thread_index)
3074 {
3075 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3076
3077 if (!thread)
3078 {
3079 ts.Printf("<?> ");
3080 continue;
3081 }
3082
3083 ts.Printf("<0x%4.4x ", thread->GetID());
3084 RegisterContext *register_context = thread->GetRegisterContext().get();
3085
3086 if (register_context)
3087 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3088 else
3089 ts.Printf("[ip unknown] ");
3090
3091 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3092 if (stop_info_sp)
3093 {
3094 const char *stop_desc = stop_info_sp->GetDescription();
3095 if (stop_desc)
3096 ts.PutCString (stop_desc);
3097 }
3098 ts.Printf(">");
3099 }
3100
3101 event_explanation = ts.GetData();
3102 } while (0);
3103
3104 if (log)
3105 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3106
3107 if (discard_on_error && thread_plan_sp)
3108 {
3109 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3110 }
3111 }
3112 }
3113 else if (return_value == eExecutionSetupError)
3114 {
3115 if (log)
3116 log->Printf("Process::RunThreadPlan(): execution set up error.");
3117
3118 if (discard_on_error && thread_plan_sp)
3119 {
3120 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3121 }
3122 }
3123 else
3124 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003125 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3126 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003127 if (log)
3128 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003129 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003130 }
3131 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3132 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003133 if (log)
3134 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003135 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003136 }
3137 else
3138 {
3139 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003140 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003141 if (discard_on_error && thread_plan_sp)
3142 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003143 if (log)
3144 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003145 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3146 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003147 }
3148 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003149
Jim Inghamf48169b2010-11-30 02:22:11 +00003150 // Thread we ran the function in may have gone away because we ran the target
3151 // Check that it's still there.
3152 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3153 if (exe_ctx.thread)
3154 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3155
3156 // Also restore the current process'es selected frame & thread, since this function calling may
3157 // be done behind the user's back.
3158
3159 if (selected_tid != LLDB_INVALID_THREAD_ID)
3160 {
3161 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3162 {
3163 // We were able to restore the selected thread, now restore the frame:
3164 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3165 }
3166 }
3167
3168 return return_value;
3169}
3170
3171const char *
3172Process::ExecutionResultAsCString (ExecutionResults result)
3173{
3174 const char *result_name;
3175
3176 switch (result)
3177 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003178 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003179 result_name = "eExecutionCompleted";
3180 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003181 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003182 result_name = "eExecutionDiscarded";
3183 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003184 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003185 result_name = "eExecutionInterrupted";
3186 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003187 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003188 result_name = "eExecutionSetupError";
3189 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003190 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003191 result_name = "eExecutionTimedOut";
3192 break;
3193 }
3194 return result_name;
3195}
3196
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003197//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003198// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003199//--------------------------------------------------------------
3200
Greg Clayton1b654882010-09-19 02:33:57 +00003201Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00003202 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003203{
Greg Clayton85851dd2010-12-04 00:10:17 +00003204 m_default_settings.reset (new ProcessInstanceSettings (*this,
3205 false,
Caroline Tice91123da2010-09-08 17:48:55 +00003206 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003207}
3208
Greg Clayton1b654882010-09-19 02:33:57 +00003209Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003210{
3211}
3212
3213lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00003214Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003215{
Greg Claytondbe54502010-11-19 03:46:01 +00003216 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3217 false,
3218 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003219 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3220 return new_settings_sp;
3221}
3222
3223//--------------------------------------------------------------
3224// class ProcessInstanceSettings
3225//--------------------------------------------------------------
3226
Greg Clayton85851dd2010-12-04 00:10:17 +00003227ProcessInstanceSettings::ProcessInstanceSettings
3228(
3229 UserSettingsController &owner,
3230 bool live_instance,
3231 const char *name
3232) :
3233 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003234 m_run_args (),
3235 m_env_vars (),
3236 m_input_path (),
3237 m_output_path (),
3238 m_error_path (),
3239 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00003240 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00003241 m_disable_stdio (false),
3242 m_inherit_host_env (true),
3243 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003244{
Caroline Ticef20e8232010-09-09 18:26:37 +00003245 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3246 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3247 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00003248 // This is true for CreateInstanceName() too.
3249
3250 if (GetInstanceName () == InstanceSettings::InvalidName())
3251 {
3252 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3253 m_owner.RegisterInstanceSettings (this);
3254 }
Caroline Ticef20e8232010-09-09 18:26:37 +00003255
3256 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003257 {
3258 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3259 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00003260 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003261 }
3262}
3263
3264ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00003265 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003266 m_run_args (rhs.m_run_args),
3267 m_env_vars (rhs.m_env_vars),
3268 m_input_path (rhs.m_input_path),
3269 m_output_path (rhs.m_output_path),
3270 m_error_path (rhs.m_error_path),
3271 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00003272 m_disable_aslr (rhs.m_disable_aslr),
3273 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003274{
3275 if (m_instance_name != InstanceSettings::GetDefaultName())
3276 {
3277 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3278 CopyInstanceSettings (pending_settings,false);
3279 m_owner.RemovePendingSettings (m_instance_name);
3280 }
3281}
3282
3283ProcessInstanceSettings::~ProcessInstanceSettings ()
3284{
3285}
3286
3287ProcessInstanceSettings&
3288ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3289{
3290 if (this != &rhs)
3291 {
3292 m_run_args = rhs.m_run_args;
3293 m_env_vars = rhs.m_env_vars;
3294 m_input_path = rhs.m_input_path;
3295 m_output_path = rhs.m_output_path;
3296 m_error_path = rhs.m_error_path;
3297 m_plugin = rhs.m_plugin;
3298 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003299 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00003300 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003301 }
3302
3303 return *this;
3304}
3305
3306
3307void
3308ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3309 const char *index_value,
3310 const char *value,
3311 const ConstString &instance_name,
3312 const SettingEntry &entry,
3313 lldb::VarSetOperationType op,
3314 Error &err,
3315 bool pending)
3316{
3317 if (var_name == RunArgsVarName())
3318 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3319 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003320 {
3321 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003322 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003323 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003324 else if (var_name == InputPathVarName())
3325 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3326 else if (var_name == OutputPathVarName())
3327 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3328 else if (var_name == ErrorPathVarName())
3329 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3330 else if (var_name == PluginVarName())
3331 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003332 else if (var_name == InheritHostEnvVarName())
3333 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003334 else if (var_name == DisableASLRVarName())
3335 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003336 else if (var_name == DisableSTDIOVarName ())
3337 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003338}
3339
3340void
3341ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3342 bool pending)
3343{
3344 if (new_settings.get() == NULL)
3345 return;
3346
3347 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3348
3349 m_run_args = new_process_settings->m_run_args;
3350 m_env_vars = new_process_settings->m_env_vars;
3351 m_input_path = new_process_settings->m_input_path;
3352 m_output_path = new_process_settings->m_output_path;
3353 m_error_path = new_process_settings->m_error_path;
3354 m_plugin = new_process_settings->m_plugin;
3355 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003356 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003357}
3358
Caroline Tice12cecd72010-09-20 21:37:42 +00003359bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003360ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3361 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003362 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003363 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003364{
3365 if (var_name == RunArgsVarName())
3366 {
3367 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003368 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003369 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3370 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003371 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003372 }
3373 else if (var_name == EnvVarsVarName())
3374 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003375 GetHostEnvironmentIfNeeded ();
3376
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003377 if (m_env_vars.size() > 0)
3378 {
3379 std::map<std::string, std::string>::iterator pos;
3380 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3381 {
3382 StreamString value_str;
3383 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3384 value.AppendString (value_str.GetData());
3385 }
3386 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003387 }
3388 else if (var_name == InputPathVarName())
3389 {
3390 value.AppendString (m_input_path.c_str());
3391 }
3392 else if (var_name == OutputPathVarName())
3393 {
3394 value.AppendString (m_output_path.c_str());
3395 }
3396 else if (var_name == ErrorPathVarName())
3397 {
3398 value.AppendString (m_error_path.c_str());
3399 }
3400 else if (var_name == PluginVarName())
3401 {
3402 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3403 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003404 else if (var_name == InheritHostEnvVarName())
3405 {
3406 if (m_inherit_host_env)
3407 value.AppendString ("true");
3408 else
3409 value.AppendString ("false");
3410 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003411 else if (var_name == DisableASLRVarName())
3412 {
3413 if (m_disable_aslr)
3414 value.AppendString ("true");
3415 else
3416 value.AppendString ("false");
3417 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003418 else if (var_name == DisableSTDIOVarName())
3419 {
3420 if (m_disable_stdio)
3421 value.AppendString ("true");
3422 else
3423 value.AppendString ("false");
3424 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003425 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003426 {
3427 if (err)
3428 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3429 return false;
3430 }
3431 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003432}
3433
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003434const ConstString
3435ProcessInstanceSettings::CreateInstanceName ()
3436{
3437 static int instance_count = 1;
3438 StreamString sstr;
3439
3440 sstr.Printf ("process_%d", instance_count);
3441 ++instance_count;
3442
3443 const ConstString ret_val (sstr.GetData());
3444 return ret_val;
3445}
3446
3447const ConstString &
3448ProcessInstanceSettings::RunArgsVarName ()
3449{
3450 static ConstString run_args_var_name ("run-args");
3451
3452 return run_args_var_name;
3453}
3454
3455const ConstString &
3456ProcessInstanceSettings::EnvVarsVarName ()
3457{
3458 static ConstString env_vars_var_name ("env-vars");
3459
3460 return env_vars_var_name;
3461}
3462
3463const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003464ProcessInstanceSettings::InheritHostEnvVarName ()
3465{
3466 static ConstString g_name ("inherit-env");
3467
3468 return g_name;
3469}
3470
3471const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003472ProcessInstanceSettings::InputPathVarName ()
3473{
3474 static ConstString input_path_var_name ("input-path");
3475
3476 return input_path_var_name;
3477}
3478
3479const ConstString &
3480ProcessInstanceSettings::OutputPathVarName ()
3481{
Caroline Tice49e27372010-09-07 18:35:40 +00003482 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003483
3484 return output_path_var_name;
3485}
3486
3487const ConstString &
3488ProcessInstanceSettings::ErrorPathVarName ()
3489{
Caroline Tice49e27372010-09-07 18:35:40 +00003490 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003491
3492 return error_path_var_name;
3493}
3494
3495const ConstString &
3496ProcessInstanceSettings::PluginVarName ()
3497{
3498 static ConstString plugin_var_name ("plugin");
3499
3500 return plugin_var_name;
3501}
3502
3503
3504const ConstString &
3505ProcessInstanceSettings::DisableASLRVarName ()
3506{
3507 static ConstString disable_aslr_var_name ("disable-aslr");
3508
3509 return disable_aslr_var_name;
3510}
3511
Caroline Ticef8da8632010-12-03 18:46:09 +00003512const ConstString &
3513ProcessInstanceSettings::DisableSTDIOVarName ()
3514{
3515 static ConstString disable_stdio_var_name ("disable-stdio");
3516
3517 return disable_stdio_var_name;
3518}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003519
3520//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003521// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003522//--------------------------------------------------
3523
3524SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003525Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003526{
3527 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3528 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3529};
3530
3531
3532lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003533Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003534{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003535 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3536 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3537 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003538};
3539
3540SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003541Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003542{
Greg Clayton85851dd2010-12-04 00:10:17 +00003543 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3544 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3545 { "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." },
3546 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00003547 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3548 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3549 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3550 { "plugin", eSetVarTypeEnum, NULL, g_plugins, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00003551 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3552 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3553 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003554};
3555
3556
Jim Ingham5aee1622010-08-09 23:31:02 +00003557