blob: dab34765ef53c1e7e02edcffd419ae884ccca2d7 [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)
2040 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
2041
2042 // Signal the private state thread
2043 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
2044 {
2045 TimeValue timeout_time;
2046 bool timed_out;
2047
2048 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2049
2050 timeout_time = TimeValue::Now();
2051 timeout_time.OffsetWithSeconds(2);
2052 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2053 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2054
2055 if (signal == eBroadcastInternalStateControlStop)
2056 {
2057 if (timed_out)
2058 Host::ThreadCancel (m_private_state_thread, NULL);
2059
2060 thread_result_t result = NULL;
2061 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002062 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002063 }
2064 }
2065}
2066
2067void
2068Process::HandlePrivateEvent (EventSP &event_sp)
2069{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002070 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002071 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2072 // See if we should broadcast this state to external clients?
2073 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2074 if (log)
2075 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
2076
2077 if (should_broadcast)
2078 {
2079 if (log)
2080 {
2081 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
2082 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002083 if (StateIsRunningState (internal_state))
2084 PushProcessInputReader ();
2085 else
2086 PopProcessInputReader ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002087 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2088 BroadcastEvent (event_sp);
2089 }
2090 else
2091 {
2092 if (log)
2093 {
2094 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
2095 }
2096 }
2097}
2098
2099void *
2100Process::PrivateStateThread (void *arg)
2101{
2102 Process *proc = static_cast<Process*> (arg);
2103 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104 return result;
2105}
2106
2107void *
2108Process::RunPrivateStateThread ()
2109{
2110 bool control_only = false;
2111 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2112
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002113 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002114 if (log)
2115 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2116
2117 bool exit_now = false;
2118 while (!exit_now)
2119 {
2120 EventSP event_sp;
2121 WaitForEventsPrivate (NULL, event_sp, control_only);
2122 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2123 {
2124 switch (event_sp->GetType())
2125 {
2126 case eBroadcastInternalStateControlStop:
2127 exit_now = true;
2128 continue; // Go to next loop iteration so we exit without
2129 break; // doing any internal state managment below
2130
2131 case eBroadcastInternalStateControlPause:
2132 control_only = true;
2133 break;
2134
2135 case eBroadcastInternalStateControlResume:
2136 control_only = false;
2137 break;
2138 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002139
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002140 if (log)
2141 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002144 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 }
2146
2147
2148 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2149
2150 if (internal_state != eStateInvalid)
2151 {
2152 HandlePrivateEvent (event_sp);
2153 }
2154
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002155 if (internal_state == eStateInvalid ||
2156 internal_state == eStateExited ||
2157 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002158 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002159 if (log)
2160 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002163 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164 }
2165
Caroline Tice20ad3c42010-10-29 21:48:37 +00002166 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 if (log)
2168 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2169
Greg Clayton6ed95942011-01-22 07:12:45 +00002170 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2171 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002172 return NULL;
2173}
2174
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002175//------------------------------------------------------------------
2176// Process Event Data
2177//------------------------------------------------------------------
2178
2179Process::ProcessEventData::ProcessEventData () :
2180 EventData (),
2181 m_process_sp (),
2182 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002183 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002184 m_update_state (false),
2185 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186{
2187}
2188
2189Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2190 EventData (),
2191 m_process_sp (process_sp),
2192 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002193 m_restarted (false),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002194 m_update_state (false),
2195 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002196{
2197}
2198
2199Process::ProcessEventData::~ProcessEventData()
2200{
2201}
2202
2203const ConstString &
2204Process::ProcessEventData::GetFlavorString ()
2205{
2206 static ConstString g_flavor ("Process::ProcessEventData");
2207 return g_flavor;
2208}
2209
2210const ConstString &
2211Process::ProcessEventData::GetFlavor () const
2212{
2213 return ProcessEventData::GetFlavorString ();
2214}
2215
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002216void
2217Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2218{
2219 // This function gets called twice for each event, once when the event gets pulled
2220 // off of the private process event queue, and once when it gets pulled off of
2221 // the public event queue. m_update_state is used to distinguish these
2222 // two cases; it is false when we're just pulling it off for private handling,
2223 // and we don't want to do the breakpoint command handling then.
2224
2225 if (!m_update_state)
2226 return;
2227
2228 m_process_sp->SetPublicState (m_state);
2229
2230 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2231 if (m_state == eStateStopped && ! m_restarted)
2232 {
2233 int num_threads = m_process_sp->GetThreadList().GetSize();
2234 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002235
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 for (idx = 0; idx < num_threads; ++idx)
2237 {
2238 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2239
Jim Inghamb15bfc72010-10-20 00:39:53 +00002240 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2241 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002243 stop_info_sp->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002244 }
2245 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00002246
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00002247 // The stop action might restart the target. If it does, then we want to mark that in the
2248 // event so that whoever is receiving it will know to wait for the running event and reflect
2249 // that state appropriately.
2250
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 if (m_process_sp->GetPrivateState() == eStateRunning)
2252 SetRestarted(true);
2253 }
2254}
2255
2256void
2257Process::ProcessEventData::Dump (Stream *s) const
2258{
2259 if (m_process_sp)
2260 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2261
2262 s->Printf("state = %s", StateAsCString(GetState()));;
2263}
2264
2265const Process::ProcessEventData *
2266Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2267{
2268 if (event_ptr)
2269 {
2270 const EventData *event_data = event_ptr->GetData();
2271 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2272 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2273 }
2274 return NULL;
2275}
2276
2277ProcessSP
2278Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2279{
2280 ProcessSP process_sp;
2281 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2282 if (data)
2283 process_sp = data->GetProcessSP();
2284 return process_sp;
2285}
2286
2287StateType
2288Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2289{
2290 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2291 if (data == NULL)
2292 return eStateInvalid;
2293 else
2294 return data->GetState();
2295}
2296
2297bool
2298Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2299{
2300 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2301 if (data == NULL)
2302 return false;
2303 else
2304 return data->GetRestarted();
2305}
2306
2307void
2308Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2309{
2310 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2311 if (data != NULL)
2312 data->SetRestarted(new_value);
2313}
2314
2315bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002316Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2317{
2318 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2319 if (data == NULL)
2320 return false;
2321 else
2322 return data->GetInterrupted ();
2323}
2324
2325void
2326Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2327{
2328 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2329 if (data != NULL)
2330 data->SetInterrupted(new_value);
2331}
2332
2333bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2335{
2336 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2337 if (data)
2338 {
2339 data->SetUpdateStateOnRemoval();
2340 return true;
2341 }
2342 return false;
2343}
2344
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345Target *
2346Process::CalculateTarget ()
2347{
2348 return &m_target;
2349}
2350
2351Process *
2352Process::CalculateProcess ()
2353{
2354 return this;
2355}
2356
2357Thread *
2358Process::CalculateThread ()
2359{
2360 return NULL;
2361}
2362
2363StackFrame *
2364Process::CalculateStackFrame ()
2365{
2366 return NULL;
2367}
2368
2369void
Greg Clayton0603aa92010-10-04 01:05:56 +00002370Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371{
2372 exe_ctx.target = &m_target;
2373 exe_ctx.process = this;
2374 exe_ctx.thread = NULL;
2375 exe_ctx.frame = NULL;
2376}
2377
2378lldb::ProcessSP
2379Process::GetSP ()
2380{
2381 return GetTarget().GetProcessSP();
2382}
2383
Jim Ingham5aee1622010-08-09 23:31:02 +00002384uint32_t
2385Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2386{
2387 return 0;
2388}
2389
2390ArchSpec
2391Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2392{
2393 return Host::GetArchSpecForExistingProcess (pid);
2394}
2395
2396ArchSpec
2397Process::GetArchSpecForExistingProcess (const char *process_name)
2398{
2399 return Host::GetArchSpecForExistingProcess (process_name);
2400}
2401
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002402void
2403Process::AppendSTDOUT (const char * s, size_t len)
2404{
Greg Clayton3af9ea52010-11-18 05:57:03 +00002405 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002406 m_stdout_data.append (s, len);
2407
Greg Claytona9ff3062010-12-05 19:16:56 +00002408 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002409}
2410
2411void
2412Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2413{
2414 Process *process = (Process *) baton;
2415 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2416}
2417
2418size_t
2419Process::ProcessInputReaderCallback (void *baton,
2420 InputReader &reader,
2421 lldb::InputReaderAction notification,
2422 const char *bytes,
2423 size_t bytes_len)
2424{
2425 Process *process = (Process *) baton;
2426
2427 switch (notification)
2428 {
2429 case eInputReaderActivate:
2430 break;
2431
2432 case eInputReaderDeactivate:
2433 break;
2434
2435 case eInputReaderReactivate:
2436 break;
2437
2438 case eInputReaderGotToken:
2439 {
2440 Error error;
2441 process->PutSTDIN (bytes, bytes_len, error);
2442 }
2443 break;
2444
Caroline Ticeefed6132010-11-19 20:47:54 +00002445 case eInputReaderInterrupt:
2446 process->Halt ();
2447 break;
2448
2449 case eInputReaderEndOfFile:
2450 process->AppendSTDOUT ("^D", 2);
2451 break;
2452
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002453 case eInputReaderDone:
2454 break;
2455
2456 }
2457
2458 return bytes_len;
2459}
2460
2461void
2462Process::ResetProcessInputReader ()
2463{
2464 m_process_input_reader.reset();
2465}
2466
2467void
2468Process::SetUpProcessInputReader (int file_descriptor)
2469{
2470 // First set up the Read Thread for reading/handling process I/O
2471
2472 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2473
2474 if (conn_ap.get())
2475 {
2476 m_stdio_communication.SetConnection (conn_ap.release());
2477 if (m_stdio_communication.IsConnected())
2478 {
2479 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2480 m_stdio_communication.StartReadThread();
2481
2482 // Now read thread is set up, set up input reader.
2483
2484 if (!m_process_input_reader.get())
2485 {
2486 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2487 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2488 this,
2489 eInputReaderGranularityByte,
2490 NULL,
2491 NULL,
2492 false));
2493
2494 if (err.Fail())
2495 m_process_input_reader.reset();
2496 }
2497 }
2498 }
2499}
2500
2501void
2502Process::PushProcessInputReader ()
2503{
2504 if (m_process_input_reader && !m_process_input_reader->IsActive())
2505 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2506}
2507
2508void
2509Process::PopProcessInputReader ()
2510{
2511 if (m_process_input_reader && m_process_input_reader->IsActive())
2512 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2513}
2514
Greg Clayton99d0faf2010-11-18 23:32:35 +00002515
2516void
2517Process::Initialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002518{
Greg Clayton99d0faf2010-11-18 23:32:35 +00002519 UserSettingsControllerSP &usc = GetSettingsController();
2520 usc.reset (new SettingsController);
2521 UserSettingsController::InitializeSettingsController (usc,
2522 SettingsController::global_settings_table,
2523 SettingsController::instance_settings_table);
2524}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002525
Greg Clayton99d0faf2010-11-18 23:32:35 +00002526void
2527Process::Terminate ()
2528{
2529 UserSettingsControllerSP &usc = GetSettingsController();
2530 UserSettingsController::FinalizeSettingsController (usc);
2531 usc.reset();
2532}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002533
Greg Clayton99d0faf2010-11-18 23:32:35 +00002534UserSettingsControllerSP &
2535Process::GetSettingsController ()
2536{
2537 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002538 return g_settings_controller;
2539}
2540
Caroline Tice1559a462010-09-27 00:30:10 +00002541void
2542Process::UpdateInstanceName ()
2543{
2544 ModuleSP module_sp = GetTarget().GetExecutableModule();
2545 if (module_sp)
2546 {
2547 StreamString sstr;
2548 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2549
Greg Claytondbe54502010-11-19 03:46:01 +00002550 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1559a462010-09-27 00:30:10 +00002551 sstr.GetData());
2552 }
2553}
2554
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002555ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00002556Process::RunThreadPlan (ExecutionContext &exe_ctx,
2557 lldb::ThreadPlanSP &thread_plan_sp,
2558 bool stop_others,
2559 bool try_all_threads,
2560 bool discard_on_error,
2561 uint32_t single_thread_timeout_usec,
2562 Stream &errors)
2563{
2564 ExecutionResults return_value = eExecutionSetupError;
2565
Jim Ingham77787032011-01-20 02:03:18 +00002566 if (thread_plan_sp.get() == NULL)
2567 {
2568 errors.Printf("RunThreadPlan called with empty thread plan.");
2569 return lldb::eExecutionSetupError;
2570 }
2571
Jim Inghamf48169b2010-11-30 02:22:11 +00002572 // Save this value for restoration of the execution context after we run
2573 uint32_t tid = exe_ctx.thread->GetIndexID();
2574
2575 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2576 // so we should arrange to reset them as well.
2577
2578 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2579 lldb::StackFrameSP selected_frame_sp;
2580
2581 uint32_t selected_tid;
2582 if (selected_thread_sp != NULL)
2583 {
2584 selected_tid = selected_thread_sp->GetIndexID();
2585 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2586 }
2587 else
2588 {
2589 selected_tid = LLDB_INVALID_THREAD_ID;
2590 }
2591
2592 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2593
2594 Listener listener("ClangFunction temporary listener");
2595 exe_ctx.process->HijackProcessEvents(&listener);
2596
Jim Ingham77787032011-01-20 02:03:18 +00002597 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2598 if (log)
2599 {
2600 StreamString s;
2601 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
2602 log->Printf ("Resuming thread 0x%x to run thread plan \"%s\".", tid, s.GetData());
2603 }
2604
Jim Inghamf48169b2010-11-30 02:22:11 +00002605 Error resume_error = exe_ctx.process->Resume ();
2606 if (!resume_error.Success())
2607 {
2608 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
2609 exe_ctx.process->RestoreProcessEvents();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002610 return lldb::eExecutionSetupError;
Jim Inghamf48169b2010-11-30 02:22:11 +00002611 }
2612
2613 // We need to call the function synchronously, so spin waiting for it to return.
2614 // If we get interrupted while executing, we're going to lose our context, and
2615 // won't be able to gather the result at this point.
2616 // We set the timeout AFTER the resume, since the resume takes some time and we
2617 // don't want to charge that to the timeout.
2618
2619 TimeValue* timeout_ptr = NULL;
2620 TimeValue real_timeout;
2621
2622 if (single_thread_timeout_usec != 0)
2623 {
2624 real_timeout = TimeValue::Now();
2625 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2626 timeout_ptr = &real_timeout;
2627 }
2628
Jim Inghamf48169b2010-11-30 02:22:11 +00002629 while (1)
2630 {
2631 lldb::EventSP event_sp;
2632 lldb::StateType stop_state = lldb::eStateInvalid;
2633 // Now wait for the process to stop again:
2634 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
2635
2636 if (!got_event)
2637 {
2638 // Right now this is the only way to tell we've timed out...
2639 // We should interrupt the process here...
2640 // Not really sure what to do if Halt fails here...
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002641 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00002642 if (try_all_threads)
2643 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
2644 single_thread_timeout_usec);
2645 else
2646 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
2647 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002648 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002649
Jim Inghame22e88b2011-01-22 01:30:53 +00002650 Error halt_error = exe_ctx.process->Halt();
2651
2652 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00002653 {
2654 timeout_ptr = NULL;
2655 if (log)
2656 log->Printf ("Halt succeeded.");
2657
2658 // Between the time that we got the timeout and the time we halted, but target
2659 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
2660 // timeout to
2661 got_event = listener.WaitForEvent(NULL, event_sp);
2662
2663 if (got_event)
2664 {
2665 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2666 if (log)
2667 {
2668 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
2669 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
2670 log->Printf (" Event was the Halt interruption event.");
2671 }
2672
2673 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2674 {
2675 if (log)
2676 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002677 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002678 break;
2679 }
2680
2681 if (try_all_threads
2682 && (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent (event_sp.get())))
2683 {
2684
2685 thread_plan_sp->SetStopOthers (false);
2686 if (log)
2687 log->Printf ("About to resume.");
2688
2689 exe_ctx.process->Resume();
2690 continue;
2691 }
2692 else
2693 {
2694 exe_ctx.process->RestoreProcessEvents ();
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002695 return lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002696 }
2697 }
2698 }
Jim Inghame22e88b2011-01-22 01:30:53 +00002699 else
2700 {
2701
2702 if (log)
2703 log->Printf ("Halt failed: \"%s\", I'm just going to wait a little longer and see if the world gets nicer to me.",
2704 halt_error.AsCString());
2705
2706 if (single_thread_timeout_usec != 0)
2707 {
2708 real_timeout = TimeValue::Now();
2709 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2710 timeout_ptr = &real_timeout;
2711 }
2712 continue;
2713 }
2714
Jim Inghamf48169b2010-11-30 02:22:11 +00002715 }
2716
2717 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2718 if (log)
2719 log->Printf("Got event: %s.", StateAsCString(stop_state));
2720
2721 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
2722 continue;
2723
2724 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
2725 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002726 return_value = lldb::eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002727 break;
2728 }
2729 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
2730 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002731 return_value = lldb::eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00002732 break;
2733 }
2734 else
2735 {
2736 if (log)
2737 {
2738 StreamString s;
Jim Inghame22e88b2011-01-22 01:30:53 +00002739 if (event_sp)
2740 event_sp->Dump (&s);
2741 else
2742 {
2743 log->Printf ("Stop event that interrupted us is NULL.");
2744 }
2745
Jim Inghamf48169b2010-11-30 02:22:11 +00002746 StreamString ts;
2747
2748 const char *event_explanation;
2749
2750 do
2751 {
2752 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
2753
2754 if (!event_data)
2755 {
2756 event_explanation = "<no event data>";
2757 break;
2758 }
2759
2760 Process *process = event_data->GetProcessSP().get();
2761
2762 if (!process)
2763 {
2764 event_explanation = "<no process>";
2765 break;
2766 }
2767
2768 ThreadList &thread_list = process->GetThreadList();
2769
2770 uint32_t num_threads = thread_list.GetSize();
2771 uint32_t thread_index;
2772
2773 ts.Printf("<%u threads> ", num_threads);
2774
2775 for (thread_index = 0;
2776 thread_index < num_threads;
2777 ++thread_index)
2778 {
2779 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
2780
2781 if (!thread)
2782 {
2783 ts.Printf("<?> ");
2784 continue;
2785 }
2786
Jim Inghame22e88b2011-01-22 01:30:53 +00002787 ts.Printf("<0x%4.4x ", thread->GetID());
Greg Clayton5ccbd292011-01-06 22:15:06 +00002788 RegisterContext *register_context = thread->GetRegisterContext().get();
Jim Inghamf48169b2010-11-30 02:22:11 +00002789
2790 if (register_context)
2791 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
2792 else
2793 ts.Printf("[ip unknown] ");
2794
2795 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
2796 if (stop_info_sp)
2797 {
2798 const char *stop_desc = stop_info_sp->GetDescription();
2799 if (stop_desc)
2800 ts.PutCString (stop_desc);
2801 }
2802 ts.Printf(">");
2803 }
2804
2805 event_explanation = ts.GetData();
2806 } while (0);
2807
Jim Inghame22e88b2011-01-22 01:30:53 +00002808 // See if any of the threads that stopped think we ought to stop. Otherwise continue on.
2809 if (!GetThreadList().ShouldStop(event_sp.get()))
2810 {
2811 if (log)
2812 log->Printf("Execution interrupted, but nobody wanted to stop, so we continued: %s %s",
2813 s.GetData(), event_explanation);
2814 if (single_thread_timeout_usec != 0)
2815 {
2816 real_timeout = TimeValue::Now();
2817 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
2818 timeout_ptr = &real_timeout;
2819 }
2820
2821 continue;
2822 }
2823 else
2824 {
2825 if (log)
2826 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
2827 }
Jim Inghamf48169b2010-11-30 02:22:11 +00002828 }
2829
2830 if (discard_on_error && thread_plan_sp)
2831 {
2832 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
2833 }
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002834 return_value = lldb::eExecutionInterrupted;
Jim Inghamf48169b2010-11-30 02:22:11 +00002835 break;
2836 }
2837 }
2838
2839 if (exe_ctx.process)
2840 exe_ctx.process->RestoreProcessEvents ();
2841
2842 // Thread we ran the function in may have gone away because we ran the target
2843 // Check that it's still there.
2844 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
2845 if (exe_ctx.thread)
2846 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
2847
2848 // Also restore the current process'es selected frame & thread, since this function calling may
2849 // be done behind the user's back.
2850
2851 if (selected_tid != LLDB_INVALID_THREAD_ID)
2852 {
2853 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
2854 {
2855 // We were able to restore the selected thread, now restore the frame:
2856 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
2857 }
2858 }
2859
2860 return return_value;
2861}
2862
2863const char *
2864Process::ExecutionResultAsCString (ExecutionResults result)
2865{
2866 const char *result_name;
2867
2868 switch (result)
2869 {
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002870 case lldb::eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002871 result_name = "eExecutionCompleted";
2872 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002873 case lldb::eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00002874 result_name = "eExecutionDiscarded";
2875 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002876 case lldb::eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00002877 result_name = "eExecutionInterrupted";
2878 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002879 case lldb::eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00002880 result_name = "eExecutionSetupError";
2881 break;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002882 case lldb::eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00002883 result_name = "eExecutionTimedOut";
2884 break;
2885 }
2886 return result_name;
2887}
2888
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002889//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00002890// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002891//--------------------------------------------------------------
2892
Greg Clayton1b654882010-09-19 02:33:57 +00002893Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00002894 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002895{
Greg Clayton85851dd2010-12-04 00:10:17 +00002896 m_default_settings.reset (new ProcessInstanceSettings (*this,
2897 false,
Caroline Tice91123da2010-09-08 17:48:55 +00002898 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002899}
2900
Greg Clayton1b654882010-09-19 02:33:57 +00002901Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002902{
2903}
2904
2905lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00002906Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002907{
Greg Claytondbe54502010-11-19 03:46:01 +00002908 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
2909 false,
2910 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002911 lldb::InstanceSettingsSP new_settings_sp (new_settings);
2912 return new_settings_sp;
2913}
2914
2915//--------------------------------------------------------------
2916// class ProcessInstanceSettings
2917//--------------------------------------------------------------
2918
Greg Clayton85851dd2010-12-04 00:10:17 +00002919ProcessInstanceSettings::ProcessInstanceSettings
2920(
2921 UserSettingsController &owner,
2922 bool live_instance,
2923 const char *name
2924) :
2925 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002926 m_run_args (),
2927 m_env_vars (),
2928 m_input_path (),
2929 m_output_path (),
2930 m_error_path (),
2931 m_plugin (),
Caroline Ticef8da8632010-12-03 18:46:09 +00002932 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00002933 m_disable_stdio (false),
2934 m_inherit_host_env (true),
2935 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002936{
Caroline Ticef20e8232010-09-09 18:26:37 +00002937 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2938 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
2939 // 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 +00002940 // This is true for CreateInstanceName() too.
2941
2942 if (GetInstanceName () == InstanceSettings::InvalidName())
2943 {
2944 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2945 m_owner.RegisterInstanceSettings (this);
2946 }
Caroline Ticef20e8232010-09-09 18:26:37 +00002947
2948 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002949 {
2950 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2951 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00002952 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002953 }
2954}
2955
2956ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00002957 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002958 m_run_args (rhs.m_run_args),
2959 m_env_vars (rhs.m_env_vars),
2960 m_input_path (rhs.m_input_path),
2961 m_output_path (rhs.m_output_path),
2962 m_error_path (rhs.m_error_path),
2963 m_plugin (rhs.m_plugin),
Caroline Ticef8da8632010-12-03 18:46:09 +00002964 m_disable_aslr (rhs.m_disable_aslr),
2965 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002966{
2967 if (m_instance_name != InstanceSettings::GetDefaultName())
2968 {
2969 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2970 CopyInstanceSettings (pending_settings,false);
2971 m_owner.RemovePendingSettings (m_instance_name);
2972 }
2973}
2974
2975ProcessInstanceSettings::~ProcessInstanceSettings ()
2976{
2977}
2978
2979ProcessInstanceSettings&
2980ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
2981{
2982 if (this != &rhs)
2983 {
2984 m_run_args = rhs.m_run_args;
2985 m_env_vars = rhs.m_env_vars;
2986 m_input_path = rhs.m_input_path;
2987 m_output_path = rhs.m_output_path;
2988 m_error_path = rhs.m_error_path;
2989 m_plugin = rhs.m_plugin;
2990 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00002991 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00002992 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00002993 }
2994
2995 return *this;
2996}
2997
2998
2999void
3000ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3001 const char *index_value,
3002 const char *value,
3003 const ConstString &instance_name,
3004 const SettingEntry &entry,
3005 lldb::VarSetOperationType op,
3006 Error &err,
3007 bool pending)
3008{
3009 if (var_name == RunArgsVarName())
3010 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3011 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00003012 {
3013 GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003014 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003015 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003016 else if (var_name == InputPathVarName())
3017 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3018 else if (var_name == OutputPathVarName())
3019 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3020 else if (var_name == ErrorPathVarName())
3021 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3022 else if (var_name == PluginVarName())
3023 UserSettingsController::UpdateEnumVariable (entry.enum_values, (int *) &m_plugin, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00003024 else if (var_name == InheritHostEnvVarName())
3025 UserSettingsController::UpdateBooleanVariable (op, m_inherit_host_env, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003026 else if (var_name == DisableASLRVarName())
3027 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00003028 else if (var_name == DisableSTDIOVarName ())
3029 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003030}
3031
3032void
3033ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3034 bool pending)
3035{
3036 if (new_settings.get() == NULL)
3037 return;
3038
3039 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3040
3041 m_run_args = new_process_settings->m_run_args;
3042 m_env_vars = new_process_settings->m_env_vars;
3043 m_input_path = new_process_settings->m_input_path;
3044 m_output_path = new_process_settings->m_output_path;
3045 m_error_path = new_process_settings->m_error_path;
3046 m_plugin = new_process_settings->m_plugin;
3047 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00003048 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003049}
3050
Caroline Tice12cecd72010-09-20 21:37:42 +00003051bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003052ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3053 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00003054 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00003055 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003056{
3057 if (var_name == RunArgsVarName())
3058 {
3059 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00003060 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003061 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3062 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00003063 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003064 }
3065 else if (var_name == EnvVarsVarName())
3066 {
Greg Clayton85851dd2010-12-04 00:10:17 +00003067 GetHostEnvironmentIfNeeded ();
3068
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003069 if (m_env_vars.size() > 0)
3070 {
3071 std::map<std::string, std::string>::iterator pos;
3072 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3073 {
3074 StreamString value_str;
3075 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3076 value.AppendString (value_str.GetData());
3077 }
3078 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003079 }
3080 else if (var_name == InputPathVarName())
3081 {
3082 value.AppendString (m_input_path.c_str());
3083 }
3084 else if (var_name == OutputPathVarName())
3085 {
3086 value.AppendString (m_output_path.c_str());
3087 }
3088 else if (var_name == ErrorPathVarName())
3089 {
3090 value.AppendString (m_error_path.c_str());
3091 }
3092 else if (var_name == PluginVarName())
3093 {
3094 value.AppendString (UserSettingsController::EnumToString (entry.enum_values, (int) m_plugin));
3095 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00003096 else if (var_name == InheritHostEnvVarName())
3097 {
3098 if (m_inherit_host_env)
3099 value.AppendString ("true");
3100 else
3101 value.AppendString ("false");
3102 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003103 else if (var_name == DisableASLRVarName())
3104 {
3105 if (m_disable_aslr)
3106 value.AppendString ("true");
3107 else
3108 value.AppendString ("false");
3109 }
Caroline Ticef8da8632010-12-03 18:46:09 +00003110 else if (var_name == DisableSTDIOVarName())
3111 {
3112 if (m_disable_stdio)
3113 value.AppendString ("true");
3114 else
3115 value.AppendString ("false");
3116 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003117 else
Caroline Tice12cecd72010-09-20 21:37:42 +00003118 {
3119 if (err)
3120 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3121 return false;
3122 }
3123 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003124}
3125
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003126const ConstString
3127ProcessInstanceSettings::CreateInstanceName ()
3128{
3129 static int instance_count = 1;
3130 StreamString sstr;
3131
3132 sstr.Printf ("process_%d", instance_count);
3133 ++instance_count;
3134
3135 const ConstString ret_val (sstr.GetData());
3136 return ret_val;
3137}
3138
3139const ConstString &
3140ProcessInstanceSettings::RunArgsVarName ()
3141{
3142 static ConstString run_args_var_name ("run-args");
3143
3144 return run_args_var_name;
3145}
3146
3147const ConstString &
3148ProcessInstanceSettings::EnvVarsVarName ()
3149{
3150 static ConstString env_vars_var_name ("env-vars");
3151
3152 return env_vars_var_name;
3153}
3154
3155const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00003156ProcessInstanceSettings::InheritHostEnvVarName ()
3157{
3158 static ConstString g_name ("inherit-env");
3159
3160 return g_name;
3161}
3162
3163const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003164ProcessInstanceSettings::InputPathVarName ()
3165{
3166 static ConstString input_path_var_name ("input-path");
3167
3168 return input_path_var_name;
3169}
3170
3171const ConstString &
3172ProcessInstanceSettings::OutputPathVarName ()
3173{
Caroline Tice49e27372010-09-07 18:35:40 +00003174 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003175
3176 return output_path_var_name;
3177}
3178
3179const ConstString &
3180ProcessInstanceSettings::ErrorPathVarName ()
3181{
Caroline Tice49e27372010-09-07 18:35:40 +00003182 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003183
3184 return error_path_var_name;
3185}
3186
3187const ConstString &
3188ProcessInstanceSettings::PluginVarName ()
3189{
3190 static ConstString plugin_var_name ("plugin");
3191
3192 return plugin_var_name;
3193}
3194
3195
3196const ConstString &
3197ProcessInstanceSettings::DisableASLRVarName ()
3198{
3199 static ConstString disable_aslr_var_name ("disable-aslr");
3200
3201 return disable_aslr_var_name;
3202}
3203
Caroline Ticef8da8632010-12-03 18:46:09 +00003204const ConstString &
3205ProcessInstanceSettings::DisableSTDIOVarName ()
3206{
3207 static ConstString disable_stdio_var_name ("disable-stdio");
3208
3209 return disable_stdio_var_name;
3210}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003211
3212//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00003213// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003214//--------------------------------------------------
3215
3216SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003217Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003218{
3219 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3220 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3221};
3222
3223
3224lldb::OptionEnumValueElement
Greg Clayton1b654882010-09-19 02:33:57 +00003225Process::SettingsController::g_plugins[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003226{
Caroline Tice5c9fdfa2010-09-09 18:01:59 +00003227 { eMacosx, "process.macosx", "Use the native MacOSX debugger plugin" },
3228 { eRemoteDebugger, "process.gdb-remote" , "Use the GDB Remote protocol based debugger plugin" },
3229 { 0, NULL, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003230};
3231
3232SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00003233Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003234{
Greg Clayton85851dd2010-12-04 00:10:17 +00003235 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3236 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3237 { "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." },
3238 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
3239 { "input-path", eSetVarTypeString, "/dev/stdin", NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3240 { "output-path", eSetVarTypeString, "/dev/stdout", NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3241 { "error-path", eSetVarTypeString, "/dev/stderr", NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
3242 { "plugin", eSetVarTypeEnum, NULL , g_plugins, false, false, "The plugin to be used to run the process." },
3243 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3244 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3245 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003246};
3247
3248
Jim Ingham5aee1622010-08-09 23:31:02 +00003249