blob: 74f5fc31c3842e82445ee0c740401301bc90e542 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000023#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
25#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000026#include "lldb/Target/DynamicLoader.h"
Jim Ingham642036f2010-09-23 02:01:19 +000027#include "lldb/Target/LanguageRuntime.h"
28#include "lldb/Target/CPPLanguageRuntime.h"
29#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000030#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000032#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/Target.h"
34#include "lldb/Target/TargetList.h"
35#include "lldb/Target/Thread.h"
36#include "lldb/Target/ThreadPlan.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
Greg Clayton24bc5d92011-03-30 18:16:51 +000041void
42ProcessInfo::Dump (Stream &s, Platform *platform) const
43{
44 const char *cstr;
45 if (m_pid != LLDB_INVALID_PROCESS_ID) s.Printf (" pid = %i\n", m_pid);
46 if (!m_name.empty()) s.Printf (" name = \"%s\"\n", m_name.c_str());
47 if (m_arch.IsValid()) s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
48 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)s.Printf ("parent = %i\n", m_parent_pid);
49 if (m_real_uid != UINT32_MAX)
50 {
51 cstr = platform->GetUserName (m_real_uid);
52 s.Printf (" uid = %u %s\n", m_real_uid, cstr ? cstr : "");
53 }
54 if (m_real_gid != UINT32_MAX)
55 {
56 cstr = platform->GetGroupName (m_real_gid);
57 s.Printf (" gid = %u %s\n", m_real_gid, cstr ? cstr : "");
58 }
59 if (m_effective_uid != UINT32_MAX)
60 {
61 cstr = platform->GetUserName (m_effective_uid);
62 s.Printf (" euid = %u %s\n", m_effective_uid, cstr ? cstr : "");
63 }
64 if (m_effective_gid != UINT32_MAX)
65 {
66 cstr = platform->GetGroupName (m_effective_gid);
67 s.Printf (" egid = %u %s\n", m_effective_gid, cstr ? cstr : "");
68 }
69}
70
71void
72ProcessInfo::DumpTableHeader (Stream &s, Platform *platform)
73{
74// s.PutCString ("PID PARENT UID GID EUID EGID TRIPLE NAME\n");
75// s.PutCString ("====== ====== ===== ===== ===== ===== ======================== ============================\n");
76 s.PutCString ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE NAME\n");
77 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
78}
79
80void
81ProcessInfo::DumpAsTableRow (Stream &s, Platform *platform) const
82{
83 if (m_pid != LLDB_INVALID_PROCESS_ID)
84 {
85 const char *cstr;
86 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
87
88 cstr = platform->GetUserName (m_real_uid);
89 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
90 s.Printf ("%-10s ", cstr);
91 else
92 s.Printf ("%-10u ", m_real_uid);
93
94 cstr = platform->GetGroupName (m_real_gid);
95 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
96 s.Printf ("%-10s ", cstr);
97 else
98 s.Printf ("%-10u ", m_real_gid);
99
100 cstr = platform->GetUserName (m_effective_uid);
101 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
102 s.Printf ("%-10s ", cstr);
103 else
104 s.Printf ("%-10u ", m_effective_uid);
105
106 cstr = platform->GetGroupName (m_effective_gid);
107 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
108 s.Printf ("%-10s ", cstr);
109 else
110 s.Printf ("%-10u ", m_effective_gid);
111
112 s.Printf ("%-24s %s\n",
113 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "",
114 m_name.c_str());
115 }
116}
117
118bool
119ProcessInfoMatch::NameMatches (const char *process_name) const
120{
121 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
122 return true;
123 const char *match_name = m_match_info.GetName();
124 if (!match_name)
125 return true;
126
127 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
128}
129
130bool
131ProcessInfoMatch::Matches (const ProcessInfo &proc_info) const
132{
133 if (!NameMatches (proc_info.GetName()))
134 return false;
135
136 if (m_match_info.ProcessIDIsValid() &&
137 m_match_info.GetProcessID() != proc_info.GetProcessID())
138 return false;
139
140 if (m_match_info.ParentProcessIDIsValid() &&
141 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
142 return false;
143
144 if (m_match_info.RealUserIDIsValid () &&
145 m_match_info.GetRealUserID() != proc_info.GetRealUserID())
146 return false;
147
148 if (m_match_info.RealGroupIDIsValid () &&
149 m_match_info.GetRealGroupID() != proc_info.GetRealGroupID())
150 return false;
151
152 if (m_match_info.EffectiveUserIDIsValid () &&
153 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
154 return false;
155
156 if (m_match_info.EffectiveGroupIDIsValid () &&
157 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
158 return false;
159
160 if (m_match_info.GetArchitecture().IsValid() &&
161 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
162 return false;
163 return true;
164}
165
166bool
167ProcessInfoMatch::MatchAllProcesses () const
168{
169 if (m_name_match_type != eNameMatchIgnore)
170 return false;
171
172 if (m_match_info.ProcessIDIsValid())
173 return false;
174
175 if (m_match_info.ParentProcessIDIsValid())
176 return false;
177
178 if (m_match_info.RealUserIDIsValid ())
179 return false;
180
181 if (m_match_info.RealGroupIDIsValid ())
182 return false;
183
184 if (m_match_info.EffectiveUserIDIsValid ())
185 return false;
186
187 if (m_match_info.EffectiveGroupIDIsValid ())
188 return false;
189
190 if (m_match_info.GetArchitecture().IsValid())
191 return false;
192
193 if (m_match_all_users)
194 return false;
195
196 return true;
197
198}
199
200void
201ProcessInfoMatch::Clear()
202{
203 m_match_info.Clear();
204 m_name_match_type = eNameMatchIgnore;
205 m_match_all_users = false;
206}
Greg Claytonfd119992011-01-07 06:08:19 +0000207
208//----------------------------------------------------------------------
209// MemoryCache constructor
210//----------------------------------------------------------------------
211Process::MemoryCache::MemoryCache() :
212 m_cache_line_byte_size (512),
213 m_cache_mutex (Mutex::eMutexTypeRecursive),
214 m_cache ()
215{
216}
217
218//----------------------------------------------------------------------
219// Destructor
220//----------------------------------------------------------------------
221Process::MemoryCache::~MemoryCache()
222{
223}
224
225void
226Process::MemoryCache::Clear()
227{
228 Mutex::Locker locker (m_cache_mutex);
229 m_cache.clear();
230}
231
232void
233Process::MemoryCache::Flush (addr_t addr, size_t size)
234{
235 if (size == 0)
236 return;
237
238 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
239 const addr_t end_addr = (addr + size - 1);
240 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
241 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
242
243 Mutex::Locker locker (m_cache_mutex);
244 if (m_cache.empty())
245 return;
246
247 assert ((flush_start_addr % cache_line_byte_size) == 0);
248
249 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
250 {
251 collection::iterator pos = m_cache.find (curr_addr);
252 if (pos != m_cache.end())
253 m_cache.erase(pos);
254 }
255}
256
257size_t
258Process::MemoryCache::Read
259(
260 Process *process,
261 addr_t addr,
262 void *dst,
263 size_t dst_len,
264 Error &error
265)
266{
267 size_t bytes_left = dst_len;
268 if (dst && bytes_left > 0)
269 {
270 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
271 uint8_t *dst_buf = (uint8_t *)dst;
272 addr_t curr_addr = addr - (addr % cache_line_byte_size);
273 addr_t cache_offset = addr - curr_addr;
274 Mutex::Locker locker (m_cache_mutex);
275
276 while (bytes_left > 0)
277 {
278 collection::const_iterator pos = m_cache.find (curr_addr);
279 collection::const_iterator end = m_cache.end ();
280
281 if (pos != end)
282 {
283 size_t curr_read_size = cache_line_byte_size - cache_offset;
284 if (curr_read_size > bytes_left)
285 curr_read_size = bytes_left;
286
287 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
288
289 bytes_left -= curr_read_size;
290 curr_addr += curr_read_size + cache_offset;
291 cache_offset = 0;
292
293 if (bytes_left > 0)
294 {
295 // Get sequential cache page hits
296 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
297 {
298 assert ((curr_addr % cache_line_byte_size) == 0);
299
300 if (pos->first != curr_addr)
301 break;
302
303 curr_read_size = pos->second->GetByteSize();
304 if (curr_read_size > bytes_left)
305 curr_read_size = bytes_left;
306
307 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
308
309 bytes_left -= curr_read_size;
310 curr_addr += curr_read_size;
311
312 // We have a cache page that succeeded to read some bytes
313 // but not an entire page. If this happens, we must cap
314 // off how much data we are able to read...
315 if (pos->second->GetByteSize() != cache_line_byte_size)
316 return dst_len - bytes_left;
317 }
318 }
319 }
320
321 // We need to read from the process
322
323 if (bytes_left > 0)
324 {
325 assert ((curr_addr % cache_line_byte_size) == 0);
326 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
327 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
328 data_buffer_heap_ap->GetBytes(),
329 data_buffer_heap_ap->GetByteSize(),
330 error);
331 if (process_bytes_read == 0)
332 return dst_len - bytes_left;
333
334 if (process_bytes_read != cache_line_byte_size)
335 data_buffer_heap_ap->SetByteSize (process_bytes_read);
336 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
337 // We have read data and put it into the cache, continue through the
338 // loop again to get the data out of the cache...
339 }
340 }
341 }
342
343 return dst_len - bytes_left;
344}
345
Chris Lattner24943d22010-06-08 16:52:24 +0000346Process*
347Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
348{
349 ProcessCreateInstance create_callback = NULL;
350 if (plugin_name)
351 {
352 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
353 if (create_callback)
354 {
355 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
356 if (debugger_ap->CanDebug(target))
357 return debugger_ap.release();
358 }
359 }
360 else
361 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000362 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000363 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000364 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
365 if (debugger_ap->CanDebug(target))
366 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000367 }
368 }
369 return NULL;
370}
371
372
373//----------------------------------------------------------------------
374// Process constructor
375//----------------------------------------------------------------------
376Process::Process(Target &target, Listener &listener) :
377 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000378 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000379 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000380 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000381 m_public_state (eStateUnloaded),
382 m_private_state (eStateUnloaded),
383 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
384 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
385 m_private_state_listener ("lldb.process.internal_state_listener"),
386 m_private_state_control_wait(),
387 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
388 m_stop_id (0),
389 m_thread_index_id (0),
390 m_exit_status (-1),
391 m_exit_string (),
392 m_thread_list (this),
393 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000394 m_image_tokens (),
395 m_listener (listener),
396 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000397 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000398 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000399 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000400 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000401 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000402 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000403 m_stdout_data (),
Jim Inghamc2dc7c82011-01-29 01:49:25 +0000404 m_memory_cache (),
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000405 m_next_event_action_ap()
Chris Lattner24943d22010-06-08 16:52:24 +0000406{
Caroline Tice1ebef442010-09-27 00:30:10 +0000407 UpdateInstanceName();
408
Greg Claytone005f2c2010-11-06 01:53:30 +0000409 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000410 if (log)
411 log->Printf ("%p Process::Process()", this);
412
Greg Clayton49ce6822010-10-31 03:01:06 +0000413 SetEventName (eBroadcastBitStateChanged, "state-changed");
414 SetEventName (eBroadcastBitInterrupt, "interrupt");
415 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
416 SetEventName (eBroadcastBitSTDERR, "stderr-available");
417
Chris Lattner24943d22010-06-08 16:52:24 +0000418 listener.StartListeningForEvents (this,
419 eBroadcastBitStateChanged |
420 eBroadcastBitInterrupt |
421 eBroadcastBitSTDOUT |
422 eBroadcastBitSTDERR);
423
424 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
425 eBroadcastBitStateChanged);
426
427 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
428 eBroadcastInternalStateControlStop |
429 eBroadcastInternalStateControlPause |
430 eBroadcastInternalStateControlResume);
431}
432
433//----------------------------------------------------------------------
434// Destructor
435//----------------------------------------------------------------------
436Process::~Process()
437{
Greg Claytone005f2c2010-11-06 01:53:30 +0000438 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000439 if (log)
440 log->Printf ("%p Process::~Process()", this);
441 StopPrivateStateThread();
442}
443
444void
445Process::Finalize()
446{
447 // Do any cleanup needed prior to being destructed... Subclasses
448 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000449
450 // We need to destroy the loader before the derived Process class gets destroyed
451 // since it is very likely that undoing the loader will require access to the real process.
452 if (m_dyld_ap.get() != NULL)
453 m_dyld_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000454}
455
456void
457Process::RegisterNotificationCallbacks (const Notifications& callbacks)
458{
459 m_notifications.push_back(callbacks);
460 if (callbacks.initialize != NULL)
461 callbacks.initialize (callbacks.baton, this);
462}
463
464bool
465Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
466{
467 std::vector<Notifications>::iterator pos, end = m_notifications.end();
468 for (pos = m_notifications.begin(); pos != end; ++pos)
469 {
470 if (pos->baton == callbacks.baton &&
471 pos->initialize == callbacks.initialize &&
472 pos->process_state_changed == callbacks.process_state_changed)
473 {
474 m_notifications.erase(pos);
475 return true;
476 }
477 }
478 return false;
479}
480
481void
482Process::SynchronouslyNotifyStateChanged (StateType state)
483{
484 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
485 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
486 {
487 if (notification_pos->process_state_changed)
488 notification_pos->process_state_changed (notification_pos->baton, this, state);
489 }
490}
491
492// FIXME: We need to do some work on events before the general Listener sees them.
493// For instance if we are continuing from a breakpoint, we need to ensure that we do
494// the little "insert real insn, step & stop" trick. But we can't do that when the
495// event is delivered by the broadcaster - since that is done on the thread that is
496// waiting for new events, so if we needed more than one event for our handling, we would
497// stall. So instead we do it when we fetch the event off of the queue.
498//
499
500StateType
501Process::GetNextEvent (EventSP &event_sp)
502{
503 StateType state = eStateInvalid;
504
505 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
506 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
507
508 return state;
509}
510
511
512StateType
513Process::WaitForProcessToStop (const TimeValue *timeout)
514{
515 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
516 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
517}
518
519
520StateType
521Process::WaitForState
522(
523 const TimeValue *timeout,
524 const StateType *match_states, const uint32_t num_match_states
525)
526{
527 EventSP event_sp;
528 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000529 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000530 while (state != eStateInvalid)
531 {
Greg Claytond8c62532010-10-07 04:19:01 +0000532 // If we are exited or detached, we won't ever get back to any
533 // other valid state...
534 if (state == eStateDetached || state == eStateExited)
535 return state;
536
Chris Lattner24943d22010-06-08 16:52:24 +0000537 state = WaitForStateChangedEvents (timeout, event_sp);
538
539 for (i=0; i<num_match_states; ++i)
540 {
541 if (match_states[i] == state)
542 return state;
543 }
544 }
545 return state;
546}
547
Jim Ingham63e24d72010-10-11 23:53:14 +0000548bool
549Process::HijackProcessEvents (Listener *listener)
550{
551 if (listener != NULL)
552 {
553 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
554 }
555 else
556 return false;
557}
558
559void
560Process::RestoreProcessEvents ()
561{
562 RestoreBroadcaster();
563}
564
Jim Inghamf9f40c22011-02-08 05:20:59 +0000565bool
566Process::HijackPrivateProcessEvents (Listener *listener)
567{
568 if (listener != NULL)
569 {
570 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
571 }
572 else
573 return false;
574}
575
576void
577Process::RestorePrivateProcessEvents ()
578{
579 m_private_state_broadcaster.RestoreBroadcaster();
580}
581
Chris Lattner24943d22010-06-08 16:52:24 +0000582StateType
583Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
584{
Greg Claytone005f2c2010-11-06 01:53:30 +0000585 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000586
587 if (log)
588 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
589
590 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000591 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
592 this,
593 eBroadcastBitStateChanged,
594 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000595 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
596
597 if (log)
598 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
599 __FUNCTION__,
600 timeout,
601 StateAsCString(state));
602 return state;
603}
604
605Event *
606Process::PeekAtStateChangedEvents ()
607{
Greg Claytone005f2c2010-11-06 01:53:30 +0000608 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610 if (log)
611 log->Printf ("Process::%s...", __FUNCTION__);
612
613 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000614 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
615 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000616 if (log)
617 {
618 if (event_ptr)
619 {
620 log->Printf ("Process::%s (event_ptr) => %s",
621 __FUNCTION__,
622 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
623 }
624 else
625 {
626 log->Printf ("Process::%s no events found",
627 __FUNCTION__);
628 }
629 }
630 return event_ptr;
631}
632
633StateType
634Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
635{
Greg Claytone005f2c2010-11-06 01:53:30 +0000636 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000637
638 if (log)
639 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
640
641 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000642 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
643 &m_private_state_broadcaster,
644 eBroadcastBitStateChanged,
645 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000646 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
647
648 // This is a bit of a hack, but when we wait here we could very well return
649 // to the command-line, and that could disable the log, which would render the
650 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000651 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000652 {
653 if (state == eStateInvalid)
654 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
655 else
656 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
657 }
Chris Lattner24943d22010-06-08 16:52:24 +0000658 return state;
659}
660
661bool
662Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
663{
Greg Claytone005f2c2010-11-06 01:53:30 +0000664 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000665
666 if (log)
667 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
668
669 if (control_only)
670 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
671 else
672 return m_private_state_listener.WaitForEvent(timeout, event_sp);
673}
674
675bool
676Process::IsRunning () const
677{
678 return StateIsRunningState (m_public_state.GetValue());
679}
680
681int
682Process::GetExitStatus ()
683{
684 if (m_public_state.GetValue() == eStateExited)
685 return m_exit_status;
686 return -1;
687}
688
Greg Clayton638351a2010-12-04 00:10:17 +0000689
690void
691Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
692{
693 if (m_inherit_host_env && !m_got_host_env)
694 {
695 m_got_host_env = true;
696 StringList host_env;
697 const size_t host_env_count = Host::GetEnvironment (host_env);
698 for (size_t idx=0; idx<host_env_count; idx++)
699 {
700 const char *env_entry = host_env.GetStringAtIndex (idx);
701 if (env_entry)
702 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000703 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000704 if (equal_pos)
705 {
706 std::string key (env_entry, equal_pos - env_entry);
707 std::string value (equal_pos + 1);
708 if (m_env_vars.find (key) == m_env_vars.end())
709 m_env_vars[key] = value;
710 }
711 }
712 }
713 }
714}
715
716
717size_t
718Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
719{
720 GetHostEnvironmentIfNeeded ();
721
722 dictionary::const_iterator pos, end = m_env_vars.end();
723 for (pos = m_env_vars.begin(); pos != end; ++pos)
724 {
725 std::string env_var_equal_value (pos->first);
726 env_var_equal_value.append(1, '=');
727 env_var_equal_value.append (pos->second);
728 env.AppendArgument (env_var_equal_value.c_str());
729 }
730 return env.GetArgumentCount();
731}
732
733
Chris Lattner24943d22010-06-08 16:52:24 +0000734const char *
735Process::GetExitDescription ()
736{
737 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
738 return m_exit_string.c_str();
739 return NULL;
740}
741
Greg Clayton72e1c782011-01-22 23:43:18 +0000742bool
Chris Lattner24943d22010-06-08 16:52:24 +0000743Process::SetExitStatus (int status, const char *cstr)
744{
Greg Clayton68ca8232011-01-25 02:58:48 +0000745 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
746 if (log)
747 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
748 status, status,
749 cstr ? "\"" : "",
750 cstr ? cstr : "NULL",
751 cstr ? "\"" : "");
752
Greg Clayton72e1c782011-01-22 23:43:18 +0000753 // We were already in the exited state
754 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +0000755 {
Greg Clayton644ddfb2011-01-26 23:47:29 +0000756 if (log)
757 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +0000758 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +0000759 }
Greg Clayton72e1c782011-01-22 23:43:18 +0000760
761 m_exit_status = status;
762 if (cstr)
763 m_exit_string = cstr;
764 else
765 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000766
Greg Clayton72e1c782011-01-22 23:43:18 +0000767 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +0000768
Greg Clayton72e1c782011-01-22 23:43:18 +0000769 SetPrivateState (eStateExited);
770 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000771}
772
773// This static callback can be used to watch for local child processes on
774// the current host. The the child process exits, the process will be
775// found in the global target list (we want to be completely sure that the
776// lldb_private::Process doesn't go away before we can deliver the signal.
777bool
778Process::SetProcessExitStatus
779(
780 void *callback_baton,
781 lldb::pid_t pid,
782 int signo, // Zero for no signal
783 int exit_status // Exit value of process if signal is zero
784)
785{
786 if (signo == 0 || exit_status)
787 {
Greg Clayton63094e02010-06-23 01:19:29 +0000788 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +0000789 if (target_sp)
790 {
791 ProcessSP process_sp (target_sp->GetProcessSP());
792 if (process_sp)
793 {
794 const char *signal_cstr = NULL;
795 if (signo)
796 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
797
798 process_sp->SetExitStatus (exit_status, signal_cstr);
799 }
800 }
801 return true;
802 }
803 return false;
804}
805
806
807uint32_t
808Process::GetNextThreadIndexID ()
809{
810 return ++m_thread_index_id;
811}
812
813StateType
814Process::GetState()
815{
816 // If any other threads access this we will need a mutex for it
817 return m_public_state.GetValue ();
818}
819
820void
821Process::SetPublicState (StateType new_state)
822{
Greg Clayton68ca8232011-01-25 02:58:48 +0000823 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000824 if (log)
825 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
826 m_public_state.SetValue (new_state);
827}
828
829StateType
830Process::GetPrivateState ()
831{
832 return m_private_state.GetValue();
833}
834
835void
836Process::SetPrivateState (StateType new_state)
837{
Greg Clayton68ca8232011-01-25 02:58:48 +0000838 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000839 bool state_changed = false;
840
841 if (log)
842 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
843
844 Mutex::Locker locker(m_private_state.GetMutex());
845
846 const StateType old_state = m_private_state.GetValueNoLock ();
847 state_changed = old_state != new_state;
848 if (state_changed)
849 {
850 m_private_state.SetValueNoLock (new_state);
851 if (StateIsStoppedState(new_state))
852 {
853 m_stop_id++;
Greg Claytonfd119992011-01-07 06:08:19 +0000854 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000855 if (log)
856 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
857 }
858 // Use our target to get a shared pointer to ourselves...
859 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
860 }
861 else
862 {
863 if (log)
864 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
865 }
866}
867
868
869uint32_t
870Process::GetStopID() const
871{
872 return m_stop_id;
873}
874
875addr_t
876Process::GetImageInfoAddress()
877{
878 return LLDB_INVALID_ADDRESS;
879}
880
Greg Clayton0baa3942010-11-04 01:54:29 +0000881//----------------------------------------------------------------------
882// LoadImage
883//
884// This function provides a default implementation that works for most
885// unix variants. Any Process subclasses that need to do shared library
886// loading differently should override LoadImage and UnloadImage and
887// do what is needed.
888//----------------------------------------------------------------------
889uint32_t
890Process::LoadImage (const FileSpec &image_spec, Error &error)
891{
892 DynamicLoader *loader = GetDynamicLoader();
893 if (loader)
894 {
895 error = loader->CanLoadImage();
896 if (error.Fail())
897 return LLDB_INVALID_IMAGE_TOKEN;
898 }
899
900 if (error.Success())
901 {
902 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
903 if (thread_sp == NULL)
904 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
905
906 if (thread_sp)
907 {
908 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
909
910 if (frame_sp)
911 {
912 ExecutionContext exe_ctx;
913 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000914 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000915 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000916 StreamString expr;
917 char path[PATH_MAX];
918 image_spec.GetPath(path, sizeof(path));
919 expr.Printf("dlopen (\"%s\", 2)", path);
920 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000921 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000922 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000923 if (result_valobj_sp->GetError().Success())
924 {
925 Scalar scalar;
926 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
927 {
928 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
929 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
930 {
931 uint32_t image_token = m_image_tokens.size();
932 m_image_tokens.push_back (image_ptr);
933 return image_token;
934 }
935 }
936 }
937 }
938 }
939 }
940 return LLDB_INVALID_IMAGE_TOKEN;
941}
942
943//----------------------------------------------------------------------
944// UnloadImage
945//
946// This function provides a default implementation that works for most
947// unix variants. Any Process subclasses that need to do shared library
948// loading differently should override LoadImage and UnloadImage and
949// do what is needed.
950//----------------------------------------------------------------------
951Error
952Process::UnloadImage (uint32_t image_token)
953{
954 Error error;
955 if (image_token < m_image_tokens.size())
956 {
957 const addr_t image_addr = m_image_tokens[image_token];
958 if (image_addr == LLDB_INVALID_ADDRESS)
959 {
960 error.SetErrorString("image already unloaded");
961 }
962 else
963 {
964 DynamicLoader *loader = GetDynamicLoader();
965 if (loader)
966 error = loader->CanLoadImage();
967
968 if (error.Success())
969 {
970 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
971 if (thread_sp == NULL)
972 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
973
974 if (thread_sp)
975 {
976 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
977
978 if (frame_sp)
979 {
980 ExecutionContext exe_ctx;
981 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +0000982 bool unwind_on_error = true;
Sean Callanan6a925532011-01-13 08:53:35 +0000983 bool keep_in_memory = false;
Greg Clayton0baa3942010-11-04 01:54:29 +0000984 StreamString expr;
985 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
986 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +0000987 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan6a925532011-01-13 08:53:35 +0000988 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +0000989 if (result_valobj_sp->GetError().Success())
990 {
991 Scalar scalar;
992 if (result_valobj_sp->ResolveValue (frame_sp.get(), scalar))
993 {
994 if (scalar.UInt(1))
995 {
996 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
997 }
998 else
999 {
1000 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1001 }
1002 }
1003 }
1004 else
1005 {
1006 error = result_valobj_sp->GetError();
1007 }
1008 }
1009 }
1010 }
1011 }
1012 }
1013 else
1014 {
1015 error.SetErrorString("invalid image token");
1016 }
1017 return error;
1018}
1019
Chris Lattner24943d22010-06-08 16:52:24 +00001020const ABI *
1021Process::GetABI()
1022{
Chris Lattner24943d22010-06-08 16:52:24 +00001023 if (m_abi_sp.get() == NULL)
Greg Clayton395fc332011-02-15 21:59:32 +00001024 m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
Chris Lattner24943d22010-06-08 16:52:24 +00001025
1026 return m_abi_sp.get();
1027}
1028
Jim Ingham642036f2010-09-23 02:01:19 +00001029LanguageRuntime *
1030Process::GetLanguageRuntime(lldb::LanguageType language)
1031{
1032 LanguageRuntimeCollection::iterator pos;
1033 pos = m_language_runtimes.find (language);
1034 if (pos == m_language_runtimes.end())
1035 {
1036 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1037
1038 m_language_runtimes[language]
1039 = runtime;
1040 return runtime.get();
1041 }
1042 else
1043 return (*pos).second.get();
1044}
1045
1046CPPLanguageRuntime *
1047Process::GetCPPLanguageRuntime ()
1048{
1049 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1050 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1051 return static_cast<CPPLanguageRuntime *> (runtime);
1052 return NULL;
1053}
1054
1055ObjCLanguageRuntime *
1056Process::GetObjCLanguageRuntime ()
1057{
1058 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1059 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1060 return static_cast<ObjCLanguageRuntime *> (runtime);
1061 return NULL;
1062}
1063
Chris Lattner24943d22010-06-08 16:52:24 +00001064BreakpointSiteList &
1065Process::GetBreakpointSiteList()
1066{
1067 return m_breakpoint_site_list;
1068}
1069
1070const BreakpointSiteList &
1071Process::GetBreakpointSiteList() const
1072{
1073 return m_breakpoint_site_list;
1074}
1075
1076
1077void
1078Process::DisableAllBreakpointSites ()
1079{
1080 m_breakpoint_site_list.SetEnabledForAll (false);
1081}
1082
1083Error
1084Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1085{
1086 Error error (DisableBreakpointSiteByID (break_id));
1087
1088 if (error.Success())
1089 m_breakpoint_site_list.Remove(break_id);
1090
1091 return error;
1092}
1093
1094Error
1095Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1096{
1097 Error error;
1098 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1099 if (bp_site_sp)
1100 {
1101 if (bp_site_sp->IsEnabled())
1102 error = DisableBreakpoint (bp_site_sp.get());
1103 }
1104 else
1105 {
1106 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1107 }
1108
1109 return error;
1110}
1111
1112Error
1113Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1114{
1115 Error error;
1116 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1117 if (bp_site_sp)
1118 {
1119 if (!bp_site_sp->IsEnabled())
1120 error = EnableBreakpoint (bp_site_sp.get());
1121 }
1122 else
1123 {
1124 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1125 }
1126 return error;
1127}
1128
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001129lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001130Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1131{
Greg Claytoneea26402010-09-14 23:36:40 +00001132 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001133 if (load_addr != LLDB_INVALID_ADDRESS)
1134 {
1135 BreakpointSiteSP bp_site_sp;
1136
1137 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1138 // create a new breakpoint site and add it.
1139
1140 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1141
1142 if (bp_site_sp)
1143 {
1144 bp_site_sp->AddOwner (owner);
1145 owner->SetBreakpointSite (bp_site_sp);
1146 return bp_site_sp->GetID();
1147 }
1148 else
1149 {
1150 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1151 if (bp_site_sp)
1152 {
1153 if (EnableBreakpoint (bp_site_sp.get()).Success())
1154 {
1155 owner->SetBreakpointSite (bp_site_sp);
1156 return m_breakpoint_site_list.Add (bp_site_sp);
1157 }
1158 }
1159 }
1160 }
1161 // We failed to enable the breakpoint
1162 return LLDB_INVALID_BREAK_ID;
1163
1164}
1165
1166void
1167Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1168{
1169 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1170 if (num_owners == 0)
1171 {
1172 DisableBreakpoint(bp_site_sp.get());
1173 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1174 }
1175}
1176
1177
1178size_t
1179Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1180{
1181 size_t bytes_removed = 0;
1182 addr_t intersect_addr;
1183 size_t intersect_size;
1184 size_t opcode_offset;
1185 size_t idx;
1186 BreakpointSiteSP bp;
1187
1188 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1189 {
1190 if (bp->GetType() == BreakpointSite::eSoftware)
1191 {
1192 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1193 {
1194 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1195 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1196 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1197 size_t buf_offset = intersect_addr - bp_addr;
1198 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1199 }
1200 }
1201 }
1202 return bytes_removed;
1203}
1204
1205
Greg Claytonb1888f22011-03-19 01:12:21 +00001206
1207size_t
1208Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1209{
1210 PlatformSP platform_sp (m_target.GetPlatform());
1211 if (platform_sp)
1212 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1213 return 0;
1214}
1215
Chris Lattner24943d22010-06-08 16:52:24 +00001216Error
1217Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1218{
1219 Error error;
1220 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001221 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001222 const addr_t bp_addr = bp_site->GetLoadAddress();
1223 if (log)
1224 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1225 if (bp_site->IsEnabled())
1226 {
1227 if (log)
1228 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1229 return error;
1230 }
1231
1232 if (bp_addr == LLDB_INVALID_ADDRESS)
1233 {
1234 error.SetErrorString("BreakpointSite contains an invalid load address.");
1235 return error;
1236 }
1237 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1238 // trap for the breakpoint site
1239 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1240
1241 if (bp_opcode_size == 0)
1242 {
1243 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1244 }
1245 else
1246 {
1247 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1248
1249 if (bp_opcode_bytes == NULL)
1250 {
1251 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1252 return error;
1253 }
1254
1255 // Save the original opcode by reading it
1256 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1257 {
1258 // Write a software breakpoint in place of the original opcode
1259 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1260 {
1261 uint8_t verify_bp_opcode_bytes[64];
1262 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1263 {
1264 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1265 {
1266 bp_site->SetEnabled(true);
1267 bp_site->SetType (BreakpointSite::eSoftware);
1268 if (log)
1269 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1270 bp_site->GetID(),
1271 (uint64_t)bp_addr);
1272 }
1273 else
1274 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1275 }
1276 else
1277 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1278 }
1279 else
1280 error.SetErrorString("Unable to write breakpoint trap to memory.");
1281 }
1282 else
1283 error.SetErrorString("Unable to read memory at breakpoint address.");
1284 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001285 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001286 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1287 bp_site->GetID(),
1288 (uint64_t)bp_addr,
1289 error.AsCString());
1290 return error;
1291}
1292
1293Error
1294Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1295{
1296 Error error;
1297 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001298 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001299 addr_t bp_addr = bp_site->GetLoadAddress();
1300 lldb::user_id_t breakID = bp_site->GetID();
1301 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001302 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001303
1304 if (bp_site->IsHardware())
1305 {
1306 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1307 }
1308 else if (bp_site->IsEnabled())
1309 {
1310 const size_t break_op_size = bp_site->GetByteSize();
1311 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1312 if (break_op_size > 0)
1313 {
1314 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001315 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001316 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001317 bool break_op_found = false;
1318
1319 // Read the breakpoint opcode
1320 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1321 {
1322 bool verify = false;
1323 // Make sure we have the a breakpoint opcode exists at this address
1324 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1325 {
1326 break_op_found = true;
1327 // We found a valid breakpoint opcode at this address, now restore
1328 // the saved opcode.
1329 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1330 {
1331 verify = true;
1332 }
1333 else
1334 error.SetErrorString("Memory write failed when restoring original opcode.");
1335 }
1336 else
1337 {
1338 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1339 // Set verify to true and so we can check if the original opcode has already been restored
1340 verify = true;
1341 }
1342
1343 if (verify)
1344 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001345 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001346 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001347 // Verify that our original opcode made it back to the inferior
1348 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1349 {
1350 // compare the memory we just read with the original opcode
1351 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1352 {
1353 // SUCCESS
1354 bp_site->SetEnabled(false);
1355 if (log)
1356 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1357 return error;
1358 }
1359 else
1360 {
1361 if (break_op_found)
1362 error.SetErrorString("Failed to restore original opcode.");
1363 }
1364 }
1365 else
1366 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1367 }
1368 }
1369 else
1370 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1371 }
1372 }
1373 else
1374 {
1375 if (log)
1376 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1377 return error;
1378 }
1379
1380 if (log)
1381 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1382 bp_site->GetID(),
1383 (uint64_t)bp_addr,
1384 error.AsCString());
1385 return error;
1386
1387}
1388
Greg Claytonfd119992011-01-07 06:08:19 +00001389// Comment out line below to disable memory caching
1390#define ENABLE_MEMORY_CACHING
1391// Uncomment to verify memory caching works after making changes to caching code
1392//#define VERIFY_MEMORY_READS
1393
1394#if defined (ENABLE_MEMORY_CACHING)
1395
1396#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001397
1398size_t
1399Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1400{
Greg Claytonfd119992011-01-07 06:08:19 +00001401 // Memory caching is enabled, with debug verification
1402 if (buf && size)
1403 {
1404 // Uncomment the line below to make sure memory caching is working.
1405 // I ran this through the test suite and got no assertions, so I am
1406 // pretty confident this is working well. If any changes are made to
1407 // memory caching, uncomment the line below and test your changes!
1408
1409 // Verify all memory reads by using the cache first, then redundantly
1410 // reading the same memory from the inferior and comparing to make sure
1411 // everything is exactly the same.
1412 std::string verify_buf (size, '\0');
1413 assert (verify_buf.size() == size);
1414 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1415 Error verify_error;
1416 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1417 assert (cache_bytes_read == verify_bytes_read);
1418 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1419 assert (verify_error.Success() == error.Success());
1420 return cache_bytes_read;
1421 }
1422 return 0;
1423}
1424
1425#else // #if defined (VERIFY_MEMORY_READS)
1426
1427size_t
1428Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1429{
1430 // Memory caching enabled, no verification
1431 return m_memory_cache.Read (this, addr, buf, size, error);
1432}
1433
1434#endif // #else for #if defined (VERIFY_MEMORY_READS)
1435
1436#else // #if defined (ENABLE_MEMORY_CACHING)
1437
1438size_t
1439Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1440{
1441 // Memory caching is disabled
1442 return ReadMemoryFromInferior (addr, buf, size, error);
1443}
1444
1445#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1446
1447
1448size_t
1449Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1450{
Chris Lattner24943d22010-06-08 16:52:24 +00001451 if (buf == NULL || size == 0)
1452 return 0;
1453
1454 size_t bytes_read = 0;
1455 uint8_t *bytes = (uint8_t *)buf;
1456
1457 while (bytes_read < size)
1458 {
1459 const size_t curr_size = size - bytes_read;
1460 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1461 bytes + bytes_read,
1462 curr_size,
1463 error);
1464 bytes_read += curr_bytes_read;
1465 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1466 break;
1467 }
1468
1469 // Replace any software breakpoint opcodes that fall into this range back
1470 // into "buf" before we return
1471 if (bytes_read > 0)
1472 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1473 return bytes_read;
1474}
1475
Greg Claytonf72fdee2010-12-16 20:01:20 +00001476uint64_t
1477Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1478{
1479 if (integer_byte_size > sizeof(uint64_t))
1480 {
1481 error.SetErrorString ("unsupported integer size");
1482 }
1483 else
1484 {
1485 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton395fc332011-02-15 21:59:32 +00001486 DataExtractor data (tmp,
1487 integer_byte_size,
1488 m_target.GetArchitecture().GetByteOrder(),
1489 m_target.GetArchitecture().GetAddressByteSize());
Greg Claytonf72fdee2010-12-16 20:01:20 +00001490 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1491 {
1492 uint32_t offset = 0;
1493 return data.GetMaxU64 (&offset, integer_byte_size);
1494 }
1495 }
1496 // Any plug-in that doesn't return success a memory read with the number
1497 // of bytes that were requested should be setting the error
1498 assert (error.Fail());
1499 return 0;
1500}
1501
Chris Lattner24943d22010-06-08 16:52:24 +00001502size_t
1503Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1504{
1505 size_t bytes_written = 0;
1506 const uint8_t *bytes = (const uint8_t *)buf;
1507
1508 while (bytes_written < size)
1509 {
1510 const size_t curr_size = size - bytes_written;
1511 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1512 bytes + bytes_written,
1513 curr_size,
1514 error);
1515 bytes_written += curr_bytes_written;
1516 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1517 break;
1518 }
1519 return bytes_written;
1520}
1521
1522size_t
1523Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1524{
Greg Claytonfd119992011-01-07 06:08:19 +00001525#if defined (ENABLE_MEMORY_CACHING)
1526 m_memory_cache.Flush (addr, size);
1527#endif
1528
Chris Lattner24943d22010-06-08 16:52:24 +00001529 if (buf == NULL || size == 0)
1530 return 0;
1531 // We need to write any data that would go where any current software traps
1532 // (enabled software breakpoints) any software traps (breakpoints) that we
1533 // may have placed in our tasks memory.
1534
1535 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1536 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1537
1538 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1539 return DoWriteMemory(addr, buf, size, error);
1540
1541 BreakpointSiteList::collection::const_iterator pos;
1542 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001543 addr_t intersect_addr = 0;
1544 size_t intersect_size = 0;
1545 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001546 const uint8_t *ubuf = (const uint8_t *)buf;
1547
1548 for (pos = iter; pos != end; ++pos)
1549 {
1550 BreakpointSiteSP bp;
1551 bp = pos->second;
1552
1553 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1554 assert(addr <= intersect_addr && intersect_addr < addr + size);
1555 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1556 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1557
1558 // Check for bytes before this breakpoint
1559 const addr_t curr_addr = addr + bytes_written;
1560 if (intersect_addr > curr_addr)
1561 {
1562 // There are some bytes before this breakpoint that we need to
1563 // just write to memory
1564 size_t curr_size = intersect_addr - curr_addr;
1565 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1566 ubuf + bytes_written,
1567 curr_size,
1568 error);
1569 bytes_written += curr_bytes_written;
1570 if (curr_bytes_written != curr_size)
1571 {
1572 // We weren't able to write all of the requested bytes, we
1573 // are done looping and will return the number of bytes that
1574 // we have written so far.
1575 break;
1576 }
1577 }
1578
1579 // Now write any bytes that would cover up any software breakpoints
1580 // directly into the breakpoint opcode buffer
1581 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1582 bytes_written += intersect_size;
1583 }
1584
1585 // Write any remaining bytes after the last breakpoint if we have any left
1586 if (bytes_written < size)
1587 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1588 ubuf + bytes_written,
1589 size - bytes_written,
1590 error);
1591
1592 return bytes_written;
1593}
1594
1595addr_t
1596Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1597{
1598 // Fixme: we should track the blocks we've allocated, and clean them up...
1599 // We could even do our own allocator here if that ends up being more efficient.
Greg Clayton2860ba92011-01-23 19:58:49 +00001600 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1601 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1602 if (log)
Greg Claytonb349adc2011-01-24 06:30:45 +00001603 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001604 size,
1605 permissions & ePermissionsReadable ? 'r' : '-',
1606 permissions & ePermissionsWritable ? 'w' : '-',
1607 permissions & ePermissionsExecutable ? 'x' : '-',
1608 (uint64_t)allocated_addr,
1609 m_stop_id);
1610 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001611}
1612
1613Error
1614Process::DeallocateMemory (addr_t ptr)
1615{
Greg Clayton2860ba92011-01-23 19:58:49 +00001616 Error error(DoDeallocateMemory (ptr));
1617
1618 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1619 if (log)
1620 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1621 ptr,
1622 error.AsCString("SUCCESS"),
1623 m_stop_id);
1624 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001625}
1626
1627
1628Error
1629Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1630{
1631 Error error;
1632 error.SetErrorString("watchpoints are not supported");
1633 return error;
1634}
1635
1636Error
1637Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1638{
1639 Error error;
1640 error.SetErrorString("watchpoints are not supported");
1641 return error;
1642}
1643
1644StateType
1645Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1646{
1647 StateType state;
1648 // Now wait for the process to launch and return control to us, and then
1649 // call DidLaunch:
1650 while (1)
1651 {
Greg Clayton72e1c782011-01-22 23:43:18 +00001652 event_sp.reset();
1653 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
1654
1655 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00001656 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00001657
1658 // If state is invalid, then we timed out
1659 if (state == eStateInvalid)
1660 break;
1661
1662 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001663 HandlePrivateEvent (event_sp);
1664 }
1665 return state;
1666}
1667
1668Error
1669Process::Launch
1670(
1671 char const *argv[],
1672 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00001673 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00001674 const char *stdin_path,
1675 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001676 const char *stderr_path,
1677 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00001678)
1679{
1680 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001681 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00001682 m_dyld_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001683 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001684
1685 Module *exe_module = m_target.GetExecutableModule().get();
1686 if (exe_module)
1687 {
1688 char exec_file_path[PATH_MAX];
1689 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
1690 if (exe_module->GetFileSpec().Exists())
1691 {
Greg Claytona2f74232011-02-24 22:24:29 +00001692 if (PrivateStateThreadIsValid ())
1693 PausePrivateStateThread ();
1694
Chris Lattner24943d22010-06-08 16:52:24 +00001695 error = WillLaunch (exe_module);
1696 if (error.Success())
1697 {
Greg Claytond8c62532010-10-07 04:19:01 +00001698 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00001699 // The args coming in should not contain the application name, the
1700 // lldb_private::Process class will add this in case the executable
1701 // gets resolved to a different file than was given on the command
1702 // line (like when an applicaiton bundle is specified and will
1703 // resolve to the contained exectuable file, or the file given was
1704 // a symlink or other file system link that resolves to a different
1705 // file).
1706
1707 // Get the resolved exectuable path
1708
1709 // Make a new argument vector
1710 std::vector<const char *> exec_path_plus_argv;
1711 // Append the resolved executable path
1712 exec_path_plus_argv.push_back (exec_file_path);
1713
1714 // Push all args if there are any
1715 if (argv)
1716 {
1717 for (int i = 0; argv[i]; ++i)
1718 exec_path_plus_argv.push_back(argv[i]);
1719 }
1720
1721 // Push a NULL to terminate the args.
1722 exec_path_plus_argv.push_back(NULL);
1723
1724 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00001725 error = DoLaunch (exe_module,
1726 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
1727 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00001728 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00001729 stdin_path,
1730 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00001731 stderr_path,
1732 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00001733
1734 if (error.Fail())
1735 {
1736 if (GetID() != LLDB_INVALID_PROCESS_ID)
1737 {
1738 SetID (LLDB_INVALID_PROCESS_ID);
1739 const char *error_string = error.AsCString();
1740 if (error_string == NULL)
1741 error_string = "launch failed";
1742 SetExitStatus (-1, error_string);
1743 }
1744 }
1745 else
1746 {
1747 EventSP event_sp;
1748 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1749
1750 if (state == eStateStopped || state == eStateCrashed)
1751 {
Greg Clayton75c703d2011-02-16 04:46:07 +00001752
Chris Lattner24943d22010-06-08 16:52:24 +00001753 DidLaunch ();
1754
Greg Clayton4fdf7602011-03-20 04:57:14 +00001755 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00001756 if (m_dyld_ap.get())
1757 m_dyld_ap->DidLaunch();
1758
Chris Lattner24943d22010-06-08 16:52:24 +00001759 // This delays passing the stopped event to listeners till DidLaunch gets
1760 // a chance to complete...
1761 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00001762
1763 if (PrivateStateThreadIsValid ())
1764 ResumePrivateStateThread ();
1765 else
1766 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001767 }
1768 else if (state == eStateExited)
1769 {
1770 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1771 // not likely to work, and return an invalid pid.
1772 HandlePrivateEvent (event_sp);
1773 }
1774 }
1775 }
1776 }
1777 else
1778 {
1779 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1780 }
1781 }
1782 return error;
1783}
1784
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001785Process::NextEventAction::EventActionResult
1786Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00001787{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001788 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
1789 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00001790 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001791 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00001792 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001793 return eEventActionRetry;
1794
1795 case eStateStopped:
1796 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00001797 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001798 // During attach, prior to sending the eStateStopped event,
1799 // lldb_private::Process subclasses must set the process must set
1800 // the new process ID.
1801 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00001802 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001803 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00001804 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001805
1806
1807 break;
1808 default:
1809 case eStateExited:
1810 case eStateInvalid:
1811 m_exit_string.assign ("No valid Process");
1812 return eEventActionExit;
1813 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001814 }
1815}
Chris Lattner24943d22010-06-08 16:52:24 +00001816
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001817Process::NextEventAction::EventActionResult
1818Process::AttachCompletionHandler::HandleBeingInterrupted()
1819{
1820 return eEventActionSuccess;
1821}
1822
1823const char *
1824Process::AttachCompletionHandler::GetExitString ()
1825{
1826 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00001827}
1828
1829Error
1830Process::Attach (lldb::pid_t attach_pid)
1831{
1832
Chris Lattner24943d22010-06-08 16:52:24 +00001833 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001834 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00001835
Jim Ingham7508e732010-08-09 23:31:02 +00001836 // Find the process and its architecture. Make sure it matches the architecture
1837 // of the current Target, and if not adjust it.
1838
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001839 ProcessInfo process_info;
Greg Claytonb1888f22011-03-19 01:12:21 +00001840 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001841 if (platform_sp)
Jim Ingham7508e732010-08-09 23:31:02 +00001842 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001843 if (platform_sp->GetProcessInfo (attach_pid, process_info))
1844 {
1845 const ArchSpec &process_arch = process_info.GetArchitecture();
1846 if (process_arch.IsValid())
1847 GetTarget().SetArchitecture(process_arch);
1848 }
Jim Ingham7508e732010-08-09 23:31:02 +00001849 }
1850
Greg Clayton75c703d2011-02-16 04:46:07 +00001851 m_dyld_ap.reset();
1852
Greg Clayton54e7afa2010-07-09 20:39:50 +00001853 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001854 if (error.Success())
1855 {
Greg Claytond8c62532010-10-07 04:19:01 +00001856 SetPublicState (eStateAttaching);
1857
Greg Clayton54e7afa2010-07-09 20:39:50 +00001858 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00001859 if (error.Success())
1860 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00001861 SetNextEventAction(new Process::AttachCompletionHandler(this));
1862 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00001863 }
1864 else
1865 {
1866 if (GetID() != LLDB_INVALID_PROCESS_ID)
1867 {
1868 SetID (LLDB_INVALID_PROCESS_ID);
1869 const char *error_string = error.AsCString();
1870 if (error_string == NULL)
1871 error_string = "attach failed";
1872
1873 SetExitStatus(-1, error_string);
1874 }
1875 }
1876 }
1877 return error;
1878}
1879
1880Error
1881Process::Attach (const char *process_name, bool wait_for_launch)
1882{
Chris Lattner24943d22010-06-08 16:52:24 +00001883 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00001884 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00001885
1886 // Find the process and its architecture. Make sure it matches the architecture
1887 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001888 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00001889
Jim Inghamea294182010-08-17 21:54:19 +00001890 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00001891 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001892 ProcessInfoList process_infos;
Greg Claytonb1888f22011-03-19 01:12:21 +00001893 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001894 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00001895 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00001896 ProcessInfoMatch match_info;
1897 match_info.GetProcessInfo().SetName(process_name);
1898 match_info.SetNameMatchType (eNameMatchEquals);
1899 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001900 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00001901 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001902 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
1903 }
1904 else if (process_infos.GetSize() == 0)
1905 {
1906 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
1907 }
1908 else
1909 {
1910 ProcessInfo process_info;
1911 if (process_infos.GetInfoAtIndex (0, process_info))
1912 {
1913 const ArchSpec &process_arch = process_info.GetArchitecture();
1914 if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
1915 {
1916 // Set the architecture on the target.
1917 GetTarget().SetArchitecture (process_arch);
1918 }
1919 }
Chris Lattner24943d22010-06-08 16:52:24 +00001920 }
1921 }
1922 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001923 {
1924 error.SetErrorString ("Invalid platform");
1925 }
1926 }
1927
1928 if (error.Success())
1929 {
1930 m_dyld_ap.reset();
1931
1932 error = WillAttachToProcessWithName(process_name, wait_for_launch);
1933 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00001934 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001935 SetPublicState (eStateAttaching);
1936 error = DoAttachToProcessWithName (process_name, wait_for_launch);
1937 if (error.Fail())
1938 {
1939 if (GetID() != LLDB_INVALID_PROCESS_ID)
1940 {
1941 SetID (LLDB_INVALID_PROCESS_ID);
1942 const char *error_string = error.AsCString();
1943 if (error_string == NULL)
1944 error_string = "attach failed";
1945
1946 SetExitStatus(-1, error_string);
1947 }
1948 }
1949 else
1950 {
1951 SetNextEventAction(new Process::AttachCompletionHandler(this));
1952 StartPrivateStateThread();
1953 }
Chris Lattner24943d22010-06-08 16:52:24 +00001954 }
1955 }
1956 return error;
1957}
1958
Greg Clayton75c703d2011-02-16 04:46:07 +00001959void
1960Process::CompleteAttach ()
1961{
1962 // Let the process subclass figure out at much as it can about the process
1963 // before we go looking for a dynamic loader plug-in.
1964 DidAttach();
1965
1966 // We have complete the attach, now it is time to find the dynamic loader
1967 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00001968 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00001969 if (m_dyld_ap.get())
1970 m_dyld_ap->DidAttach();
1971
1972 // Figure out which one is the executable, and set that in our target:
1973 ModuleList &modules = m_target.GetImages();
1974
1975 size_t num_modules = modules.GetSize();
1976 for (int i = 0; i < num_modules; i++)
1977 {
1978 ModuleSP module_sp (modules.GetModuleAtIndex(i));
1979 if (module_sp->IsExecutable())
1980 {
1981 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
1982 if (target_exe_module_sp != module_sp)
1983 m_target.SetExecutableModule (module_sp, false);
1984 break;
1985 }
1986 }
1987}
1988
Chris Lattner24943d22010-06-08 16:52:24 +00001989Error
Greg Claytone71e2582011-02-04 01:58:07 +00001990Process::ConnectRemote (const char *remote_url)
1991{
Greg Claytone71e2582011-02-04 01:58:07 +00001992 m_abi_sp.reset();
1993 m_process_input_reader.reset();
1994
1995 // Find the process and its architecture. Make sure it matches the architecture
1996 // of the current Target, and if not adjust it.
1997
1998 Error error (DoConnectRemote (remote_url));
1999 if (error.Success())
2000 {
Greg Claytona2f74232011-02-24 22:24:29 +00002001 if (GetID() != LLDB_INVALID_PROCESS_ID)
2002 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002003 EventSP event_sp;
2004 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2005
2006 if (state == eStateStopped || state == eStateCrashed)
2007 {
2008 // If we attached and actually have a process on the other end, then
2009 // this ended up being the equivalent of an attach.
2010 CompleteAttach ();
2011
2012 // This delays passing the stopped event to listeners till
2013 // CompleteAttach gets a chance to complete...
2014 HandlePrivateEvent (event_sp);
2015
2016 }
Greg Claytona2f74232011-02-24 22:24:29 +00002017 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002018
2019 if (PrivateStateThreadIsValid ())
2020 ResumePrivateStateThread ();
2021 else
2022 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002023 }
2024 return error;
2025}
2026
2027
2028Error
Chris Lattner24943d22010-06-08 16:52:24 +00002029Process::Resume ()
2030{
Greg Claytone005f2c2010-11-06 01:53:30 +00002031 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002032 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002033 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
2034 m_stop_id,
2035 StateAsCString(m_public_state.GetValue()),
2036 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002037
2038 Error error (WillResume());
2039 // Tell the process it is about to resume before the thread list
2040 if (error.Success())
2041 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002042 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002043 // can let all of our threads know that they are about to be
2044 // resumed. Threads will each be called with
2045 // Thread::WillResume(StateType) where StateType contains the state
2046 // that they are supposed to have when the process is resumed
2047 // (suspended/running/stepping). Threads should also check
2048 // their resume signal in lldb::Thread::GetResumeSignal()
2049 // to see if they are suppoed to start back up with a signal.
2050 if (m_thread_list.WillResume())
2051 {
2052 error = DoResume();
2053 if (error.Success())
2054 {
2055 DidResume();
2056 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002057 if (log)
2058 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002059 }
2060 }
2061 else
2062 {
Jim Inghamac959662011-01-24 06:34:17 +00002063 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002064 }
2065 }
Jim Inghamac959662011-01-24 06:34:17 +00002066 else if (log)
2067 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002068 return error;
2069}
2070
2071Error
2072Process::Halt ()
2073{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002074 // Pause our private state thread so we can ensure no one else eats
2075 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002076 Listener halt_listener ("lldb.process.halt_listener");
2077 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002078
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002079 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002080 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002081
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002082 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002083 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002084
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002085 bool caused_stop = false;
2086
2087 // Ask the process subclass to actually halt our process
2088 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002089 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002090 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002091 if (m_public_state.GetValue() == eStateAttaching)
2092 {
2093 SetExitStatus(SIGKILL, "Cancelled async attach.");
2094 Destroy ();
2095 }
2096 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002097 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002098 // If "caused_stop" is true, then DoHalt stopped the process. If
2099 // "caused_stop" is false, the process was already stopped.
2100 // If the DoHalt caused the process to stop, then we want to catch
2101 // this event and set the interrupted bool to true before we pass
2102 // this along so clients know that the process was interrupted by
2103 // a halt command.
2104 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002105 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002106 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002107 TimeValue timeout_time;
2108 timeout_time = TimeValue::Now();
2109 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002110 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2111 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002112
Jim Inghamf9f40c22011-02-08 05:20:59 +00002113 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002114 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002115 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002116 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002117 }
2118 else
2119 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002120 if (StateIsStoppedState (state))
2121 {
2122 // We caused the process to interrupt itself, so mark this
2123 // as such in the stop event so clients can tell an interrupted
2124 // process from a natural stop
2125 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2126 }
2127 else
2128 {
2129 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2130 if (log)
2131 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2132 error.SetErrorString ("Did not get stopped event after halt.");
2133 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002134 }
2135 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002136 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002137 }
2138 }
Chris Lattner24943d22010-06-08 16:52:24 +00002139 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002140 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002141 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002142
2143 // Post any event we might have consumed. If all goes well, we will have
2144 // stopped the process, intercepted the event and set the interrupted
2145 // bool in the event. Post it to the private event queue and that will end up
2146 // correctly setting the state.
2147 if (event_sp)
2148 m_private_state_broadcaster.BroadcastEvent(event_sp);
2149
Chris Lattner24943d22010-06-08 16:52:24 +00002150 return error;
2151}
2152
2153Error
2154Process::Detach ()
2155{
2156 Error error (WillDetach());
2157
2158 if (error.Success())
2159 {
2160 DisableAllBreakpointSites();
2161 error = DoDetach();
2162 if (error.Success())
2163 {
2164 DidDetach();
2165 StopPrivateStateThread();
2166 }
2167 }
2168 return error;
2169}
2170
2171Error
2172Process::Destroy ()
2173{
2174 Error error (WillDestroy());
2175 if (error.Success())
2176 {
2177 DisableAllBreakpointSites();
2178 error = DoDestroy();
2179 if (error.Success())
2180 {
2181 DidDestroy();
2182 StopPrivateStateThread();
2183 }
Caroline Tice861efb32010-11-16 05:07:41 +00002184 m_stdio_communication.StopReadThread();
2185 m_stdio_communication.Disconnect();
2186 if (m_process_input_reader && m_process_input_reader->IsActive())
2187 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2188 if (m_process_input_reader)
2189 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002190 }
2191 return error;
2192}
2193
2194Error
2195Process::Signal (int signal)
2196{
2197 Error error (WillSignal());
2198 if (error.Success())
2199 {
2200 error = DoSignal(signal);
2201 if (error.Success())
2202 DidSignal();
2203 }
2204 return error;
2205}
2206
Greg Clayton395fc332011-02-15 21:59:32 +00002207lldb::ByteOrder
2208Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002209{
Greg Clayton395fc332011-02-15 21:59:32 +00002210 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002211}
2212
2213uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002214Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002215{
Greg Clayton395fc332011-02-15 21:59:32 +00002216 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002217}
2218
Greg Clayton395fc332011-02-15 21:59:32 +00002219
Chris Lattner24943d22010-06-08 16:52:24 +00002220bool
2221Process::ShouldBroadcastEvent (Event *event_ptr)
2222{
2223 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2224 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002225 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002226
2227 switch (state)
2228 {
Greg Claytone71e2582011-02-04 01:58:07 +00002229 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002230 case eStateAttaching:
2231 case eStateLaunching:
2232 case eStateDetached:
2233 case eStateExited:
2234 case eStateUnloaded:
2235 // These events indicate changes in the state of the debugging session, always report them.
2236 return_value = true;
2237 break;
2238 case eStateInvalid:
2239 // We stopped for no apparent reason, don't report it.
2240 return_value = false;
2241 break;
2242 case eStateRunning:
2243 case eStateStepping:
2244 // If we've started the target running, we handle the cases where we
2245 // are already running and where there is a transition from stopped to
2246 // running differently.
2247 // running -> running: Automatically suppress extra running events
2248 // stopped -> running: Report except when there is one or more no votes
2249 // and no yes votes.
2250 SynchronouslyNotifyStateChanged (state);
2251 switch (m_public_state.GetValue())
2252 {
2253 case eStateRunning:
2254 case eStateStepping:
2255 // We always suppress multiple runnings with no PUBLIC stop in between.
2256 return_value = false;
2257 break;
2258 default:
2259 // TODO: make this work correctly. For now always report
2260 // run if we aren't running so we don't miss any runnning
2261 // events. If I run the lldb/test/thread/a.out file and
2262 // break at main.cpp:58, run and hit the breakpoints on
2263 // multiple threads, then somehow during the stepping over
2264 // of all breakpoints no run gets reported.
2265 return_value = true;
2266
2267 // This is a transition from stop to run.
2268 switch (m_thread_list.ShouldReportRun (event_ptr))
2269 {
2270 case eVoteYes:
2271 case eVoteNoOpinion:
2272 return_value = true;
2273 break;
2274 case eVoteNo:
2275 return_value = false;
2276 break;
2277 }
2278 break;
2279 }
2280 break;
2281 case eStateStopped:
2282 case eStateCrashed:
2283 case eStateSuspended:
2284 {
2285 // We've stopped. First see if we're going to restart the target.
2286 // If we are going to stop, then we always broadcast the event.
2287 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002288 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002289 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002290 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002291 if (log)
2292 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002293 return true;
2294 }
2295 else
2296 {
Chris Lattner24943d22010-06-08 16:52:24 +00002297 RefreshStateAfterStop ();
2298
2299 if (m_thread_list.ShouldStop (event_ptr) == false)
2300 {
2301 switch (m_thread_list.ShouldReportStop (event_ptr))
2302 {
2303 case eVoteYes:
2304 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002305 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002306 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002307 case eVoteNo:
2308 return_value = false;
2309 break;
2310 }
2311
2312 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002313 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002314 Resume ();
2315 }
2316 else
2317 {
2318 return_value = true;
2319 SynchronouslyNotifyStateChanged (state);
2320 }
2321 }
2322 }
2323 }
2324
2325 if (log)
2326 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2327 return return_value;
2328}
2329
Chris Lattner24943d22010-06-08 16:52:24 +00002330
2331bool
2332Process::StartPrivateStateThread ()
2333{
Greg Claytone005f2c2010-11-06 01:53:30 +00002334 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002335
2336 if (log)
2337 log->Printf ("Process::%s ( )", __FUNCTION__);
2338
2339 // Create a thread that watches our internal state and controls which
2340 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002341 char thread_name[1024];
2342 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2343 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002344 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002345}
2346
2347void
2348Process::PausePrivateStateThread ()
2349{
2350 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2351}
2352
2353void
2354Process::ResumePrivateStateThread ()
2355{
2356 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2357}
2358
2359void
2360Process::StopPrivateStateThread ()
2361{
2362 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2363}
2364
2365void
2366Process::ControlPrivateStateThread (uint32_t signal)
2367{
Greg Claytone005f2c2010-11-06 01:53:30 +00002368 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002369
2370 assert (signal == eBroadcastInternalStateControlStop ||
2371 signal == eBroadcastInternalStateControlPause ||
2372 signal == eBroadcastInternalStateControlResume);
2373
2374 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002375 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002376
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002377 // Signal the private state thread. First we should copy this is case the
2378 // thread starts exiting since the private state thread will NULL this out
2379 // when it exits
2380 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002381 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002382 {
2383 TimeValue timeout_time;
2384 bool timed_out;
2385
2386 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2387
2388 timeout_time = TimeValue::Now();
2389 timeout_time.OffsetWithSeconds(2);
2390 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2391 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2392
2393 if (signal == eBroadcastInternalStateControlStop)
2394 {
2395 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002396 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002397
2398 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002399 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002400 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002401 }
2402 }
2403}
2404
2405void
2406Process::HandlePrivateEvent (EventSP &event_sp)
2407{
Greg Claytone005f2c2010-11-06 01:53:30 +00002408 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002409
Greg Clayton68ca8232011-01-25 02:58:48 +00002410 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002411
2412 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002413 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002414 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002415 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002416 switch (action_result)
2417 {
2418 case NextEventAction::eEventActionSuccess:
2419 SetNextEventAction(NULL);
2420 break;
2421 case NextEventAction::eEventActionRetry:
2422 break;
2423 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002424 // Handle Exiting Here. If we already got an exited event,
2425 // we should just propagate it. Otherwise, swallow this event,
2426 // and set our state to exit so the next event will kill us.
2427 if (new_state != eStateExited)
2428 {
2429 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002430 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002431 SetNextEventAction(NULL);
2432 return;
2433 }
2434 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002435 break;
2436 }
2437 }
2438
Chris Lattner24943d22010-06-08 16:52:24 +00002439 // See if we should broadcast this state to external clients?
2440 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002441
2442 if (should_broadcast)
2443 {
2444 if (log)
2445 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002446 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2447 __FUNCTION__,
2448 GetID(),
2449 StateAsCString(new_state),
2450 StateAsCString (GetState ()),
2451 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002452 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002453 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002454 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002455 PushProcessInputReader ();
2456 else
2457 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002458
Chris Lattner24943d22010-06-08 16:52:24 +00002459 BroadcastEvent (event_sp);
2460 }
2461 else
2462 {
2463 if (log)
2464 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002465 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2466 __FUNCTION__,
2467 GetID(),
2468 StateAsCString(new_state),
2469 StateAsCString (GetState ()),
2470 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002471 }
2472 }
2473}
2474
2475void *
2476Process::PrivateStateThread (void *arg)
2477{
2478 Process *proc = static_cast<Process*> (arg);
2479 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002480 return result;
2481}
2482
2483void *
2484Process::RunPrivateStateThread ()
2485{
2486 bool control_only = false;
2487 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2488
Greg Claytone005f2c2010-11-06 01:53:30 +00002489 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002490 if (log)
2491 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2492
2493 bool exit_now = false;
2494 while (!exit_now)
2495 {
2496 EventSP event_sp;
2497 WaitForEventsPrivate (NULL, event_sp, control_only);
2498 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2499 {
2500 switch (event_sp->GetType())
2501 {
2502 case eBroadcastInternalStateControlStop:
2503 exit_now = true;
2504 continue; // Go to next loop iteration so we exit without
2505 break; // doing any internal state managment below
2506
2507 case eBroadcastInternalStateControlPause:
2508 control_only = true;
2509 break;
2510
2511 case eBroadcastInternalStateControlResume:
2512 control_only = false;
2513 break;
2514 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002515
Jim Ingham3ae449a2010-11-17 02:32:00 +00002516 if (log)
2517 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2518
Chris Lattner24943d22010-06-08 16:52:24 +00002519 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002520 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002521 }
2522
2523
2524 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2525
2526 if (internal_state != eStateInvalid)
2527 {
2528 HandlePrivateEvent (event_sp);
2529 }
2530
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002531 if (internal_state == eStateInvalid ||
2532 internal_state == eStateExited ||
2533 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002534 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002535 if (log)
2536 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2537
Chris Lattner24943d22010-06-08 16:52:24 +00002538 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002539 }
Chris Lattner24943d22010-06-08 16:52:24 +00002540 }
2541
Caroline Tice926060e2010-10-29 21:48:37 +00002542 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002543 if (log)
2544 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2545
Greg Claytona4881d02011-01-22 07:12:45 +00002546 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2547 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002548 return NULL;
2549}
2550
Chris Lattner24943d22010-06-08 16:52:24 +00002551//------------------------------------------------------------------
2552// Process Event Data
2553//------------------------------------------------------------------
2554
2555Process::ProcessEventData::ProcessEventData () :
2556 EventData (),
2557 m_process_sp (),
2558 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002559 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002560 m_update_state (false),
2561 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002562{
2563}
2564
2565Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2566 EventData (),
2567 m_process_sp (process_sp),
2568 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002569 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002570 m_update_state (false),
2571 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002572{
2573}
2574
2575Process::ProcessEventData::~ProcessEventData()
2576{
2577}
2578
2579const ConstString &
2580Process::ProcessEventData::GetFlavorString ()
2581{
2582 static ConstString g_flavor ("Process::ProcessEventData");
2583 return g_flavor;
2584}
2585
2586const ConstString &
2587Process::ProcessEventData::GetFlavor () const
2588{
2589 return ProcessEventData::GetFlavorString ();
2590}
2591
Chris Lattner24943d22010-06-08 16:52:24 +00002592void
2593Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2594{
2595 // This function gets called twice for each event, once when the event gets pulled
2596 // off of the private process event queue, and once when it gets pulled off of
2597 // the public event queue. m_update_state is used to distinguish these
2598 // two cases; it is false when we're just pulling it off for private handling,
2599 // and we don't want to do the breakpoint command handling then.
2600
2601 if (!m_update_state)
2602 return;
2603
2604 m_process_sp->SetPublicState (m_state);
2605
2606 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2607 if (m_state == eStateStopped && ! m_restarted)
2608 {
2609 int num_threads = m_process_sp->GetThreadList().GetSize();
2610 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002611
Chris Lattner24943d22010-06-08 16:52:24 +00002612 for (idx = 0; idx < num_threads; ++idx)
2613 {
2614 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2615
Jim Ingham6297a3a2010-10-20 00:39:53 +00002616 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2617 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002618 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002619 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00002620 }
2621 }
Greg Clayton643ee732010-08-04 01:40:35 +00002622
Jim Ingham6fb8baa2010-08-10 00:59:59 +00002623 // The stop action might restart the target. If it does, then we want to mark that in the
2624 // event so that whoever is receiving it will know to wait for the running event and reflect
2625 // that state appropriately.
2626
Chris Lattner24943d22010-06-08 16:52:24 +00002627 if (m_process_sp->GetPrivateState() == eStateRunning)
2628 SetRestarted(true);
Jim Inghamd60d94a2011-03-11 03:53:59 +00002629 else
2630 {
2631 // Finally, if we didn't restart, run the Stop Hooks here:
2632 // They might also restart the target, so watch for that.
2633 m_process_sp->GetTarget().RunStopHooks();
2634 if (m_process_sp->GetPrivateState() == eStateRunning)
2635 SetRestarted(true);
2636 }
2637
Chris Lattner24943d22010-06-08 16:52:24 +00002638 }
2639}
2640
2641void
2642Process::ProcessEventData::Dump (Stream *s) const
2643{
2644 if (m_process_sp)
2645 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
2646
2647 s->Printf("state = %s", StateAsCString(GetState()));;
2648}
2649
2650const Process::ProcessEventData *
2651Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
2652{
2653 if (event_ptr)
2654 {
2655 const EventData *event_data = event_ptr->GetData();
2656 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
2657 return static_cast <const ProcessEventData *> (event_ptr->GetData());
2658 }
2659 return NULL;
2660}
2661
2662ProcessSP
2663Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
2664{
2665 ProcessSP process_sp;
2666 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2667 if (data)
2668 process_sp = data->GetProcessSP();
2669 return process_sp;
2670}
2671
2672StateType
2673Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
2674{
2675 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2676 if (data == NULL)
2677 return eStateInvalid;
2678 else
2679 return data->GetState();
2680}
2681
2682bool
2683Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
2684{
2685 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2686 if (data == NULL)
2687 return false;
2688 else
2689 return data->GetRestarted();
2690}
2691
2692void
2693Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
2694{
2695 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2696 if (data != NULL)
2697 data->SetRestarted(new_value);
2698}
2699
2700bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00002701Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
2702{
2703 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
2704 if (data == NULL)
2705 return false;
2706 else
2707 return data->GetInterrupted ();
2708}
2709
2710void
2711Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
2712{
2713 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2714 if (data != NULL)
2715 data->SetInterrupted(new_value);
2716}
2717
2718bool
Chris Lattner24943d22010-06-08 16:52:24 +00002719Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
2720{
2721 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
2722 if (data)
2723 {
2724 data->SetUpdateStateOnRemoval();
2725 return true;
2726 }
2727 return false;
2728}
2729
Chris Lattner24943d22010-06-08 16:52:24 +00002730void
Greg Claytona830adb2010-10-04 01:05:56 +00002731Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00002732{
2733 exe_ctx.target = &m_target;
2734 exe_ctx.process = this;
2735 exe_ctx.thread = NULL;
2736 exe_ctx.frame = NULL;
2737}
2738
2739lldb::ProcessSP
2740Process::GetSP ()
2741{
2742 return GetTarget().GetProcessSP();
2743}
2744
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002745//uint32_t
2746//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2747//{
2748// return 0;
2749//}
2750//
2751//ArchSpec
2752//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
2753//{
2754// return Host::GetArchSpecForExistingProcess (pid);
2755//}
2756//
2757//ArchSpec
2758//Process::GetArchSpecForExistingProcess (const char *process_name)
2759//{
2760// return Host::GetArchSpecForExistingProcess (process_name);
2761//}
2762//
Caroline Tice861efb32010-11-16 05:07:41 +00002763void
2764Process::AppendSTDOUT (const char * s, size_t len)
2765{
Greg Clayton20d338f2010-11-18 05:57:03 +00002766 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00002767 m_stdout_data.append (s, len);
2768
Greg Claytonb3781332010-12-05 19:16:56 +00002769 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00002770}
2771
2772void
2773Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
2774{
2775 Process *process = (Process *) baton;
2776 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
2777}
2778
2779size_t
2780Process::ProcessInputReaderCallback (void *baton,
2781 InputReader &reader,
2782 lldb::InputReaderAction notification,
2783 const char *bytes,
2784 size_t bytes_len)
2785{
2786 Process *process = (Process *) baton;
2787
2788 switch (notification)
2789 {
2790 case eInputReaderActivate:
2791 break;
2792
2793 case eInputReaderDeactivate:
2794 break;
2795
2796 case eInputReaderReactivate:
2797 break;
2798
2799 case eInputReaderGotToken:
2800 {
2801 Error error;
2802 process->PutSTDIN (bytes, bytes_len, error);
2803 }
2804 break;
2805
Caroline Ticec4f55fe2010-11-19 20:47:54 +00002806 case eInputReaderInterrupt:
2807 process->Halt ();
2808 break;
2809
2810 case eInputReaderEndOfFile:
2811 process->AppendSTDOUT ("^D", 2);
2812 break;
2813
Caroline Tice861efb32010-11-16 05:07:41 +00002814 case eInputReaderDone:
2815 break;
2816
2817 }
2818
2819 return bytes_len;
2820}
2821
2822void
2823Process::ResetProcessInputReader ()
2824{
2825 m_process_input_reader.reset();
2826}
2827
2828void
2829Process::SetUpProcessInputReader (int file_descriptor)
2830{
2831 // First set up the Read Thread for reading/handling process I/O
2832
2833 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
2834
2835 if (conn_ap.get())
2836 {
2837 m_stdio_communication.SetConnection (conn_ap.release());
2838 if (m_stdio_communication.IsConnected())
2839 {
2840 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
2841 m_stdio_communication.StartReadThread();
2842
2843 // Now read thread is set up, set up input reader.
2844
2845 if (!m_process_input_reader.get())
2846 {
2847 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
2848 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
2849 this,
2850 eInputReaderGranularityByte,
2851 NULL,
2852 NULL,
2853 false));
2854
2855 if (err.Fail())
2856 m_process_input_reader.reset();
2857 }
2858 }
2859 }
2860}
2861
2862void
2863Process::PushProcessInputReader ()
2864{
2865 if (m_process_input_reader && !m_process_input_reader->IsActive())
2866 m_target.GetDebugger().PushInputReader (m_process_input_reader);
2867}
2868
2869void
2870Process::PopProcessInputReader ()
2871{
2872 if (m_process_input_reader && m_process_input_reader->IsActive())
2873 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2874}
2875
Greg Claytond284b662011-02-18 01:44:25 +00002876// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00002877void
Caroline Tice2a456812011-03-10 22:14:10 +00002878Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002879{
Greg Claytonb3448432011-03-24 21:19:54 +00002880 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00002881
2882 int i=0;
2883 const char *name;
2884 OptionEnumValueElement option_enum;
2885 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
2886 {
2887 if (name)
2888 {
2889 option_enum.value = i;
2890 option_enum.string_value = name;
2891 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
2892 g_plugins.push_back (option_enum);
2893 }
2894 ++i;
2895 }
2896 option_enum.value = 0;
2897 option_enum.string_value = NULL;
2898 option_enum.usage = NULL;
2899 g_plugins.push_back (option_enum);
2900
2901 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
2902 {
2903 if (::strcmp (name, "plugin") == 0)
2904 {
2905 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
2906 break;
2907 }
2908 }
Greg Clayton990de7b2010-11-18 23:32:35 +00002909 UserSettingsControllerSP &usc = GetSettingsController();
2910 usc.reset (new SettingsController);
2911 UserSettingsController::InitializeSettingsController (usc,
2912 SettingsController::global_settings_table,
2913 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00002914
2915 // Now call SettingsInitialize() for each 'child' of Process settings
2916 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00002917}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002918
Greg Clayton990de7b2010-11-18 23:32:35 +00002919void
Caroline Tice2a456812011-03-10 22:14:10 +00002920Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00002921{
Caroline Tice2a456812011-03-10 22:14:10 +00002922 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
2923
2924 Thread::SettingsTerminate ();
2925
2926 // Now terminate Process Settings.
2927
Greg Clayton990de7b2010-11-18 23:32:35 +00002928 UserSettingsControllerSP &usc = GetSettingsController();
2929 UserSettingsController::FinalizeSettingsController (usc);
2930 usc.reset();
2931}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002932
Greg Clayton990de7b2010-11-18 23:32:35 +00002933UserSettingsControllerSP &
2934Process::GetSettingsController ()
2935{
2936 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00002937 return g_settings_controller;
2938}
2939
Caroline Tice1ebef442010-09-27 00:30:10 +00002940void
2941Process::UpdateInstanceName ()
2942{
2943 ModuleSP module_sp = GetTarget().GetExecutableModule();
2944 if (module_sp)
2945 {
2946 StreamString sstr;
2947 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
2948
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00002949 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Caroline Tice1ebef442010-09-27 00:30:10 +00002950 sstr.GetData());
2951 }
2952}
2953
Greg Clayton427f2902010-12-14 02:59:59 +00002954ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00002955Process::RunThreadPlan (ExecutionContext &exe_ctx,
2956 lldb::ThreadPlanSP &thread_plan_sp,
2957 bool stop_others,
2958 bool try_all_threads,
2959 bool discard_on_error,
2960 uint32_t single_thread_timeout_usec,
2961 Stream &errors)
2962{
2963 ExecutionResults return_value = eExecutionSetupError;
2964
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002965 if (thread_plan_sp.get() == NULL)
2966 {
2967 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00002968 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00002969 }
2970
Jim Inghamac959662011-01-24 06:34:17 +00002971 if (m_private_state.GetValue() != eStateStopped)
2972 {
2973 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00002974 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00002975 }
2976
Jim Ingham360f53f2010-11-30 02:22:11 +00002977 // Save this value for restoration of the execution context after we run
2978 uint32_t tid = exe_ctx.thread->GetIndexID();
2979
2980 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
2981 // so we should arrange to reset them as well.
2982
2983 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
2984 lldb::StackFrameSP selected_frame_sp;
2985
2986 uint32_t selected_tid;
2987 if (selected_thread_sp != NULL)
2988 {
2989 selected_tid = selected_thread_sp->GetIndexID();
2990 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
2991 }
2992 else
2993 {
2994 selected_tid = LLDB_INVALID_THREAD_ID;
2995 }
2996
2997 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
2998
Jim Ingham6ae318c2011-01-23 21:14:08 +00002999 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003000
3001 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3002 // restored on exit to the function.
3003
3004 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003005
Jim Ingham6ae318c2011-01-23 21:14:08 +00003006 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003007 if (log)
3008 {
3009 StreamString s;
3010 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003011 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
3012 exe_ctx.thread->GetIndexID(),
3013 exe_ctx.thread->GetID(),
3014 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003015 }
3016
Jim Inghamf9f40c22011-02-08 05:20:59 +00003017 bool got_event;
3018 lldb::EventSP event_sp;
3019 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003020
3021 TimeValue* timeout_ptr = NULL;
3022 TimeValue real_timeout;
3023
Jim Inghamf9f40c22011-02-08 05:20:59 +00003024 bool first_timeout = true;
3025 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003026
Jim Ingham360f53f2010-11-30 02:22:11 +00003027 while (1)
3028 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003029 // We usually want to resume the process if we get to the top of the loop.
3030 // The only exception is if we get two running events with no intervening
3031 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003032
Jim Inghamf9f40c22011-02-08 05:20:59 +00003033 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003034 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003035 // Do the initial resume and wait for the running event before going further.
3036
3037 Error resume_error = exe_ctx.process->Resume ();
3038 if (!resume_error.Success())
3039 {
3040 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003041 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003042 break;
3043 }
3044
3045 real_timeout = TimeValue::Now();
3046 real_timeout.OffsetWithMicroSeconds(500000);
3047 timeout_ptr = &real_timeout;
3048
3049 got_event = listener.WaitForEvent(NULL, event_sp);
3050 if (!got_event)
3051 {
3052 if (log)
3053 log->Printf("Didn't get any event after initial resume, exiting.");
3054
3055 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003056 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003057 break;
3058 }
3059
3060 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3061 if (stop_state != eStateRunning)
3062 {
3063 if (log)
3064 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3065
3066 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003067 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003068 break;
3069 }
3070
3071 if (log)
3072 log->Printf ("Resuming succeeded.");
3073 // We need to call the function synchronously, so spin waiting for it to return.
3074 // If we get interrupted while executing, we're going to lose our context, and
3075 // won't be able to gather the result at this point.
3076 // We set the timeout AFTER the resume, since the resume takes some time and we
3077 // don't want to charge that to the timeout.
3078
3079 if (single_thread_timeout_usec != 0)
3080 {
3081 real_timeout = TimeValue::Now();
3082 if (first_timeout)
3083 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3084 else
3085 real_timeout.OffsetWithSeconds(10);
3086
3087 timeout_ptr = &real_timeout;
3088 }
3089 }
3090 else
3091 {
3092 if (log)
3093 log->Printf ("Handled an extra running event.");
3094 do_resume = true;
3095 }
3096
3097 // Now wait for the process to stop again:
3098 stop_state = lldb::eStateInvalid;
3099 event_sp.reset();
3100 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3101
3102 if (got_event)
3103 {
3104 if (event_sp.get())
3105 {
3106 bool keep_going = false;
3107 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3108 if (log)
3109 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3110
3111 switch (stop_state)
3112 {
3113 case lldb::eStateStopped:
3114 // Yay, we're done.
3115 if (log)
3116 log->Printf ("Execution completed successfully.");
Greg Claytonb3448432011-03-24 21:19:54 +00003117 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003118 break;
3119 case lldb::eStateCrashed:
3120 if (log)
3121 log->Printf ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003122 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003123 break;
3124 case lldb::eStateRunning:
3125 do_resume = false;
3126 keep_going = true;
3127 break;
3128 default:
3129 if (log)
3130 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003131 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003132 break;
3133 }
3134 if (keep_going)
3135 continue;
3136 else
3137 break;
3138 }
3139 else
3140 {
3141 if (log)
3142 log->Printf ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003143 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003144 break;
3145 }
3146 }
3147 else
3148 {
3149 // If we didn't get an event that means we've timed out...
3150 // We will interrupt the process here. Depending on what we were asked to do we will
3151 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003152 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003153
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003154 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003155 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003156 {
3157 if (first_timeout)
3158 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3159 "trying with all threads enabled.",
3160 single_thread_timeout_usec);
3161 else
3162 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3163 "and timeout: %d timed out.",
3164 single_thread_timeout_usec);
3165 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003166 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003167 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3168 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003169 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003170 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003171
Jim Inghamc556b462011-01-22 01:30:53 +00003172 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003173 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003174 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003175 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00003176 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003177
Jim Inghamf9f40c22011-02-08 05:20:59 +00003178 // If halt succeeds, it always produces a stopped event. Wait for that:
3179
3180 real_timeout = TimeValue::Now();
3181 real_timeout.OffsetWithMicroSeconds(500000);
3182
3183 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003184
3185 if (got_event)
3186 {
3187 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3188 if (log)
3189 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003190 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003191 if (stop_state == lldb::eStateStopped
3192 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003193 log->Printf (" Event was the Halt interruption event.");
3194 }
3195
Jim Inghamf9f40c22011-02-08 05:20:59 +00003196 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003197 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003198 // Between the time we initiated the Halt and the time we delivered it, the process could have
3199 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003200
Jim Inghamf9f40c22011-02-08 05:20:59 +00003201 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3202 {
3203 if (log)
3204 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3205 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003206 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003207 break;
3208 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003209
Jim Inghamf9f40c22011-02-08 05:20:59 +00003210 if (!try_all_threads)
3211 {
3212 if (log)
3213 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003214 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003215 break;
3216 }
3217
3218 if (first_timeout)
3219 {
3220 // Set all the other threads to run, and return to the top of the loop, which will continue;
3221 first_timeout = false;
3222 thread_plan_sp->SetStopOthers (false);
3223 if (log)
3224 log->Printf ("Process::RunThreadPlan(): About to resume.");
3225
3226 continue;
3227 }
3228 else
3229 {
3230 // Running all threads failed, so return Interrupted.
3231 if (log)
3232 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003233 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003234 break;
3235 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003236 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003237 }
3238 else
3239 { if (log)
3240 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
3241 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003242 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003243 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003244 }
3245 }
Jim Inghamc556b462011-01-22 01:30:53 +00003246 else
3247 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003248 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3249 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003250 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003251 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.",
3252 halt_error.AsCString());
3253 real_timeout = TimeValue::Now();
3254 real_timeout.OffsetWithMicroSeconds(500000);
3255 timeout_ptr = &real_timeout;
3256 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3257 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003258 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003259 // This is not going anywhere, bag out.
3260 if (log)
3261 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003262 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003263 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003264 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003265 else
3266 {
3267 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3268 if (log)
3269 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3270 if (stop_state == lldb::eStateStopped)
3271 {
3272 // Between the time we initiated the Halt and the time we delivered it, the process could have
3273 // already finished its job. Check that here:
3274
3275 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3276 {
3277 if (log)
3278 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3279 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003280 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003281 break;
3282 }
3283
3284 if (first_timeout)
3285 {
3286 // Set all the other threads to run, and return to the top of the loop, which will continue;
3287 first_timeout = false;
3288 thread_plan_sp->SetStopOthers (false);
3289 if (log)
3290 log->Printf ("Process::RunThreadPlan(): About to resume.");
3291
3292 continue;
3293 }
3294 else
3295 {
3296 // Running all threads failed, so return Interrupted.
3297 if (log)
3298 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003299 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003300 break;
3301 }
3302 }
3303 else
3304 {
3305 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3306 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003307 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003308 break;
3309 }
3310 }
Jim Inghamc556b462011-01-22 01:30:53 +00003311 }
3312
Jim Ingham360f53f2010-11-30 02:22:11 +00003313 }
3314
Jim Inghamf9f40c22011-02-08 05:20:59 +00003315 } // END WAIT LOOP
3316
3317 // Now do some processing on the results of the run:
3318 if (return_value == eExecutionInterrupted)
3319 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003320 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003321 {
3322 StreamString s;
3323 if (event_sp)
3324 event_sp->Dump (&s);
3325 else
3326 {
3327 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3328 }
3329
3330 StreamString ts;
3331
3332 const char *event_explanation;
3333
3334 do
3335 {
3336 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3337
3338 if (!event_data)
3339 {
3340 event_explanation = "<no event data>";
3341 break;
3342 }
3343
3344 Process *process = event_data->GetProcessSP().get();
3345
3346 if (!process)
3347 {
3348 event_explanation = "<no process>";
3349 break;
3350 }
3351
3352 ThreadList &thread_list = process->GetThreadList();
3353
3354 uint32_t num_threads = thread_list.GetSize();
3355 uint32_t thread_index;
3356
3357 ts.Printf("<%u threads> ", num_threads);
3358
3359 for (thread_index = 0;
3360 thread_index < num_threads;
3361 ++thread_index)
3362 {
3363 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3364
3365 if (!thread)
3366 {
3367 ts.Printf("<?> ");
3368 continue;
3369 }
3370
3371 ts.Printf("<0x%4.4x ", thread->GetID());
3372 RegisterContext *register_context = thread->GetRegisterContext().get();
3373
3374 if (register_context)
3375 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3376 else
3377 ts.Printf("[ip unknown] ");
3378
3379 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3380 if (stop_info_sp)
3381 {
3382 const char *stop_desc = stop_info_sp->GetDescription();
3383 if (stop_desc)
3384 ts.PutCString (stop_desc);
3385 }
3386 ts.Printf(">");
3387 }
3388
3389 event_explanation = ts.GetData();
3390 } while (0);
3391
3392 if (log)
3393 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3394
3395 if (discard_on_error && thread_plan_sp)
3396 {
3397 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3398 }
3399 }
3400 }
3401 else if (return_value == eExecutionSetupError)
3402 {
3403 if (log)
3404 log->Printf("Process::RunThreadPlan(): execution set up error.");
3405
3406 if (discard_on_error && thread_plan_sp)
3407 {
3408 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3409 }
3410 }
3411 else
3412 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003413 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3414 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003415 if (log)
3416 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003417 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003418 }
3419 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3420 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003421 if (log)
3422 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003423 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003424 }
3425 else
3426 {
3427 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003428 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003429 if (discard_on_error && thread_plan_sp)
3430 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003431 if (log)
3432 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003433 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3434 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003435 }
3436 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003437
Jim Ingham360f53f2010-11-30 02:22:11 +00003438 // Thread we ran the function in may have gone away because we ran the target
3439 // Check that it's still there.
3440 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3441 if (exe_ctx.thread)
3442 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3443
3444 // Also restore the current process'es selected frame & thread, since this function calling may
3445 // be done behind the user's back.
3446
3447 if (selected_tid != LLDB_INVALID_THREAD_ID)
3448 {
3449 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3450 {
3451 // We were able to restore the selected thread, now restore the frame:
3452 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3453 }
3454 }
3455
3456 return return_value;
3457}
3458
3459const char *
3460Process::ExecutionResultAsCString (ExecutionResults result)
3461{
3462 const char *result_name;
3463
3464 switch (result)
3465 {
Greg Claytonb3448432011-03-24 21:19:54 +00003466 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003467 result_name = "eExecutionCompleted";
3468 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003469 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003470 result_name = "eExecutionDiscarded";
3471 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003472 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003473 result_name = "eExecutionInterrupted";
3474 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003475 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003476 result_name = "eExecutionSetupError";
3477 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003478 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003479 result_name = "eExecutionTimedOut";
3480 break;
3481 }
3482 return result_name;
3483}
3484
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003485//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003486// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003487//--------------------------------------------------------------
3488
Greg Claytond0a5a232010-09-19 02:33:57 +00003489Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003490 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003491{
Greg Clayton638351a2010-12-04 00:10:17 +00003492 m_default_settings.reset (new ProcessInstanceSettings (*this,
3493 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00003494 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003495}
3496
Greg Claytond0a5a232010-09-19 02:33:57 +00003497Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003498{
3499}
3500
3501lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00003502Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003503{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003504 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3505 false,
3506 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003507 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3508 return new_settings_sp;
3509}
3510
3511//--------------------------------------------------------------
3512// class ProcessInstanceSettings
3513//--------------------------------------------------------------
3514
Greg Clayton638351a2010-12-04 00:10:17 +00003515ProcessInstanceSettings::ProcessInstanceSettings
3516(
3517 UserSettingsController &owner,
3518 bool live_instance,
3519 const char *name
3520) :
3521 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003522 m_run_args (),
3523 m_env_vars (),
3524 m_input_path (),
3525 m_output_path (),
3526 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00003527 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00003528 m_disable_stdio (false),
3529 m_inherit_host_env (true),
3530 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003531{
Caroline Tice396704b2010-09-09 18:26:37 +00003532 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3533 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3534 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00003535 // This is true for CreateInstanceName() too.
3536
3537 if (GetInstanceName () == InstanceSettings::InvalidName())
3538 {
3539 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3540 m_owner.RegisterInstanceSettings (this);
3541 }
Caroline Tice396704b2010-09-09 18:26:37 +00003542
3543 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003544 {
3545 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3546 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003547 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003548 }
3549}
3550
3551ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003552 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003553 m_run_args (rhs.m_run_args),
3554 m_env_vars (rhs.m_env_vars),
3555 m_input_path (rhs.m_input_path),
3556 m_output_path (rhs.m_output_path),
3557 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00003558 m_disable_aslr (rhs.m_disable_aslr),
3559 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003560{
3561 if (m_instance_name != InstanceSettings::GetDefaultName())
3562 {
3563 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3564 CopyInstanceSettings (pending_settings,false);
3565 m_owner.RemovePendingSettings (m_instance_name);
3566 }
3567}
3568
3569ProcessInstanceSettings::~ProcessInstanceSettings ()
3570{
3571}
3572
3573ProcessInstanceSettings&
3574ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3575{
3576 if (this != &rhs)
3577 {
3578 m_run_args = rhs.m_run_args;
3579 m_env_vars = rhs.m_env_vars;
3580 m_input_path = rhs.m_input_path;
3581 m_output_path = rhs.m_output_path;
3582 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003583 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003584 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00003585 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003586 }
3587
3588 return *this;
3589}
3590
3591
3592void
3593ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3594 const char *index_value,
3595 const char *value,
3596 const ConstString &instance_name,
3597 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00003598 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003599 Error &err,
3600 bool pending)
3601{
3602 if (var_name == RunArgsVarName())
3603 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3604 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00003605 {
3606 GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003607 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00003608 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003609 else if (var_name == InputPathVarName())
3610 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3611 else if (var_name == OutputPathVarName())
3612 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3613 else if (var_name == ErrorPathVarName())
3614 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003615 else if (var_name == DisableASLRVarName())
3616 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
Caroline Ticebd666012010-12-03 18:46:09 +00003617 else if (var_name == DisableSTDIOVarName ())
3618 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003619}
3620
3621void
3622ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
3623 bool pending)
3624{
3625 if (new_settings.get() == NULL)
3626 return;
3627
3628 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
3629
3630 m_run_args = new_process_settings->m_run_args;
3631 m_env_vars = new_process_settings->m_env_vars;
3632 m_input_path = new_process_settings->m_input_path;
3633 m_output_path = new_process_settings->m_output_path;
3634 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003635 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00003636 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003637}
3638
Caroline Ticebcb5b452010-09-20 21:37:42 +00003639bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003640ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
3641 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00003642 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00003643 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003644{
3645 if (var_name == RunArgsVarName())
3646 {
3647 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00003648 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003649 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
3650 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00003651 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003652 }
3653 else if (var_name == EnvVarsVarName())
3654 {
Greg Clayton638351a2010-12-04 00:10:17 +00003655 GetHostEnvironmentIfNeeded ();
3656
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003657 if (m_env_vars.size() > 0)
3658 {
3659 std::map<std::string, std::string>::iterator pos;
3660 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
3661 {
3662 StreamString value_str;
3663 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
3664 value.AppendString (value_str.GetData());
3665 }
3666 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003667 }
3668 else if (var_name == InputPathVarName())
3669 {
3670 value.AppendString (m_input_path.c_str());
3671 }
3672 else if (var_name == OutputPathVarName())
3673 {
3674 value.AppendString (m_output_path.c_str());
3675 }
3676 else if (var_name == ErrorPathVarName())
3677 {
3678 value.AppendString (m_error_path.c_str());
3679 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00003680 else if (var_name == InheritHostEnvVarName())
3681 {
3682 if (m_inherit_host_env)
3683 value.AppendString ("true");
3684 else
3685 value.AppendString ("false");
3686 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003687 else if (var_name == DisableASLRVarName())
3688 {
3689 if (m_disable_aslr)
3690 value.AppendString ("true");
3691 else
3692 value.AppendString ("false");
3693 }
Caroline Ticebd666012010-12-03 18:46:09 +00003694 else if (var_name == DisableSTDIOVarName())
3695 {
3696 if (m_disable_stdio)
3697 value.AppendString ("true");
3698 else
3699 value.AppendString ("false");
3700 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003701 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00003702 {
3703 if (err)
3704 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
3705 return false;
3706 }
3707 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003708}
3709
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003710const ConstString
3711ProcessInstanceSettings::CreateInstanceName ()
3712{
3713 static int instance_count = 1;
3714 StreamString sstr;
3715
3716 sstr.Printf ("process_%d", instance_count);
3717 ++instance_count;
3718
3719 const ConstString ret_val (sstr.GetData());
3720 return ret_val;
3721}
3722
3723const ConstString &
3724ProcessInstanceSettings::RunArgsVarName ()
3725{
3726 static ConstString run_args_var_name ("run-args");
3727
3728 return run_args_var_name;
3729}
3730
3731const ConstString &
3732ProcessInstanceSettings::EnvVarsVarName ()
3733{
3734 static ConstString env_vars_var_name ("env-vars");
3735
3736 return env_vars_var_name;
3737}
3738
3739const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00003740ProcessInstanceSettings::InheritHostEnvVarName ()
3741{
3742 static ConstString g_name ("inherit-env");
3743
3744 return g_name;
3745}
3746
3747const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003748ProcessInstanceSettings::InputPathVarName ()
3749{
3750 static ConstString input_path_var_name ("input-path");
3751
3752 return input_path_var_name;
3753}
3754
3755const ConstString &
3756ProcessInstanceSettings::OutputPathVarName ()
3757{
Caroline Tice87097232010-09-07 18:35:40 +00003758 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003759
3760 return output_path_var_name;
3761}
3762
3763const ConstString &
3764ProcessInstanceSettings::ErrorPathVarName ()
3765{
Caroline Tice87097232010-09-07 18:35:40 +00003766 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003767
3768 return error_path_var_name;
3769}
3770
3771const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003772ProcessInstanceSettings::DisableASLRVarName ()
3773{
3774 static ConstString disable_aslr_var_name ("disable-aslr");
3775
3776 return disable_aslr_var_name;
3777}
3778
Caroline Ticebd666012010-12-03 18:46:09 +00003779const ConstString &
3780ProcessInstanceSettings::DisableSTDIOVarName ()
3781{
3782 static ConstString disable_stdio_var_name ("disable-stdio");
3783
3784 return disable_stdio_var_name;
3785}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003786
3787//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003788// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003789//--------------------------------------------------
3790
3791SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003792Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003793{
3794 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
3795 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
3796};
3797
3798
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003799SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00003800Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003801{
Greg Clayton638351a2010-12-04 00:10:17 +00003802 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
3803 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
3804 { "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." },
3805 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00003806 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
3807 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
3808 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytond284b662011-02-18 01:44:25 +00003809 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00003810 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
3811 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3812 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003813};
3814
3815
Jim Ingham7508e732010-08-09 23:31:02 +00003816