blob: 90ea0b6cb1811e47b61b75edb53d1b5ae69a0b58 [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_target_triple (),
233 m_byte_order (eByteOrderHost),
234 m_addr_byte_size (0),
235 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000236 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000237 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000238 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000239 m_stdout_data (),
240 m_memory_cache ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000241{
Caroline Tice1559a462010-09-27 00:30:10 +0000242 UpdateInstanceName();
243
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 if (log)
246 log->Printf ("%p Process::Process()", this);
247
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000248 SetEventName (eBroadcastBitStateChanged, "state-changed");
249 SetEventName (eBroadcastBitInterrupt, "interrupt");
250 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
251 SetEventName (eBroadcastBitSTDERR, "stderr-available");
252
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253 listener.StartListeningForEvents (this,
254 eBroadcastBitStateChanged |
255 eBroadcastBitInterrupt |
256 eBroadcastBitSTDOUT |
257 eBroadcastBitSTDERR);
258
259 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
260 eBroadcastBitStateChanged);
261
262 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
263 eBroadcastInternalStateControlStop |
264 eBroadcastInternalStateControlPause |
265 eBroadcastInternalStateControlResume);
266}
267
268//----------------------------------------------------------------------
269// Destructor
270//----------------------------------------------------------------------
271Process::~Process()
272{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274 if (log)
275 log->Printf ("%p Process::~Process()", this);
276 StopPrivateStateThread();
277}
278
279void
280Process::Finalize()
281{
282 // Do any cleanup needed prior to being destructed... Subclasses
283 // that override this method should call this superclass method as well.
284}
285
286void
287Process::RegisterNotificationCallbacks (const Notifications& callbacks)
288{
289 m_notifications.push_back(callbacks);
290 if (callbacks.initialize != NULL)
291 callbacks.initialize (callbacks.baton, this);
292}
293
294bool
295Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
296{
297 std::vector<Notifications>::iterator pos, end = m_notifications.end();
298 for (pos = m_notifications.begin(); pos != end; ++pos)
299 {
300 if (pos->baton == callbacks.baton &&
301 pos->initialize == callbacks.initialize &&
302 pos->process_state_changed == callbacks.process_state_changed)
303 {
304 m_notifications.erase(pos);
305 return true;
306 }
307 }
308 return false;
309}
310
311void
312Process::SynchronouslyNotifyStateChanged (StateType state)
313{
314 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
315 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
316 {
317 if (notification_pos->process_state_changed)
318 notification_pos->process_state_changed (notification_pos->baton, this, state);
319 }
320}
321
322// FIXME: We need to do some work on events before the general Listener sees them.
323// For instance if we are continuing from a breakpoint, we need to ensure that we do
324// the little "insert real insn, step & stop" trick. But we can't do that when the
325// event is delivered by the broadcaster - since that is done on the thread that is
326// waiting for new events, so if we needed more than one event for our handling, we would
327// stall. So instead we do it when we fetch the event off of the queue.
328//
329
330StateType
331Process::GetNextEvent (EventSP &event_sp)
332{
333 StateType state = eStateInvalid;
334
335 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
336 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
337
338 return state;
339}
340
341
342StateType
343Process::WaitForProcessToStop (const TimeValue *timeout)
344{
345 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
346 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
347}
348
349
350StateType
351Process::WaitForState
352(
353 const TimeValue *timeout,
354 const StateType *match_states, const uint32_t num_match_states
355)
356{
357 EventSP event_sp;
358 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000359 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 while (state != eStateInvalid)
361 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000362 // If we are exited or detached, we won't ever get back to any
363 // other valid state...
364 if (state == eStateDetached || state == eStateExited)
365 return state;
366
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367 state = WaitForStateChangedEvents (timeout, event_sp);
368
369 for (i=0; i<num_match_states; ++i)
370 {
371 if (match_states[i] == state)
372 return state;
373 }
374 }
375 return state;
376}
377
Jim Ingham30f9b212010-10-11 23:53:14 +0000378bool
379Process::HijackProcessEvents (Listener *listener)
380{
381 if (listener != NULL)
382 {
383 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
384 }
385 else
386 return false;
387}
388
389void
390Process::RestoreProcessEvents ()
391{
392 RestoreBroadcaster();
393}
394
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395StateType
396Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
397{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000398 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399
400 if (log)
401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
402
403 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000404 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
405 this,
406 eBroadcastBitStateChanged,
407 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
409
410 if (log)
411 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
412 __FUNCTION__,
413 timeout,
414 StateAsCString(state));
415 return state;
416}
417
418Event *
419Process::PeekAtStateChangedEvents ()
420{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000421 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422
423 if (log)
424 log->Printf ("Process::%s...", __FUNCTION__);
425
426 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000427 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
428 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429 if (log)
430 {
431 if (event_ptr)
432 {
433 log->Printf ("Process::%s (event_ptr) => %s",
434 __FUNCTION__,
435 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
436 }
437 else
438 {
439 log->Printf ("Process::%s no events found",
440 __FUNCTION__);
441 }
442 }
443 return event_ptr;
444}
445
446StateType
447Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
448{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000449 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450
451 if (log)
452 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
453
454 StateType state = eStateInvalid;
455 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
456 &m_private_state_broadcaster,
457 eBroadcastBitStateChanged,
458 event_sp))
459 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
460
461 // This is a bit of a hack, but when we wait here we could very well return
462 // to the command-line, and that could disable the log, which would render the
463 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464 if (log)
465 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
466 return state;
467}
468
469bool
470Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
471{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000472 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000473
474 if (log)
475 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
476
477 if (control_only)
478 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
479 else
480 return m_private_state_listener.WaitForEvent(timeout, event_sp);
481}
482
483bool
484Process::IsRunning () const
485{
486 return StateIsRunningState (m_public_state.GetValue());
487}
488
489int
490Process::GetExitStatus ()
491{
492 if (m_public_state.GetValue() == eStateExited)
493 return m_exit_status;
494 return -1;
495}
496
Greg Clayton85851dd2010-12-04 00:10:17 +0000497
498void
499Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
500{
501 if (m_inherit_host_env && !m_got_host_env)
502 {
503 m_got_host_env = true;
504 StringList host_env;
505 const size_t host_env_count = Host::GetEnvironment (host_env);
506 for (size_t idx=0; idx<host_env_count; idx++)
507 {
508 const char *env_entry = host_env.GetStringAtIndex (idx);
509 if (env_entry)
510 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000511 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000512 if (equal_pos)
513 {
514 std::string key (env_entry, equal_pos - env_entry);
515 std::string value (equal_pos + 1);
516 if (m_env_vars.find (key) == m_env_vars.end())
517 m_env_vars[key] = value;
518 }
519 }
520 }
521 }
522}
523
524
525size_t
526Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
527{
528 GetHostEnvironmentIfNeeded ();
529
530 dictionary::const_iterator pos, end = m_env_vars.end();
531 for (pos = m_env_vars.begin(); pos != end; ++pos)
532 {
533 std::string env_var_equal_value (pos->first);
534 env_var_equal_value.append(1, '=');
535 env_var_equal_value.append (pos->second);
536 env.AppendArgument (env_var_equal_value.c_str());
537 }
538 return env.GetArgumentCount();
539}
540
541
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542const char *
543Process::GetExitDescription ()
544{
545 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
546 return m_exit_string.c_str();
547 return NULL;
548}
549
550void
551Process::SetExitStatus (int status, const char *cstr)
552{
Greg Clayton10177aa2010-12-08 05:08:21 +0000553 if (m_private_state.GetValue() != eStateExited)
554 {
555 m_exit_status = status;
556 if (cstr)
557 m_exit_string = cstr;
558 else
559 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560
Greg Clayton10177aa2010-12-08 05:08:21 +0000561 DidExit ();
562
563 SetPrivateState (eStateExited);
564 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565}
566
567// This static callback can be used to watch for local child processes on
568// the current host. The the child process exits, the process will be
569// found in the global target list (we want to be completely sure that the
570// lldb_private::Process doesn't go away before we can deliver the signal.
571bool
572Process::SetProcessExitStatus
573(
574 void *callback_baton,
575 lldb::pid_t pid,
576 int signo, // Zero for no signal
577 int exit_status // Exit value of process if signal is zero
578)
579{
580 if (signo == 0 || exit_status)
581 {
Greg Clayton66111032010-06-23 01:19:29 +0000582 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583 if (target_sp)
584 {
585 ProcessSP process_sp (target_sp->GetProcessSP());
586 if (process_sp)
587 {
588 const char *signal_cstr = NULL;
589 if (signo)
590 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
591
592 process_sp->SetExitStatus (exit_status, signal_cstr);
593 }
594 }
595 return true;
596 }
597 return false;
598}
599
600
601uint32_t
602Process::GetNextThreadIndexID ()
603{
604 return ++m_thread_index_id;
605}
606
607StateType
608Process::GetState()
609{
610 // If any other threads access this we will need a mutex for it
611 return m_public_state.GetValue ();
612}
613
614void
615Process::SetPublicState (StateType new_state)
616{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000617 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 if (log)
619 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
620 m_public_state.SetValue (new_state);
621}
622
623StateType
624Process::GetPrivateState ()
625{
626 return m_private_state.GetValue();
627}
628
629void
630Process::SetPrivateState (StateType new_state)
631{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000632 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 bool state_changed = false;
634
635 if (log)
636 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
637
638 Mutex::Locker locker(m_private_state.GetMutex());
639
640 const StateType old_state = m_private_state.GetValueNoLock ();
641 state_changed = old_state != new_state;
642 if (state_changed)
643 {
644 m_private_state.SetValueNoLock (new_state);
645 if (StateIsStoppedState(new_state))
646 {
647 m_stop_id++;
Greg Clayton58be07b2011-01-07 06:08:19 +0000648 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 if (log)
650 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
651 }
652 // Use our target to get a shared pointer to ourselves...
653 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
654 }
655 else
656 {
657 if (log)
658 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
659 }
660}
661
662
663uint32_t
664Process::GetStopID() const
665{
666 return m_stop_id;
667}
668
669addr_t
670Process::GetImageInfoAddress()
671{
672 return LLDB_INVALID_ADDRESS;
673}
674
Greg Clayton8f343b02010-11-04 01:54:29 +0000675//----------------------------------------------------------------------
676// LoadImage
677//
678// This function provides a default implementation that works for most
679// unix variants. Any Process subclasses that need to do shared library
680// loading differently should override LoadImage and UnloadImage and
681// do what is needed.
682//----------------------------------------------------------------------
683uint32_t
684Process::LoadImage (const FileSpec &image_spec, Error &error)
685{
686 DynamicLoader *loader = GetDynamicLoader();
687 if (loader)
688 {
689 error = loader->CanLoadImage();
690 if (error.Fail())
691 return LLDB_INVALID_IMAGE_TOKEN;
692 }
693
694 if (error.Success())
695 {
696 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
697 if (thread_sp == NULL)
698 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
699
700 if (thread_sp)
701 {
702 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
703
704 if (frame_sp)
705 {
706 ExecutionContext exe_ctx;
707 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000708 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000709 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000710 StreamString expr;
711 char path[PATH_MAX];
712 image_spec.GetPath(path, sizeof(path));
713 expr.Printf("dlopen (\"%s\", 2)", path);
714 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000715 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000716 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000717 if (result_valobj_sp->GetError().Success())
718 {
719 Scalar scalar;
720 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
721 {
722 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
723 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
724 {
725 uint32_t image_token = m_image_tokens.size();
726 m_image_tokens.push_back (image_ptr);
727 return image_token;
728 }
729 }
730 }
731 }
732 }
733 }
734 return LLDB_INVALID_IMAGE_TOKEN;
735}
736
737//----------------------------------------------------------------------
738// UnloadImage
739//
740// This function provides a default implementation that works for most
741// unix variants. Any Process subclasses that need to do shared library
742// loading differently should override LoadImage and UnloadImage and
743// do what is needed.
744//----------------------------------------------------------------------
745Error
746Process::UnloadImage (uint32_t image_token)
747{
748 Error error;
749 if (image_token < m_image_tokens.size())
750 {
751 const addr_t image_addr = m_image_tokens[image_token];
752 if (image_addr == LLDB_INVALID_ADDRESS)
753 {
754 error.SetErrorString("image already unloaded");
755 }
756 else
757 {
758 DynamicLoader *loader = GetDynamicLoader();
759 if (loader)
760 error = loader->CanLoadImage();
761
762 if (error.Success())
763 {
764 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
765 if (thread_sp == NULL)
766 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
767
768 if (thread_sp)
769 {
770 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
771
772 if (frame_sp)
773 {
774 ExecutionContext exe_ctx;
775 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +0000776 bool unwind_on_error = true;
Sean Callanan92adcac2011-01-13 08:53:35 +0000777 bool keep_in_memory = false;
Greg Clayton8f343b02010-11-04 01:54:29 +0000778 StreamString expr;
779 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
780 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +0000781 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan92adcac2011-01-13 08:53:35 +0000782 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +0000783 if (result_valobj_sp->GetError().Success())
784 {
785 Scalar scalar;
786 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
787 {
788 if (scalar.UInt(1))
789 {
790 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
791 }
792 else
793 {
794 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
795 }
796 }
797 }
798 else
799 {
800 error = result_valobj_sp->GetError();
801 }
802 }
803 }
804 }
805 }
806 }
807 else
808 {
809 error.SetErrorString("invalid image token");
810 }
811 return error;
812}
813
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814DynamicLoader *
815Process::GetDynamicLoader()
816{
817 return NULL;
818}
819
820const ABI *
821Process::GetABI()
822{
823 ConstString& triple = m_target_triple;
824
825 if (triple.IsEmpty())
826 return NULL;
827
828 if (m_abi_sp.get() == NULL)
829 {
830 m_abi_sp.reset(ABI::FindPlugin(triple));
831 }
832
833 return m_abi_sp.get();
834}
835
Jim Ingham22777012010-09-23 02:01:19 +0000836LanguageRuntime *
837Process::GetLanguageRuntime(lldb::LanguageType language)
838{
839 LanguageRuntimeCollection::iterator pos;
840 pos = m_language_runtimes.find (language);
841 if (pos == m_language_runtimes.end())
842 {
843 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
844
845 m_language_runtimes[language]
846 = runtime;
847 return runtime.get();
848 }
849 else
850 return (*pos).second.get();
851}
852
853CPPLanguageRuntime *
854Process::GetCPPLanguageRuntime ()
855{
856 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
857 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
858 return static_cast<CPPLanguageRuntime *> (runtime);
859 return NULL;
860}
861
862ObjCLanguageRuntime *
863Process::GetObjCLanguageRuntime ()
864{
865 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
866 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
867 return static_cast<ObjCLanguageRuntime *> (runtime);
868 return NULL;
869}
870
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000871BreakpointSiteList &
872Process::GetBreakpointSiteList()
873{
874 return m_breakpoint_site_list;
875}
876
877const BreakpointSiteList &
878Process::GetBreakpointSiteList() const
879{
880 return m_breakpoint_site_list;
881}
882
883
884void
885Process::DisableAllBreakpointSites ()
886{
887 m_breakpoint_site_list.SetEnabledForAll (false);
888}
889
890Error
891Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
892{
893 Error error (DisableBreakpointSiteByID (break_id));
894
895 if (error.Success())
896 m_breakpoint_site_list.Remove(break_id);
897
898 return error;
899}
900
901Error
902Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
903{
904 Error error;
905 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
906 if (bp_site_sp)
907 {
908 if (bp_site_sp->IsEnabled())
909 error = DisableBreakpoint (bp_site_sp.get());
910 }
911 else
912 {
913 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
914 }
915
916 return error;
917}
918
919Error
920Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
921{
922 Error error;
923 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
924 if (bp_site_sp)
925 {
926 if (!bp_site_sp->IsEnabled())
927 error = EnableBreakpoint (bp_site_sp.get());
928 }
929 else
930 {
931 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
932 }
933 return error;
934}
935
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000936lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
938{
Greg Claytonf5e56de2010-09-14 23:36:40 +0000939 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 if (load_addr != LLDB_INVALID_ADDRESS)
941 {
942 BreakpointSiteSP bp_site_sp;
943
944 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
945 // create a new breakpoint site and add it.
946
947 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
948
949 if (bp_site_sp)
950 {
951 bp_site_sp->AddOwner (owner);
952 owner->SetBreakpointSite (bp_site_sp);
953 return bp_site_sp->GetID();
954 }
955 else
956 {
957 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
958 if (bp_site_sp)
959 {
960 if (EnableBreakpoint (bp_site_sp.get()).Success())
961 {
962 owner->SetBreakpointSite (bp_site_sp);
963 return m_breakpoint_site_list.Add (bp_site_sp);
964 }
965 }
966 }
967 }
968 // We failed to enable the breakpoint
969 return LLDB_INVALID_BREAK_ID;
970
971}
972
973void
974Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
975{
976 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
977 if (num_owners == 0)
978 {
979 DisableBreakpoint(bp_site_sp.get());
980 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
981 }
982}
983
984
985size_t
986Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
987{
988 size_t bytes_removed = 0;
989 addr_t intersect_addr;
990 size_t intersect_size;
991 size_t opcode_offset;
992 size_t idx;
993 BreakpointSiteSP bp;
994
995 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
996 {
997 if (bp->GetType() == BreakpointSite::eSoftware)
998 {
999 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1000 {
1001 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1002 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1003 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1004 size_t buf_offset = intersect_addr - bp_addr;
1005 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1006 }
1007 }
1008 }
1009 return bytes_removed;
1010}
1011
1012
1013Error
1014Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1015{
1016 Error error;
1017 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001018 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 const addr_t bp_addr = bp_site->GetLoadAddress();
1020 if (log)
1021 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1022 if (bp_site->IsEnabled())
1023 {
1024 if (log)
1025 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1026 return error;
1027 }
1028
1029 if (bp_addr == LLDB_INVALID_ADDRESS)
1030 {
1031 error.SetErrorString("BreakpointSite contains an invalid load address.");
1032 return error;
1033 }
1034 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1035 // trap for the breakpoint site
1036 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1037
1038 if (bp_opcode_size == 0)
1039 {
1040 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1041 }
1042 else
1043 {
1044 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1045
1046 if (bp_opcode_bytes == NULL)
1047 {
1048 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1049 return error;
1050 }
1051
1052 // Save the original opcode by reading it
1053 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1054 {
1055 // Write a software breakpoint in place of the original opcode
1056 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1057 {
1058 uint8_t verify_bp_opcode_bytes[64];
1059 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1060 {
1061 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1062 {
1063 bp_site->SetEnabled(true);
1064 bp_site->SetType (BreakpointSite::eSoftware);
1065 if (log)
1066 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1067 bp_site->GetID(),
1068 (uint64_t)bp_addr);
1069 }
1070 else
1071 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1072 }
1073 else
1074 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1075 }
1076 else
1077 error.SetErrorString("Unable to write breakpoint trap to memory.");
1078 }
1079 else
1080 error.SetErrorString("Unable to read memory at breakpoint address.");
1081 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001082 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1084 bp_site->GetID(),
1085 (uint64_t)bp_addr,
1086 error.AsCString());
1087 return error;
1088}
1089
1090Error
1091Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1092{
1093 Error error;
1094 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001095 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 addr_t bp_addr = bp_site->GetLoadAddress();
1097 lldb::user_id_t breakID = bp_site->GetID();
1098 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001099 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100
1101 if (bp_site->IsHardware())
1102 {
1103 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1104 }
1105 else if (bp_site->IsEnabled())
1106 {
1107 const size_t break_op_size = bp_site->GetByteSize();
1108 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1109 if (break_op_size > 0)
1110 {
1111 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001112 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001113 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114 bool break_op_found = false;
1115
1116 // Read the breakpoint opcode
1117 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1118 {
1119 bool verify = false;
1120 // Make sure we have the a breakpoint opcode exists at this address
1121 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1122 {
1123 break_op_found = true;
1124 // We found a valid breakpoint opcode at this address, now restore
1125 // the saved opcode.
1126 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1127 {
1128 verify = true;
1129 }
1130 else
1131 error.SetErrorString("Memory write failed when restoring original opcode.");
1132 }
1133 else
1134 {
1135 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1136 // Set verify to true and so we can check if the original opcode has already been restored
1137 verify = true;
1138 }
1139
1140 if (verify)
1141 {
Greg Claytonc982c762010-07-09 20:39:50 +00001142 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001143 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144 // Verify that our original opcode made it back to the inferior
1145 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1146 {
1147 // compare the memory we just read with the original opcode
1148 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1149 {
1150 // SUCCESS
1151 bp_site->SetEnabled(false);
1152 if (log)
1153 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1154 return error;
1155 }
1156 else
1157 {
1158 if (break_op_found)
1159 error.SetErrorString("Failed to restore original opcode.");
1160 }
1161 }
1162 else
1163 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1164 }
1165 }
1166 else
1167 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1168 }
1169 }
1170 else
1171 {
1172 if (log)
1173 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1174 return error;
1175 }
1176
1177 if (log)
1178 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1179 bp_site->GetID(),
1180 (uint64_t)bp_addr,
1181 error.AsCString());
1182 return error;
1183
1184}
1185
Greg Clayton58be07b2011-01-07 06:08:19 +00001186// Comment out line below to disable memory caching
1187#define ENABLE_MEMORY_CACHING
1188// Uncomment to verify memory caching works after making changes to caching code
1189//#define VERIFY_MEMORY_READS
1190
1191#if defined (ENABLE_MEMORY_CACHING)
1192
1193#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194
1195size_t
1196Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1197{
Greg Clayton58be07b2011-01-07 06:08:19 +00001198 // Memory caching is enabled, with debug verification
1199 if (buf && size)
1200 {
1201 // Uncomment the line below to make sure memory caching is working.
1202 // I ran this through the test suite and got no assertions, so I am
1203 // pretty confident this is working well. If any changes are made to
1204 // memory caching, uncomment the line below and test your changes!
1205
1206 // Verify all memory reads by using the cache first, then redundantly
1207 // reading the same memory from the inferior and comparing to make sure
1208 // everything is exactly the same.
1209 std::string verify_buf (size, '\0');
1210 assert (verify_buf.size() == size);
1211 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1212 Error verify_error;
1213 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1214 assert (cache_bytes_read == verify_bytes_read);
1215 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1216 assert (verify_error.Success() == error.Success());
1217 return cache_bytes_read;
1218 }
1219 return 0;
1220}
1221
1222#else // #if defined (VERIFY_MEMORY_READS)
1223
1224size_t
1225Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1226{
1227 // Memory caching enabled, no verification
1228 return m_memory_cache.Read (this, addr, buf, size, error);
1229}
1230
1231#endif // #else for #if defined (VERIFY_MEMORY_READS)
1232
1233#else // #if defined (ENABLE_MEMORY_CACHING)
1234
1235size_t
1236Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1237{
1238 // Memory caching is disabled
1239 return ReadMemoryFromInferior (addr, buf, size, error);
1240}
1241
1242#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1243
1244
1245size_t
1246Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1247{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248 if (buf == NULL || size == 0)
1249 return 0;
1250
1251 size_t bytes_read = 0;
1252 uint8_t *bytes = (uint8_t *)buf;
1253
1254 while (bytes_read < size)
1255 {
1256 const size_t curr_size = size - bytes_read;
1257 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1258 bytes + bytes_read,
1259 curr_size,
1260 error);
1261 bytes_read += curr_bytes_read;
1262 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1263 break;
1264 }
1265
1266 // Replace any software breakpoint opcodes that fall into this range back
1267 // into "buf" before we return
1268 if (bytes_read > 0)
1269 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1270 return bytes_read;
1271}
1272
Greg Clayton58a4c462010-12-16 20:01:20 +00001273uint64_t
1274Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1275{
1276 if (integer_byte_size > sizeof(uint64_t))
1277 {
1278 error.SetErrorString ("unsupported integer size");
1279 }
1280 else
1281 {
1282 uint8_t tmp[sizeof(uint64_t)];
1283 DataExtractor data (tmp, integer_byte_size, GetByteOrder(), GetAddressByteSize());
1284 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1285 {
1286 uint32_t offset = 0;
1287 return data.GetMaxU64 (&offset, integer_byte_size);
1288 }
1289 }
1290 // Any plug-in that doesn't return success a memory read with the number
1291 // of bytes that were requested should be setting the error
1292 assert (error.Fail());
1293 return 0;
1294}
1295
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001296size_t
1297Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1298{
1299 size_t bytes_written = 0;
1300 const uint8_t *bytes = (const uint8_t *)buf;
1301
1302 while (bytes_written < size)
1303 {
1304 const size_t curr_size = size - bytes_written;
1305 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1306 bytes + bytes_written,
1307 curr_size,
1308 error);
1309 bytes_written += curr_bytes_written;
1310 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1311 break;
1312 }
1313 return bytes_written;
1314}
1315
1316size_t
1317Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1318{
Greg Clayton58be07b2011-01-07 06:08:19 +00001319#if defined (ENABLE_MEMORY_CACHING)
1320 m_memory_cache.Flush (addr, size);
1321#endif
1322
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 if (buf == NULL || size == 0)
1324 return 0;
1325 // We need to write any data that would go where any current software traps
1326 // (enabled software breakpoints) any software traps (breakpoints) that we
1327 // may have placed in our tasks memory.
1328
1329 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1330 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1331
1332 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1333 return DoWriteMemory(addr, buf, size, error);
1334
1335 BreakpointSiteList::collection::const_iterator pos;
1336 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001337 addr_t intersect_addr = 0;
1338 size_t intersect_size = 0;
1339 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340 const uint8_t *ubuf = (const uint8_t *)buf;
1341
1342 for (pos = iter; pos != end; ++pos)
1343 {
1344 BreakpointSiteSP bp;
1345 bp = pos->second;
1346
1347 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1348 assert(addr <= intersect_addr && intersect_addr < addr + size);
1349 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1350 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1351
1352 // Check for bytes before this breakpoint
1353 const addr_t curr_addr = addr + bytes_written;
1354 if (intersect_addr > curr_addr)
1355 {
1356 // There are some bytes before this breakpoint that we need to
1357 // just write to memory
1358 size_t curr_size = intersect_addr - curr_addr;
1359 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1360 ubuf + bytes_written,
1361 curr_size,
1362 error);
1363 bytes_written += curr_bytes_written;
1364 if (curr_bytes_written != curr_size)
1365 {
1366 // We weren't able to write all of the requested bytes, we
1367 // are done looping and will return the number of bytes that
1368 // we have written so far.
1369 break;
1370 }
1371 }
1372
1373 // Now write any bytes that would cover up any software breakpoints
1374 // directly into the breakpoint opcode buffer
1375 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1376 bytes_written += intersect_size;
1377 }
1378
1379 // Write any remaining bytes after the last breakpoint if we have any left
1380 if (bytes_written < size)
1381 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1382 ubuf + bytes_written,
1383 size - bytes_written,
1384 error);
1385
1386 return bytes_written;
1387}
1388
1389addr_t
1390Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1391{
1392 // Fixme: we should track the blocks we've allocated, and clean them up...
1393 // We could even do our own allocator here if that ends up being more efficient.
1394 return DoAllocateMemory (size, permissions, error);
1395}
1396
1397Error
1398Process::DeallocateMemory (addr_t ptr)
1399{
1400 return DoDeallocateMemory (ptr);
1401}
1402
1403
1404Error
1405Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1406{
1407 Error error;
1408 error.SetErrorString("watchpoints are not supported");
1409 return error;
1410}
1411
1412Error
1413Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1414{
1415 Error error;
1416 error.SetErrorString("watchpoints are not supported");
1417 return error;
1418}
1419
1420StateType
1421Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1422{
1423 StateType state;
1424 // Now wait for the process to launch and return control to us, and then
1425 // call DidLaunch:
1426 while (1)
1427 {
1428 // FIXME: Might want to put a timeout in here:
1429 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
1430 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
1431 break;
1432 else
1433 HandlePrivateEvent (event_sp);
1434 }
1435 return state;
1436}
1437
1438Error
1439Process::Launch
1440(
1441 char const *argv[],
1442 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00001443 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444 const char *stdin_path,
1445 const char *stdout_path,
1446 const char *stderr_path
1447)
1448{
1449 Error error;
1450 m_target_triple.Clear();
1451 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001452 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001453
1454 Module *exe_module = m_target.GetExecutableModule().get();
1455 if (exe_module)
1456 {
1457 char exec_file_path[PATH_MAX];
1458 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1459 if (exe_module->GetFileSpec().Exists())
1460 {
1461 error = WillLaunch (exe_module);
1462 if (error.Success())
1463 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001464 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465 // The args coming in should not contain the application name, the
1466 // lldb_private::Process class will add this in case the executable
1467 // gets resolved to a different file than was given on the command
1468 // line (like when an applicaiton bundle is specified and will
1469 // resolve to the contained exectuable file, or the file given was
1470 // a symlink or other file system link that resolves to a different
1471 // file).
1472
1473 // Get the resolved exectuable path
1474
1475 // Make a new argument vector
1476 std::vector<const char *> exec_path_plus_argv;
1477 // Append the resolved executable path
1478 exec_path_plus_argv.push_back (exec_file_path);
1479
1480 // Push all args if there are any
1481 if (argv)
1482 {
1483 for (int i = 0; argv[i]; ++i)
1484 exec_path_plus_argv.push_back(argv[i]);
1485 }
1486
1487 // Push a NULL to terminate the args.
1488 exec_path_plus_argv.push_back(NULL);
1489
1490 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00001491 error = DoLaunch (exe_module,
1492 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1493 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00001494 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00001495 stdin_path,
1496 stdout_path,
1497 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498
1499 if (error.Fail())
1500 {
1501 if (GetID() != LLDB_INVALID_PROCESS_ID)
1502 {
1503 SetID (LLDB_INVALID_PROCESS_ID);
1504 const char *error_string = error.AsCString();
1505 if (error_string == NULL)
1506 error_string = "launch failed";
1507 SetExitStatus (-1, error_string);
1508 }
1509 }
1510 else
1511 {
1512 EventSP event_sp;
1513 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1514
1515 if (state == eStateStopped || state == eStateCrashed)
1516 {
1517 DidLaunch ();
1518
1519 // This delays passing the stopped event to listeners till DidLaunch gets
1520 // a chance to complete...
1521 HandlePrivateEvent (event_sp);
1522 StartPrivateStateThread ();
1523 }
1524 else if (state == eStateExited)
1525 {
1526 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1527 // not likely to work, and return an invalid pid.
1528 HandlePrivateEvent (event_sp);
1529 }
1530 }
1531 }
1532 }
1533 else
1534 {
1535 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1536 }
1537 }
1538 return error;
1539}
1540
1541Error
1542Process::CompleteAttach ()
1543{
1544 Error error;
Greg Clayton19388cf2010-10-18 01:45:30 +00001545
1546 if (GetID() == LLDB_INVALID_PROCESS_ID)
1547 {
1548 error.SetErrorString("no process");
1549 }
1550
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551 EventSP event_sp;
1552 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1553 if (state == eStateStopped || state == eStateCrashed)
1554 {
1555 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001556 // Figure out which one is the executable, and set that in our target:
1557 ModuleList &modules = GetTarget().GetImages();
1558
1559 size_t num_modules = modules.GetSize();
1560 for (int i = 0; i < num_modules; i++)
1561 {
1562 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1563 if (module_sp->IsExecutable())
1564 {
1565 ModuleSP exec_module = GetTarget().GetExecutableModule();
1566 if (!exec_module || exec_module != module_sp)
1567 {
1568
1569 GetTarget().SetExecutableModule (module_sp, false);
1570 }
1571 break;
1572 }
1573 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001574
1575 // This delays passing the stopped event to listeners till DidLaunch gets
1576 // a chance to complete...
1577 HandlePrivateEvent(event_sp);
1578 StartPrivateStateThread();
1579 }
1580 else
1581 {
1582 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1583 // not likely to work, and return an invalid pid.
1584 if (state == eStateExited)
1585 HandlePrivateEvent (event_sp);
1586 error.SetErrorStringWithFormat("invalid state after attach: %s",
1587 lldb_private::StateAsCString(state));
1588 }
1589 return error;
1590}
1591
1592Error
1593Process::Attach (lldb::pid_t attach_pid)
1594{
1595
1596 m_target_triple.Clear();
1597 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001598 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001599
Jim Ingham5aee1622010-08-09 23:31:02 +00001600 // Find the process and its architecture. Make sure it matches the architecture
1601 // of the current Target, and if not adjust it.
1602
1603 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1604 if (attach_spec != GetTarget().GetArchitecture())
1605 {
1606 // Set the architecture on the target.
1607 GetTarget().SetArchitecture(attach_spec);
1608 }
1609
Greg Claytonc982c762010-07-09 20:39:50 +00001610 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001611 if (error.Success())
1612 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001613 SetPublicState (eStateAttaching);
1614
Greg Claytonc982c762010-07-09 20:39:50 +00001615 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001616 if (error.Success())
1617 {
1618 error = CompleteAttach();
1619 }
1620 else
1621 {
1622 if (GetID() != LLDB_INVALID_PROCESS_ID)
1623 {
1624 SetID (LLDB_INVALID_PROCESS_ID);
1625 const char *error_string = error.AsCString();
1626 if (error_string == NULL)
1627 error_string = "attach failed";
1628
1629 SetExitStatus(-1, error_string);
1630 }
1631 }
1632 }
1633 return error;
1634}
1635
1636Error
1637Process::Attach (const char *process_name, bool wait_for_launch)
1638{
1639 m_target_triple.Clear();
1640 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001641 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001642
1643 // Find the process and its architecture. Make sure it matches the architecture
1644 // of the current Target, and if not adjust it.
1645
Jim Ingham2ecb7422010-08-17 21:54:19 +00001646 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001647 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001648 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
Greg Clayton19388cf2010-10-18 01:45:30 +00001649 if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
Jim Ingham2ecb7422010-08-17 21:54:19 +00001650 {
1651 // Set the architecture on the target.
1652 GetTarget().SetArchitecture(attach_spec);
1653 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001654 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001655
Greg Claytonc982c762010-07-09 20:39:50 +00001656 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001657 if (error.Success())
1658 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001659 SetPublicState (eStateAttaching);
Greg Claytonc982c762010-07-09 20:39:50 +00001660 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 if (error.Fail())
1662 {
1663 if (GetID() != LLDB_INVALID_PROCESS_ID)
1664 {
1665 SetID (LLDB_INVALID_PROCESS_ID);
1666 const char *error_string = error.AsCString();
1667 if (error_string == NULL)
1668 error_string = "attach failed";
1669
1670 SetExitStatus(-1, error_string);
1671 }
1672 }
1673 else
1674 {
1675 error = CompleteAttach();
1676 }
1677 }
1678 return error;
1679}
1680
1681Error
1682Process::Resume ()
1683{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001684 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001685 if (log)
1686 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1687
1688 Error error (WillResume());
1689 // Tell the process it is about to resume before the thread list
1690 if (error.Success())
1691 {
Johnny Chenc4221e42010-12-02 20:53:05 +00001692 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001693 // can let all of our threads know that they are about to be
1694 // resumed. Threads will each be called with
1695 // Thread::WillResume(StateType) where StateType contains the state
1696 // that they are supposed to have when the process is resumed
1697 // (suspended/running/stepping). Threads should also check
1698 // their resume signal in lldb::Thread::GetResumeSignal()
1699 // to see if they are suppoed to start back up with a signal.
1700 if (m_thread_list.WillResume())
1701 {
1702 error = DoResume();
1703 if (error.Success())
1704 {
1705 DidResume();
1706 m_thread_list.DidResume();
1707 }
1708 }
1709 else
1710 {
1711 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1712 }
1713 }
1714 return error;
1715}
1716
1717Error
1718Process::Halt ()
1719{
1720 Error error (WillHalt());
1721
1722 if (error.Success())
1723 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001724
1725 bool caused_stop = false;
1726 EventSP event_sp;
1727
1728 // Pause our private state thread so we can ensure no one else eats
1729 // the stop event out from under us.
1730 PausePrivateStateThread();
1731
1732 // Ask the process subclass to actually halt our process
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001733 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001735 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001736 // If "caused_stop" is true, then DoHalt stopped the process. If
1737 // "caused_stop" is false, the process was already stopped.
1738 // If the DoHalt caused the process to stop, then we want to catch
1739 // this event and set the interrupted bool to true before we pass
1740 // this along so clients know that the process was interrupted by
1741 // a halt command.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001742 if (caused_stop)
1743 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001744 // Wait for 2 seconds for the process to stop.
1745 TimeValue timeout_time;
1746 timeout_time = TimeValue::Now();
1747 timeout_time.OffsetWithSeconds(2);
1748 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, event_sp);
1749
1750 if (state == eStateInvalid)
1751 {
1752 // We timeout out and didn't get a stop event...
1753 error.SetErrorString ("Halt timed out.");
1754 }
1755 else
1756 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001757 if (StateIsStoppedState (state))
1758 {
1759 // We caused the process to interrupt itself, so mark this
1760 // as such in the stop event so clients can tell an interrupted
1761 // process from a natural stop
1762 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
1763 }
1764 else
1765 {
1766 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1767 if (log)
1768 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
1769 error.SetErrorString ("Did not get stopped event after halt.");
1770 }
1771 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001772 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001773 DidHalt();
1774
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001775 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001776 // Resume our private state thread before we post the event (if any)
1777 ResumePrivateStateThread();
1778
1779 // Post any event we might have consumed. If all goes well, we will have
1780 // stopped the process, intercepted the event and set the interrupted
Jim Inghamf48169b2010-11-30 02:22:11 +00001781 // bool in the event. Post it to the private event queue and that will end up
1782 // correctly setting the state.
Greg Clayton3af9ea52010-11-18 05:57:03 +00001783 if (event_sp)
Caroline Ticeefed6132010-11-19 20:47:54 +00001784 m_private_state_broadcaster.BroadcastEvent(event_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001785
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001786 }
1787 return error;
1788}
1789
1790Error
1791Process::Detach ()
1792{
1793 Error error (WillDetach());
1794
1795 if (error.Success())
1796 {
1797 DisableAllBreakpointSites();
1798 error = DoDetach();
1799 if (error.Success())
1800 {
1801 DidDetach();
1802 StopPrivateStateThread();
1803 }
1804 }
1805 return error;
1806}
1807
1808Error
1809Process::Destroy ()
1810{
1811 Error error (WillDestroy());
1812 if (error.Success())
1813 {
1814 DisableAllBreakpointSites();
1815 error = DoDestroy();
1816 if (error.Success())
1817 {
1818 DidDestroy();
1819 StopPrivateStateThread();
1820 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001821 m_stdio_communication.StopReadThread();
1822 m_stdio_communication.Disconnect();
1823 if (m_process_input_reader && m_process_input_reader->IsActive())
1824 m_target.GetDebugger().PopInputReader (m_process_input_reader);
1825 if (m_process_input_reader)
1826 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001827 }
1828 return error;
1829}
1830
1831Error
1832Process::Signal (int signal)
1833{
1834 Error error (WillSignal());
1835 if (error.Success())
1836 {
1837 error = DoSignal(signal);
1838 if (error.Success())
1839 DidSignal();
1840 }
1841 return error;
1842}
1843
1844UnixSignals &
1845Process::GetUnixSignals ()
1846{
1847 return m_unix_signals;
1848}
1849
1850Target &
1851Process::GetTarget ()
1852{
1853 return m_target;
1854}
1855
1856const Target &
1857Process::GetTarget () const
1858{
1859 return m_target;
1860}
1861
1862uint32_t
1863Process::GetAddressByteSize()
1864{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001865 if (m_addr_byte_size == 0)
1866 return m_target.GetArchitecture().GetAddressByteSize();
1867 return m_addr_byte_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001868}
1869
1870bool
1871Process::ShouldBroadcastEvent (Event *event_ptr)
1872{
1873 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1874 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001875 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876
1877 switch (state)
1878 {
1879 case eStateAttaching:
1880 case eStateLaunching:
1881 case eStateDetached:
1882 case eStateExited:
1883 case eStateUnloaded:
1884 // These events indicate changes in the state of the debugging session, always report them.
1885 return_value = true;
1886 break;
1887 case eStateInvalid:
1888 // We stopped for no apparent reason, don't report it.
1889 return_value = false;
1890 break;
1891 case eStateRunning:
1892 case eStateStepping:
1893 // If we've started the target running, we handle the cases where we
1894 // are already running and where there is a transition from stopped to
1895 // running differently.
1896 // running -> running: Automatically suppress extra running events
1897 // stopped -> running: Report except when there is one or more no votes
1898 // and no yes votes.
1899 SynchronouslyNotifyStateChanged (state);
1900 switch (m_public_state.GetValue())
1901 {
1902 case eStateRunning:
1903 case eStateStepping:
1904 // We always suppress multiple runnings with no PUBLIC stop in between.
1905 return_value = false;
1906 break;
1907 default:
1908 // TODO: make this work correctly. For now always report
1909 // run if we aren't running so we don't miss any runnning
1910 // events. If I run the lldb/test/thread/a.out file and
1911 // break at main.cpp:58, run and hit the breakpoints on
1912 // multiple threads, then somehow during the stepping over
1913 // of all breakpoints no run gets reported.
1914 return_value = true;
1915
1916 // This is a transition from stop to run.
1917 switch (m_thread_list.ShouldReportRun (event_ptr))
1918 {
1919 case eVoteYes:
1920 case eVoteNoOpinion:
1921 return_value = true;
1922 break;
1923 case eVoteNo:
1924 return_value = false;
1925 break;
1926 }
1927 break;
1928 }
1929 break;
1930 case eStateStopped:
1931 case eStateCrashed:
1932 case eStateSuspended:
1933 {
1934 // We've stopped. First see if we're going to restart the target.
1935 // If we are going to stop, then we always broadcast the event.
1936 // 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 +00001937 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001938 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00001940 if (log)
1941 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001942 return true;
1943 }
1944 else
1945 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946 RefreshStateAfterStop ();
1947
1948 if (m_thread_list.ShouldStop (event_ptr) == false)
1949 {
1950 switch (m_thread_list.ShouldReportStop (event_ptr))
1951 {
1952 case eVoteYes:
1953 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00001954 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956 case eVoteNo:
1957 return_value = false;
1958 break;
1959 }
1960
1961 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001962 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963 Resume ();
1964 }
1965 else
1966 {
1967 return_value = true;
1968 SynchronouslyNotifyStateChanged (state);
1969 }
1970 }
1971 }
1972 }
1973
1974 if (log)
1975 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1976 return return_value;
1977}
1978
1979//------------------------------------------------------------------
1980// Thread Queries
1981//------------------------------------------------------------------
1982
1983ThreadList &
1984Process::GetThreadList ()
1985{
1986 return m_thread_list;
1987}
1988
1989const ThreadList &
1990Process::GetThreadList () const
1991{
1992 return m_thread_list;
1993}
1994
1995
1996bool
1997Process::StartPrivateStateThread ()
1998{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001999 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000
2001 if (log)
2002 log->Printf ("Process::%s ( )", __FUNCTION__);
2003
2004 // Create a thread that watches our internal state and controls which
2005 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002006 char thread_name[1024];
2007 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2008 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2010}
2011
2012void
2013Process::PausePrivateStateThread ()
2014{
2015 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2016}
2017
2018void
2019Process::ResumePrivateStateThread ()
2020{
2021 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2022}
2023
2024void
2025Process::StopPrivateStateThread ()
2026{
2027 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2028}
2029
2030void
2031Process::ControlPrivateStateThread (uint32_t signal)
2032{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002033 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034
2035 assert (signal == eBroadcastInternalStateControlStop ||
2036 signal == eBroadcastInternalStateControlPause ||
2037 signal == eBroadcastInternalStateControlResume);
2038
2039 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002040 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002041
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002042 // Signal the private state thread. First we should copy this is case the
2043 // thread starts exiting since the private state thread will NULL this out
2044 // when it exits
2045 const lldb::thread_t private_state_thread = m_private_state_thread;
2046 if (private_state_thread != LLDB_INVALID_HOST_THREAD)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047 {
2048 TimeValue timeout_time;
2049 bool timed_out;
2050
2051 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2052
2053 timeout_time = TimeValue::Now();
2054 timeout_time.OffsetWithSeconds(2);
2055 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2056 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2057
2058 if (signal == eBroadcastInternalStateControlStop)
2059 {
2060 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002061 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062
2063 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002064 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002065 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 }
2067 }
2068}
2069
2070void
2071Process::HandlePrivateEvent (EventSP &event_sp)
2072{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002073 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2075 // See if we should broadcast this state to external clients?
2076 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2077 if (log)
2078 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2079
2080 if (should_broadcast)
2081 {
2082 if (log)
2083 {
2084 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2085 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002086 if (StateIsRunningState (internal_state))
2087 PushProcessInputReader ();
2088 else
2089 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2091 BroadcastEvent (event_sp);
2092 }
2093 else
2094 {
2095 if (log)
2096 {
2097 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2098 }
2099 }
2100}
2101
2102void *
2103Process::PrivateStateThread (void *arg)
2104{
2105 Process *proc = static_cast<Process*> (arg);
2106 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 return result;
2108}
2109
2110void *
2111Process::RunPrivateStateThread ()
2112{
2113 bool control_only = false;
2114 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2115
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002116 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 if (log)
2118 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2119
2120 bool exit_now = false;
2121 while (!exit_now)
2122 {
2123 EventSP event_sp;
2124 WaitForEventsPrivate (NULL, event_sp, control_only);
2125 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2126 {
2127 switch (event_sp->GetType())
2128 {
2129 case eBroadcastInternalStateControlStop:
2130 exit_now = true;
2131 continue; // Go to next loop iteration so we exit without
2132 break; // doing any internal state managment below
2133
2134 case eBroadcastInternalStateControlPause:
2135 control_only = true;
2136 break;
2137
2138 case eBroadcastInternalStateControlResume:
2139 control_only = false;
2140 break;
2141 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002142
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002143 if (log)
2144 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002147 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148 }
2149
2150
2151 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2152
2153 if (internal_state != eStateInvalid)
2154 {
2155 HandlePrivateEvent (event_sp);
2156 }
2157
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002158 if (internal_state == eStateInvalid ||
2159 internal_state == eStateExited ||
2160 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002161 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002162 if (log)
2163 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2164
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002166 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 }
2168
Caroline Tice20ad3c42010-10-29 21:48:37 +00002169 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002170 if (log)
2171 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2172
Greg Clayton6ed95942011-01-22 07:12:45 +00002173 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2174 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002175 return NULL;
2176}
2177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178//------------------------------------------------------------------
2179// Process Event Data
2180//------------------------------------------------------------------
2181
2182Process::ProcessEventData::ProcessEventData () :
2183 EventData (),
2184 m_process_sp (),
2185 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002186 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002187 m_update_state (false),
2188 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002189{
2190}
2191
2192Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2193 EventData (),
2194 m_process_sp (process_sp),
2195 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002196 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002197 m_update_state (false),
2198 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199{
2200}
2201
2202Process::ProcessEventData::~ProcessEventData()
2203{
2204}
2205
2206const ConstString &
2207Process::ProcessEventData::GetFlavorString ()
2208{
2209 static ConstString g_flavor ("Process::ProcessEventData");
2210 return g_flavor;
2211}
2212
2213const ConstString &
2214Process::ProcessEventData::GetFlavor () const
2215{
2216 return ProcessEventData::GetFlavorString ();
2217}
2218
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219void
2220Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2221{
2222 // This function gets called twice for each event, once when the event gets pulled
2223 // off of the private process event queue, and once when it gets pulled off of
2224 // the public event queue. m_update_state is used to distinguish these
2225 // two cases; it is false when we're just pulling it off for private handling,
2226 // and we don't want to do the breakpoint command handling then.
2227
2228 if (!m_update_state)
2229 return;
2230
2231 m_process_sp->SetPublicState (m_state);
2232
2233 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2234 if (m_state == eStateStopped && ! m_restarted)
2235 {
2236 int num_threads = m_process_sp->GetThreadList().GetSize();
2237 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 for (idx = 0; idx < num_threads; ++idx)
2240 {
2241 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2242
Jim Inghamb15bfc72010-10-20 00:39:53 +00002243 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2244 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002246 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247 }
2248 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002249
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002250 // The stop action might restart the target. If it does, then we want to mark that in the
2251 // event so that whoever is receiving it will know to wait for the running event and reflect
2252 // that state appropriately.
2253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 if (m_process_sp->GetPrivateState() == eStateRunning)
2255 SetRestarted(true);
2256 }
2257}
2258
2259void
2260Process::ProcessEventData::Dump (Stream *s) const
2261{
2262 if (m_process_sp)
2263 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2264
2265 s->Printf("state = %s", StateAsCString(GetState()));;
2266}
2267
2268const Process::ProcessEventData *
2269Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2270{
2271 if (event_ptr)
2272 {
2273 const EventData *event_data = event_ptr->GetData();
2274 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2275 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2276 }
2277 return NULL;
2278}
2279
2280ProcessSP
2281Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2282{
2283 ProcessSP process_sp;
2284 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2285 if (data)
2286 process_sp = data->GetProcessSP();
2287 return process_sp;
2288}
2289
2290StateType
2291Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2292{
2293 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2294 if (data == NULL)
2295 return eStateInvalid;
2296 else
2297 return data->GetState();
2298}
2299
2300bool
2301Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2302{
2303 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2304 if (data == NULL)
2305 return false;
2306 else
2307 return data->GetRestarted();
2308}
2309
2310void
2311Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2312{
2313 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2314 if (data != NULL)
2315 data->SetRestarted(new_value);
2316}
2317
2318bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002319Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2320{
2321 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2322 if (data == NULL)
2323 return false;
2324 else
2325 return data->GetInterrupted ();
2326}
2327
2328void
2329Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2330{
2331 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2332 if (data != NULL)
2333 data->SetInterrupted(new_value);
2334}
2335
2336bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2338{
2339 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2340 if (data)
2341 {
2342 data->SetUpdateStateOnRemoval();
2343 return true;
2344 }
2345 return false;
2346}
2347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348Target *
2349Process::CalculateTarget ()
2350{
2351 return &m_target;
2352}
2353
2354Process *
2355Process::CalculateProcess ()
2356{
2357 return this;
2358}
2359
2360Thread *
2361Process::CalculateThread ()
2362{
2363 return NULL;
2364}
2365
2366StackFrame *
2367Process::CalculateStackFrame ()
2368{
2369 return NULL;
2370}
2371
2372void
Greg Clayton0603aa92010-10-04 01:05:56 +00002373Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374{
2375 exe_ctx.target = &m_target;
2376 exe_ctx.process = this;
2377 exe_ctx.thread = NULL;
2378 exe_ctx.frame = NULL;
2379}
2380
2381lldb::ProcessSP
2382Process::GetSP ()
2383{
2384 return GetTarget().GetProcessSP();
2385}
2386
Jim Ingham5aee1622010-08-09 23:31:02 +00002387uint32_t
2388Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2389{
2390 return 0;
2391}
2392
2393ArchSpec
2394Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2395{
2396 return Host::GetArchSpecForExistingProcess (pid);
2397}
2398
2399ArchSpec
2400Process::GetArchSpecForExistingProcess (const char *process_name)
2401{
2402 return Host::GetArchSpecForExistingProcess (process_name);
2403}
2404
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002405void
2406Process::AppendSTDOUT (const char * s, size_t len)
2407{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002408 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002409 m_stdout_data.append (s, len);
2410
Greg Claytona9ff3062010-12-05 19:16:56 +00002411 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002412}
2413
2414void
2415Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2416{
2417 Process *process = (Process *) baton;
2418 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2419}
2420
2421size_t
2422Process::ProcessInputReaderCallback (void *baton,
2423 InputReader &reader,
2424 lldb::InputReaderAction notification,
2425 const char *bytes,
2426 size_t bytes_len)
2427{
2428 Process *process = (Process *) baton;
2429
2430 switch (notification)
2431 {
2432 case eInputReaderActivate:
2433 break;
2434
2435 case eInputReaderDeactivate:
2436 break;
2437
2438 case eInputReaderReactivate:
2439 break;
2440
2441 case eInputReaderGotToken:
2442 {
2443 Error error;
2444 process->PutSTDIN (bytes, bytes_len, error);
2445 }
2446 break;
2447
Caroline Ticeefed6132010-11-19 20:47:54 +00002448 case eInputReaderInterrupt:
2449 process->Halt ();
2450 break;
2451
2452 case eInputReaderEndOfFile:
2453 process->AppendSTDOUT ("^D", 2);
2454 break;
2455
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002456 case eInputReaderDone:
2457 break;
2458
2459 }
2460
2461 return bytes_len;
2462}
2463
2464void
2465Process::ResetProcessInputReader ()
2466{
2467 m_process_input_reader.reset();
2468}
2469
2470void
2471Process::SetUpProcessInputReader (int file_descriptor)
2472{
2473 // First set up the Read Thread for reading/handling process I/O
2474
2475 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2476
2477 if (conn_ap.get())
2478 {
2479 m_stdio_communication.SetConnection (conn_ap.release());
2480 if (m_stdio_communication.IsConnected())
2481 {
2482 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2483 m_stdio_communication.StartReadThread();
2484
2485 // Now read thread is set up, set up input reader.
2486
2487 if (!m_process_input_reader.get())
2488 {
2489 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2490 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2491 this,
2492 eInputReaderGranularityByte,
2493 NULL,
2494 NULL,
2495 false));
2496
2497 if (err.Fail())
2498 m_process_input_reader.reset();
2499 }
2500 }
2501 }
2502}
2503
2504void
2505Process::PushProcessInputReader ()
2506{
2507 if (m_process_input_reader && !m_process_input_reader->IsActive())
2508 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2509}
2510
2511void
2512Process::PopProcessInputReader ()
2513{
2514 if (m_process_input_reader && m_process_input_reader->IsActive())
2515 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2516}
2517
Greg Clayton99d0faf2010-11-18 23:32:35 +00002518
2519void
2520Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002521{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002522 UserSettingsControllerSP &usc = GetSettingsController();
2523 usc.reset (new SettingsController);
2524 UserSettingsController::InitializeSettingsController (usc,
2525 SettingsController::global_settings_table,
2526 SettingsController::instance_settings_table);
2527}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002528
Greg Clayton99d0faf2010-11-18 23:32:35 +00002529void
2530Process::Terminate ()
2531{
2532 UserSettingsControllerSP &usc = GetSettingsController();
2533 UserSettingsController::FinalizeSettingsController (usc);
2534 usc.reset();
2535}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002536
Greg Clayton99d0faf2010-11-18 23:32:35 +00002537UserSettingsControllerSP &
2538Process::GetSettingsController ()
2539{
2540 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002541 return g_settings_controller;
2542}
2543
Caroline Tice1559a462010-09-27 00:30:10 +00002544void
2545Process::UpdateInstanceName ()
2546{
2547 ModuleSP module_sp = GetTarget().GetExecutableModule();
2548 if (module_sp)
2549 {
2550 StreamString sstr;
2551 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2552
Greg Claytondbe54502010-11-19 03:46:01 +00002553 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002554 sstr.GetData());
2555 }
2556}
2557
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002558ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002559Process::RunThreadPlan (ExecutionContext &exe_ctx,
2560 lldb::ThreadPlanSP &thread_plan_sp,
2561 bool stop_others,
2562 bool try_all_threads,
2563 bool discard_on_error,
2564 uint32_t single_thread_timeout_usec,
2565 Stream &errors)
2566{
2567 ExecutionResults return_value = eExecutionSetupError;
2568
Jim Ingham77787032011-01-20 02:03:18 +00002569 if (thread_plan_sp.get() == NULL)
2570 {
2571 errors.Printf("RunThreadPlan called with empty thread plan.");
2572 return lldb::eExecutionSetupError;
2573 }
2574
Jim Inghamf48169b2010-11-30 02:22:11 +00002575 // Save this value for restoration of the execution context after we run
2576 uint32_t tid = exe_ctx.thread->GetIndexID();
2577
2578 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2579 // so we should arrange to reset them as well.
2580
2581 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2582 lldb::StackFrameSP selected_frame_sp;
2583
2584 uint32_t selected_tid;
2585 if (selected_thread_sp != NULL)
2586 {
2587 selected_tid = selected_thread_sp->GetIndexID();
2588 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2589 }
2590 else
2591 {
2592 selected_tid = LLDB_INVALID_THREAD_ID;
2593 }
2594
2595 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2596
2597 Listener listener("ClangFunction temporary listener");
2598 exe_ctx.process->HijackProcessEvents(&listener);
2599
Jim Ingham77787032011-01-20 02:03:18 +00002600 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2601 if (log)
2602 {
2603 StreamString s;
2604 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
2605 log->Printf ("Resuming thread 0x%x to run thread plan \"%s\".", tid, s.GetData());
2606 }
2607
Jim Inghamf48169b2010-11-30 02:22:11 +00002608 Error resume_error = exe_ctx.process->Resume ();
2609 if (!resume_error.Success())
2610 {
2611 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2612 exe_ctx.process->RestoreProcessEvents();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002613 return lldb::eExecutionSetupError;
Jim Inghamf48169b2010-11-30 02:22:11 +00002614 }
2615
2616 // We need to call the function synchronously, so spin waiting for it to return.
2617 // If we get interrupted while executing, we're going to lose our context, and
2618 // won't be able to gather the result at this point.
2619 // We set the timeout AFTER the resume, since the resume takes some time and we
2620 // don't want to charge that to the timeout.
2621
2622 TimeValue* timeout_ptr = NULL;
2623 TimeValue real_timeout;
2624
2625 if (single_thread_timeout_usec != 0)
2626 {
2627 real_timeout = TimeValue::Now();
2628 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2629 timeout_ptr = &real_timeout;
2630 }
2631
Jim Inghamf48169b2010-11-30 02:22:11 +00002632 while (1)
2633 {
2634 lldb::EventSP event_sp;
2635 lldb::StateType stop_state = lldb::eStateInvalid;
2636 // Now wait for the process to stop again:
2637 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2638
2639 if (!got_event)
2640 {
2641 // Right now this is the only way to tell we've timed out...
2642 // We should interrupt the process here...
2643 // Not really sure what to do if Halt fails here...
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002644 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002645 if (try_all_threads)
2646 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2647 single_thread_timeout_usec);
2648 else
2649 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2650 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002651 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002652
Jim Inghame22e88b2011-01-22 01:30:53 +00002653 Error halt_error = exe_ctx.process->Halt();
2654
2655 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002656 {
2657 timeout_ptr = NULL;
2658 if (log)
2659 log->Printf ("Halt succeeded.");
2660
2661 // Between the time that we got the timeout and the time we halted, but target
2662 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2663 // timeout to
2664 got_event = listener.WaitForEvent(NULL, event_sp);
2665
2666 if (got_event)
2667 {
2668 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2669 if (log)
2670 {
2671 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2672 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2673 log->Printf (" Event was the Halt interruption event.");
2674 }
2675
2676 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2677 {
2678 if (log)
2679 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002680 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002681 break;
2682 }
2683
2684 if (try_all_threads
2685 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2686 {
2687
2688 thread_plan_sp->SetStopOthers (false);
2689 if (log)
2690 log->Printf ("About to resume.");
2691
2692 exe_ctx.process->Resume();
2693 continue;
2694 }
2695 else
2696 {
2697 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002698 return lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002699 }
2700 }
2701 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002702 else
2703 {
2704
2705 if (log)
2706 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2707 halt_error.AsCString());
2708
2709 if (single_thread_timeout_usec != 0)
2710 {
2711 real_timeout = TimeValue::Now();
2712 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2713 timeout_ptr = &real_timeout;
2714 }
2715 continue;
2716 }
2717
Jim Inghamf48169b2010-11-30 02:22:11 +00002718 }
2719
2720 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2721 if (log)
2722 log->Printf("Got event: %s.", StateAsCString(stop_state));
2723
2724 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2725 continue;
2726
2727 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2728 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002729 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002730 break;
2731 }
2732 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2733 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002734 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00002735 break;
2736 }
2737 else
2738 {
2739 if (log)
2740 {
2741 StreamString s;
Jim Inghame22e88b2011-01-22 01:30:53 +00002742 if (event_sp)
2743 event_sp->Dump (&s);
2744 else
2745 {
2746 log->Printf ("Stop event that interrupted us is NULL.");
2747 }
2748
Jim Inghamf48169b2010-11-30 02:22:11 +00002749 StreamString ts;
2750
2751 const char *event_explanation;
2752
2753 do
2754 {
2755 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2756
2757 if (!event_data)
2758 {
2759 event_explanation = "<no event data>";
2760 break;
2761 }
2762
2763 Process *process = event_data->GetProcessSP().get();
2764
2765 if (!process)
2766 {
2767 event_explanation = "<no process>";
2768 break;
2769 }
2770
2771 ThreadList &thread_list = process->GetThreadList();
2772
2773 uint32_t num_threads = thread_list.GetSize();
2774 uint32_t thread_index;
2775
2776 ts.Printf("<%u threads> ", num_threads);
2777
2778 for (thread_index = 0;
2779 thread_index < num_threads;
2780 ++thread_index)
2781 {
2782 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2783
2784 if (!thread)
2785 {
2786 ts.Printf("<?> ");
2787 continue;
2788 }
2789
Jim Inghame22e88b2011-01-22 01:30:53 +00002790 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton5ccbd292011-01-06 22:15:06 +00002791 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Inghamf48169b2010-11-30 02:22:11 +00002792
2793 if (register_context)
2794 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2795 else
2796 ts.Printf("[ip unknown] ");
2797
2798 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2799 if (stop_info_sp)
2800 {
2801 const char *stop_desc = stop_info_sp->GetDescription();
2802 if (stop_desc)
2803 ts.PutCString (stop_desc);
2804 }
2805 ts.Printf(">");
2806 }
2807
2808 event_explanation = ts.GetData();
2809 } while (0);
2810
Jim Inghame22e88b2011-01-22 01:30:53 +00002811 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2812 if (!GetThreadList().ShouldStop(event_sp.get()))
2813 {
2814 if (log)
2815 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2816 s.GetData(), event_explanation);
2817 if (single_thread_timeout_usec != 0)
2818 {
2819 real_timeout = TimeValue::Now();
2820 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2821 timeout_ptr = &real_timeout;
2822 }
2823
2824 continue;
2825 }
2826 else
2827 {
2828 if (log)
2829 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2830 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002831 }
2832
2833 if (discard_on_error && thread_plan_sp)
2834 {
2835 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2836 }
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002837 return_value = lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002838 break;
2839 }
2840 }
2841
2842 if (exe_ctx.process)
2843 exe_ctx.process->RestoreProcessEvents ();
2844
2845 // Thread we ran the function in may have gone away because we ran the target
2846 // Check that it's still there.
2847 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2848 if (exe_ctx.thread)
2849 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2850
2851 // Also restore the current process'es selected frame & thread, since this function calling may
2852 // be done behind the user's back.
2853
2854 if (selected_tid != LLDB_INVALID_THREAD_ID)
2855 {
2856 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2857 {
2858 // We were able to restore the selected thread, now restore the frame:
2859 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2860 }
2861 }
2862
2863 return return_value;
2864}
2865
2866const char *
2867Process::ExecutionResultAsCString (ExecutionResults result)
2868{
2869 const char *result_name;
2870
2871 switch (result)
2872 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002873 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002874 result_name = "eExecutionCompleted";
2875 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002876 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00002877 result_name = "eExecutionDiscarded";
2878 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002879 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002880 result_name = "eExecutionInterrupted";
2881 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002882 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00002883 result_name = "eExecutionSetupError";
2884 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002885 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00002886 result_name = "eExecutionTimedOut";
2887 break;
2888 }
2889 return result_name;
2890}
2891
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002892//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002893// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002894//--------------------------------------------------------------
2895
Greg Clayton1b654882010-09-19 02:33:57 +00002896Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002897 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002898{
Greg Clayton85851dd2010-12-04 00:10:17 +00002899 m_default_settings.reset (new ProcessInstanceSettings (*this,
2900 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002901 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002902}
2903
Greg Clayton1b654882010-09-19 02:33:57 +00002904Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002905{
2906}
2907
2908lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002909Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002910{
Greg Claytondbe54502010-11-19 03:46:01 +00002911 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2912 false,
2913 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002914 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2915 return new_settings_sp;
2916}
2917
2918//--------------------------------------------------------------
2919// class ProcessInstanceSettings
2920//--------------------------------------------------------------
2921
Greg Clayton85851dd2010-12-04 00:10:17 +00002922ProcessInstanceSettings::ProcessInstanceSettings
2923(
2924 UserSettingsController &owner,
2925 bool live_instance,
2926 const char *name
2927) :
2928 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002929 m_run_args (),
2930 m_env_vars (),
2931 m_input_path (),
2932 m_output_path (),
2933 m_error_path (),
2934 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00002935 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00002936 m_disable_stdio (false),
2937 m_inherit_host_env (true),
2938 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002939{
Caroline Ticef20e8232010-09-09 18:26:37 +00002940 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2941 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2942 // 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 +00002943 // This is true for CreateInstanceName() too.
2944
2945 if (GetInstanceName () == InstanceSettings::InvalidName())
2946 {
2947 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2948 m_owner.RegisterInstanceSettings (this);
2949 }
Caroline Ticef20e8232010-09-09 18:26:37 +00002950
2951 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002952 {
2953 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2954 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00002955 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002956 }
2957}
2958
2959ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00002960 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002961 m_run_args (rhs.m_run_args),
2962 m_env_vars (rhs.m_env_vars),
2963 m_input_path (rhs.m_input_path),
2964 m_output_path (rhs.m_output_path),
2965 m_error_path (rhs.m_error_path),
2966 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00002967 m_disable_aslr (rhs.m_disable_aslr),
2968 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002969{
2970 if (m_instance_name != InstanceSettings::GetDefaultName())
2971 {
2972 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2973 CopyInstanceSettings (pending_settings,false);
2974 m_owner.RemovePendingSettings (m_instance_name);
2975 }
2976}
2977
2978ProcessInstanceSettings::~ProcessInstanceSettings ()
2979{
2980}
2981
2982ProcessInstanceSettings&
2983ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2984{
2985 if (this != &rhs)
2986 {
2987 m_run_args = rhs.m_run_args;
2988 m_env_vars = rhs.m_env_vars;
2989 m_input_path = rhs.m_input_path;
2990 m_output_path = rhs.m_output_path;
2991 m_error_path = rhs.m_error_path;
2992 m_plugin = rhs.m_plugin;
2993 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00002994 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00002995 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002996 }
2997
2998 return *this;
2999}
3000
3001
3002void
3003ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3004 const char *index_value,
3005 const char *value,
3006 const ConstString &instance_name,
3007 const SettingEntry &entry,
3008 lldb::VarSetOperationType op,
3009 Error &err,
3010 bool pending)
3011{
3012 if (var_name == RunArgsVarName())
3013 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3014 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003015 {
3016 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003017 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003018 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003019 else if (var_name == InputPathVarName())
3020 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3021 else if (var_name == OutputPathVarName())
3022 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3023 else if (var_name == ErrorPathVarName())
3024 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3025 else if (var_name == PluginVarName())
3026 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003027 else if (var_name == InheritHostEnvVarName())
3028 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003029 else if (var_name == DisableASLRVarName())
3030 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003031 else if (var_name == DisableSTDIOVarName ())
3032 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003033}
3034
3035void
3036ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3037 bool pending)
3038{
3039 if (new_settings.get() == NULL)
3040 return;
3041
3042 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3043
3044 m_run_args = new_process_settings->m_run_args;
3045 m_env_vars = new_process_settings->m_env_vars;
3046 m_input_path = new_process_settings->m_input_path;
3047 m_output_path = new_process_settings->m_output_path;
3048 m_error_path = new_process_settings->m_error_path;
3049 m_plugin = new_process_settings->m_plugin;
3050 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003051 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003052}
3053
Caroline Tice12cecd72010-09-20 21:37:42 +00003054bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003055ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3056 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003057 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003058 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003059{
3060 if (var_name == RunArgsVarName())
3061 {
3062 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003063 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003064 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3065 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003066 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003067 }
3068 else if (var_name == EnvVarsVarName())
3069 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003070 GetHostEnvironmentIfNeeded ();
3071
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003072 if (m_env_vars.size() > 0)
3073 {
3074 std::map<std::string, std::string>::iterator pos;
3075 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3076 {
3077 StreamString value_str;
3078 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3079 value.AppendString (value_str.GetData());
3080 }
3081 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003082 }
3083 else if (var_name == InputPathVarName())
3084 {
3085 value.AppendString (m_input_path.c_str());
3086 }
3087 else if (var_name == OutputPathVarName())
3088 {
3089 value.AppendString (m_output_path.c_str());
3090 }
3091 else if (var_name == ErrorPathVarName())
3092 {
3093 value.AppendString (m_error_path.c_str());
3094 }
3095 else if (var_name == PluginVarName())
3096 {
3097 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3098 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003099 else if (var_name == InheritHostEnvVarName())
3100 {
3101 if (m_inherit_host_env)
3102 value.AppendString ("true");
3103 else
3104 value.AppendString ("false");
3105 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003106 else if (var_name == DisableASLRVarName())
3107 {
3108 if (m_disable_aslr)
3109 value.AppendString ("true");
3110 else
3111 value.AppendString ("false");
3112 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003113 else if (var_name == DisableSTDIOVarName())
3114 {
3115 if (m_disable_stdio)
3116 value.AppendString ("true");
3117 else
3118 value.AppendString ("false");
3119 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003120 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003121 {
3122 if (err)
3123 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3124 return false;
3125 }
3126 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003127}
3128
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003129const ConstString
3130ProcessInstanceSettings::CreateInstanceName ()
3131{
3132 static int instance_count = 1;
3133 StreamString sstr;
3134
3135 sstr.Printf ("process_%d", instance_count);
3136 ++instance_count;
3137
3138 const ConstString ret_val (sstr.GetData());
3139 return ret_val;
3140}
3141
3142const ConstString &
3143ProcessInstanceSettings::RunArgsVarName ()
3144{
3145 static ConstString run_args_var_name ("run-args");
3146
3147 return run_args_var_name;
3148}
3149
3150const ConstString &
3151ProcessInstanceSettings::EnvVarsVarName ()
3152{
3153 static ConstString env_vars_var_name ("env-vars");
3154
3155 return env_vars_var_name;
3156}
3157
3158const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003159ProcessInstanceSettings::InheritHostEnvVarName ()
3160{
3161 static ConstString g_name ("inherit-env");
3162
3163 return g_name;
3164}
3165
3166const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003167ProcessInstanceSettings::InputPathVarName ()
3168{
3169 static ConstString input_path_var_name ("input-path");
3170
3171 return input_path_var_name;
3172}
3173
3174const ConstString &
3175ProcessInstanceSettings::OutputPathVarName ()
3176{
Caroline Tice49e27372010-09-07 18:35:40 +00003177 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003178
3179 return output_path_var_name;
3180}
3181
3182const ConstString &
3183ProcessInstanceSettings::ErrorPathVarName ()
3184{
Caroline Tice49e27372010-09-07 18:35:40 +00003185 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003186
3187 return error_path_var_name;
3188}
3189
3190const ConstString &
3191ProcessInstanceSettings::PluginVarName ()
3192{
3193 static ConstString plugin_var_name ("plugin");
3194
3195 return plugin_var_name;
3196}
3197
3198
3199const ConstString &
3200ProcessInstanceSettings::DisableASLRVarName ()
3201{
3202 static ConstString disable_aslr_var_name ("disable-aslr");
3203
3204 return disable_aslr_var_name;
3205}
3206
Caroline Ticef8da8632010-12-03 18:46:09 +00003207const ConstString &
3208ProcessInstanceSettings::DisableSTDIOVarName ()
3209{
3210 static ConstString disable_stdio_var_name ("disable-stdio");
3211
3212 return disable_stdio_var_name;
3213}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003214
3215//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003216// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003217//--------------------------------------------------
3218
3219SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003220Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003221{
3222 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3223 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3224};
3225
3226
3227lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003228Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003229{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003230 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3231 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3232 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003233};
3234
3235SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003236Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003237{
Greg Clayton85851dd2010-12-04 00:10:17 +00003238 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3239 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3240 { "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." },
3241 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3242 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3243 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3244 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3245 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3246 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3247 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3248 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003249};
3250
3251
Jim Ingham5aee1622010-08-09 23:31:02 +00003252