1 //===-- Thread.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/lldb-private-log.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Debugger.h"
13 #include "lldb/Core/Log.h"
14 #include "lldb/Core/Stream.h"
15 #include "lldb/Core/StreamString.h"
16 #include "lldb/Core/RegularExpression.h"
17 #include "lldb/Host/Host.h"
18 #include "lldb/Target/DynamicLoader.h"
19 #include "lldb/Target/ExecutionContext.h"
20 #include "lldb/Target/ObjCLanguageRuntime.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/RegisterContext.h"
23 #include "lldb/Target/StopInfo.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Target/Thread.h"
26 #include "lldb/Target/ThreadPlan.h"
27 #include "lldb/Target/ThreadPlanCallFunction.h"
28 #include "lldb/Target/ThreadPlanBase.h"
29 #include "lldb/Target/ThreadPlanStepInstruction.h"
30 #include "lldb/Target/ThreadPlanStepOut.h"
31 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
32 #include "lldb/Target/ThreadPlanStepThrough.h"
33 #include "lldb/Target/ThreadPlanStepInRange.h"
34 #include "lldb/Target/ThreadPlanStepOverRange.h"
35 #include "lldb/Target/ThreadPlanRunToAddress.h"
36 #include "lldb/Target/ThreadPlanStepUntil.h"
37 #include "lldb/Target/ThreadSpec.h"
38 #include "lldb/Target/Unwind.h"
39 
40 using namespace lldb;
41 using namespace lldb_private;
42 
43 Thread::Thread (Process &process, lldb::tid_t tid) :
44     UserID (tid),
45     ThreadInstanceSettings (*(Thread::GetSettingsController().get())),
46     m_process (process),
47     m_actual_stop_info_sp (),
48     m_index_id (process.GetNextThreadIndexID ()),
49     m_reg_context_sp (),
50     m_state (eStateUnloaded),
51     m_state_mutex (Mutex::eMutexTypeRecursive),
52     m_plan_stack (),
53     m_completed_plan_stack(),
54     m_curr_frames_ap (),
55     m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
56     m_resume_state (eStateRunning),
57     m_unwinder_ap ()
58 
59 {
60     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
61     if (log)
62         log->Printf ("%p Thread::Thread(tid = 0x%4.4x)", this, GetID());
63 
64     QueueFundamentalPlan(true);
65     UpdateInstanceName();
66 }
67 
68 
69 Thread::~Thread()
70 {
71     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
72     if (log)
73         log->Printf ("%p Thread::~Thread(tid = 0x%4.4x)", this, GetID());
74 }
75 
76 int
77 Thread::GetResumeSignal () const
78 {
79     return m_resume_signal;
80 }
81 
82 void
83 Thread::SetResumeSignal (int signal)
84 {
85     m_resume_signal = signal;
86 }
87 
88 StateType
89 Thread::GetResumeState () const
90 {
91     return m_resume_state;
92 }
93 
94 void
95 Thread::SetResumeState (StateType state)
96 {
97     m_resume_state = state;
98 }
99 
100 lldb::StopInfoSP
101 Thread::GetStopInfo ()
102 {
103     ThreadPlanSP plan_sp (GetCompletedPlan());
104     if (plan_sp)
105         return StopInfo::CreateStopReasonWithPlan (plan_sp);
106     else
107         return GetPrivateStopReason ();
108 }
109 
110 bool
111 Thread::ThreadStoppedForAReason (void)
112 {
113     return GetPrivateStopReason () != NULL;
114 }
115 
116 StateType
117 Thread::GetState() const
118 {
119     // If any other threads access this we will need a mutex for it
120     Mutex::Locker locker(m_state_mutex);
121     return m_state;
122 }
123 
124 void
125 Thread::SetState(StateType state)
126 {
127     Mutex::Locker locker(m_state_mutex);
128     m_state = state;
129 }
130 
131 void
132 Thread::WillStop()
133 {
134     ThreadPlan *current_plan = GetCurrentPlan();
135 
136     // FIXME: I may decide to disallow threads with no plans.  In which
137     // case this should go to an assert.
138 
139     if (!current_plan)
140         return;
141 
142     current_plan->WillStop();
143 }
144 
145 void
146 Thread::SetupForResume ()
147 {
148     if (GetResumeState() != eStateSuspended)
149     {
150 
151         // If we're at a breakpoint push the step-over breakpoint plan.  Do this before
152         // telling the current plan it will resume, since we might change what the current
153         // plan is.
154 
155         lldb::addr_t pc = GetRegisterContext()->GetPC();
156         BreakpointSiteSP bp_site_sp = GetProcess().GetBreakpointSiteList().FindByAddress(pc);
157         if (bp_site_sp && bp_site_sp->IsEnabled())
158         {
159             // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
160             // special to step over a breakpoint.
161 
162             ThreadPlan *cur_plan = GetCurrentPlan();
163 
164             if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
165             {
166                 ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
167                 if (step_bp_plan)
168                 {
169                     ThreadPlanSP step_bp_plan_sp;
170                     step_bp_plan->SetPrivate (true);
171 
172                     if (GetCurrentPlan()->RunState() != eStateStepping)
173                     {
174                         step_bp_plan->SetAutoContinue(true);
175                     }
176                     step_bp_plan_sp.reset (step_bp_plan);
177                     QueueThreadPlan (step_bp_plan_sp, false);
178                 }
179             }
180         }
181     }
182 }
183 
184 bool
185 Thread::WillResume (StateType resume_state)
186 {
187     // At this point clear the completed plan stack.
188     m_completed_plan_stack.clear();
189     m_discarded_plan_stack.clear();
190 
191     StopInfo *stop_info = GetPrivateStopReason().get();
192     if (stop_info)
193         stop_info->WillResume (resume_state);
194 
195     // Tell all the plans that we are about to resume in case they need to clear any state.
196     // We distinguish between the plan on the top of the stack and the lower
197     // plans in case a plan needs to do any special business before it runs.
198 
199     ThreadPlan *plan_ptr = GetCurrentPlan();
200     plan_ptr->WillResume(resume_state, true);
201 
202     while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
203     {
204         plan_ptr->WillResume (resume_state, false);
205     }
206 
207     m_actual_stop_info_sp.reset();
208     return true;
209 }
210 
211 void
212 Thread::DidResume ()
213 {
214     SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
215 }
216 
217 bool
218 Thread::ShouldStop (Event* event_ptr)
219 {
220     ThreadPlan *current_plan = GetCurrentPlan();
221     bool should_stop = true;
222 
223     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
224     if (log)
225     {
226         StreamString s;
227         DumpThreadPlans(&s);
228         log->PutCString (s.GetData());
229     }
230 
231     if (current_plan->PlanExplainsStop())
232     {
233         bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
234         while (1)
235         {
236             should_stop = current_plan->ShouldStop(event_ptr);
237             if (current_plan->MischiefManaged())
238             {
239                 if (should_stop)
240                     current_plan->WillStop();
241 
242                 // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
243                 // Otherwise, see if the plan's parent wants to stop.
244 
245                 if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
246                 {
247                     PopPlan();
248                     break;
249                 }
250                 else
251                 {
252 
253                     PopPlan();
254 
255                     current_plan = GetCurrentPlan();
256                     if (current_plan == NULL)
257                     {
258                         break;
259                     }
260                 }
261 
262             }
263             else
264             {
265                 break;
266             }
267         }
268         if (over_ride_stop)
269             should_stop = false;
270     }
271     else
272     {
273         // If the current plan doesn't explain the stop, then, find one that
274         // does and let it handle the situation.
275         ThreadPlan *plan_ptr = current_plan;
276         while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
277         {
278             if (plan_ptr->PlanExplainsStop())
279             {
280                 should_stop = plan_ptr->ShouldStop (event_ptr);
281                 break;
282             }
283 
284         }
285     }
286 
287     return should_stop;
288 }
289 
290 Vote
291 Thread::ShouldReportStop (Event* event_ptr)
292 {
293     StateType thread_state = GetResumeState ();
294     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
295 
296     if (thread_state == eStateSuspended || thread_state == eStateInvalid)
297     {
298         if (log)
299             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote %i (state was suspended or invalid)\n", GetID(), eVoteNoOpinion);
300         return eVoteNoOpinion;
301     }
302 
303     if (m_completed_plan_stack.size() > 0)
304     {
305         // Don't use GetCompletedPlan here, since that suppresses private plans.
306         if (log)
307             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote  for complete stack's back plan\n", GetID());
308         return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
309     }
310     else
311     {
312         if (log)
313             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote  for current plan\n", GetID());
314         return GetCurrentPlan()->ShouldReportStop (event_ptr);
315     }
316 }
317 
318 Vote
319 Thread::ShouldReportRun (Event* event_ptr)
320 {
321     StateType thread_state = GetResumeState ();
322     if (thread_state == eStateSuspended
323             || thread_state == eStateInvalid)
324         return eVoteNoOpinion;
325 
326     if (m_completed_plan_stack.size() > 0)
327     {
328         // Don't use GetCompletedPlan here, since that suppresses private plans.
329         return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
330     }
331     else
332         return GetCurrentPlan()->ShouldReportRun (event_ptr);
333 }
334 
335 bool
336 Thread::MatchesSpec (const ThreadSpec *spec)
337 {
338     if (spec == NULL)
339         return true;
340 
341     return spec->ThreadPassesBasicTests(this);
342 }
343 
344 void
345 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
346 {
347     if (thread_plan_sp)
348     {
349         m_plan_stack.push_back (thread_plan_sp);
350 
351         thread_plan_sp->DidPush();
352 
353         Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
354         if (log)
355         {
356             StreamString s;
357             thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
358             log->Printf("Pushing plan: \"%s\", tid = 0x%4.4x.",
359                         s.GetData(),
360                         thread_plan_sp->GetThread().GetID());
361         }
362     }
363 }
364 
365 void
366 Thread::PopPlan ()
367 {
368     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
369 
370     if (m_plan_stack.empty())
371         return;
372     else
373     {
374         ThreadPlanSP &plan = m_plan_stack.back();
375         if (log)
376         {
377             log->Printf("Popping plan: \"%s\", tid = 0x%4.4x, immediate = false.", plan->GetName(), plan->GetThread().GetID());
378         }
379         m_completed_plan_stack.push_back (plan);
380         plan->WillPop();
381         m_plan_stack.pop_back();
382     }
383 }
384 
385 void
386 Thread::DiscardPlan ()
387 {
388     if (m_plan_stack.size() > 1)
389     {
390         ThreadPlanSP &plan = m_plan_stack.back();
391         m_discarded_plan_stack.push_back (plan);
392         plan->WillPop();
393         m_plan_stack.pop_back();
394     }
395 }
396 
397 ThreadPlan *
398 Thread::GetCurrentPlan ()
399 {
400     if (m_plan_stack.empty())
401         return NULL;
402     else
403         return m_plan_stack.back().get();
404 }
405 
406 ThreadPlanSP
407 Thread::GetCompletedPlan ()
408 {
409     ThreadPlanSP empty_plan_sp;
410     if (!m_completed_plan_stack.empty())
411     {
412         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
413         {
414             ThreadPlanSP completed_plan_sp;
415             completed_plan_sp = m_completed_plan_stack[i];
416             if (!completed_plan_sp->GetPrivate ())
417             return completed_plan_sp;
418         }
419     }
420     return empty_plan_sp;
421 }
422 
423 bool
424 Thread::IsThreadPlanDone (ThreadPlan *plan)
425 {
426     ThreadPlanSP empty_plan_sp;
427     if (!m_completed_plan_stack.empty())
428     {
429         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
430         {
431             if (m_completed_plan_stack[i].get() == plan)
432                 return true;
433         }
434     }
435     return false;
436 }
437 
438 bool
439 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
440 {
441     ThreadPlanSP empty_plan_sp;
442     if (!m_discarded_plan_stack.empty())
443     {
444         for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
445         {
446             if (m_discarded_plan_stack[i].get() == plan)
447                 return true;
448         }
449     }
450     return false;
451 }
452 
453 ThreadPlan *
454 Thread::GetPreviousPlan (ThreadPlan *current_plan)
455 {
456     if (current_plan == NULL)
457         return NULL;
458 
459     int stack_size = m_completed_plan_stack.size();
460     for (int i = stack_size - 1; i > 0; i--)
461     {
462         if (current_plan == m_completed_plan_stack[i].get())
463             return m_completed_plan_stack[i-1].get();
464     }
465 
466     if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
467     {
468         if (m_plan_stack.size() > 0)
469             return m_plan_stack.back().get();
470         else
471             return NULL;
472     }
473 
474     stack_size = m_plan_stack.size();
475     for (int i = stack_size - 1; i > 0; i--)
476     {
477         if (current_plan == m_plan_stack[i].get())
478             return m_plan_stack[i-1].get();
479     }
480     return NULL;
481 }
482 
483 void
484 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
485 {
486     if (abort_other_plans)
487        DiscardThreadPlans(true);
488 
489     PushPlan (thread_plan_sp);
490 }
491 
492 void
493 Thread::DiscardThreadPlans(bool force)
494 {
495     // FIXME: It is not always safe to just discard plans.  Some, like the step over
496     // breakpoint trap can't be discarded in general (though you can if you plan to
497     // force a return from a function, for instance.
498     // For now I'm just not clearing immediate plans, but I need a way for plans to
499     // say they really need to be kept on, and then a way to override that.  Humm...
500 
501     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
502     if (log)
503     {
504         log->Printf("Discarding thread plans for thread (tid = 0x%4.4x, force %d)", GetID(), force);
505     }
506 
507     if (force)
508     {
509         int stack_size = m_plan_stack.size();
510         for (int i = stack_size - 1; i > 0; i--)
511         {
512             DiscardPlan();
513         }
514         return;
515     }
516 
517     while (1)
518     {
519 
520         int master_plan_idx;
521         bool discard;
522 
523         // Find the first master plan, see if it wants discarding, and if yes discard up to it.
524         for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
525         {
526             if (m_plan_stack[master_plan_idx]->IsMasterPlan())
527             {
528                 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
529                 break;
530             }
531         }
532 
533         if (discard)
534         {
535             // First pop all the dependent plans:
536             for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
537             {
538 
539                 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
540                 // for the plan leaves it in a state that it is safe to pop the plan
541                 // with no more notice?
542                 DiscardPlan();
543             }
544 
545             // Now discard the master plan itself.
546             // The bottom-most plan never gets discarded.  "OkayToDiscard" for it means
547             // discard it's dependent plans, but not it...
548             if (master_plan_idx > 0)
549             {
550                 DiscardPlan();
551             }
552         }
553         else
554         {
555             // If the master plan doesn't want to get discarded, then we're done.
556             break;
557         }
558 
559     }
560     // FIXME: What should we do about the immediate plans?
561 }
562 
563 ThreadPlan *
564 Thread::QueueFundamentalPlan (bool abort_other_plans)
565 {
566     ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
567     QueueThreadPlan (thread_plan_sp, abort_other_plans);
568     return thread_plan_sp.get();
569 }
570 
571 ThreadPlan *
572 Thread::QueueThreadPlanForStepSingleInstruction (bool step_over, bool abort_other_plans, bool stop_other_threads)
573 {
574     ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
575     QueueThreadPlan (thread_plan_sp, abort_other_plans);
576     return thread_plan_sp.get();
577 }
578 
579 ThreadPlan *
580 Thread::QueueThreadPlanForStepRange
581 (
582     bool abort_other_plans,
583     StepType type,
584     const AddressRange &range,
585     const SymbolContext &addr_context,
586     lldb::RunMode stop_other_threads,
587     bool avoid_code_without_debug_info
588 )
589 {
590     ThreadPlanSP thread_plan_sp;
591     if (type == eStepTypeInto)
592     {
593         ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this, range, addr_context, stop_other_threads);
594         if (avoid_code_without_debug_info)
595             plan->GetFlags().Set (ThreadPlanShouldStopHere::eAvoidNoDebug);
596         else
597             plan->GetFlags().Clear (ThreadPlanShouldStopHere::eAvoidNoDebug);
598         thread_plan_sp.reset (plan);
599     }
600     else
601         thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads));
602 
603     QueueThreadPlan (thread_plan_sp, abort_other_plans);
604     return thread_plan_sp.get();
605 }
606 
607 
608 ThreadPlan *
609 Thread::QueueThreadPlanForStepOverBreakpointPlan (bool abort_other_plans)
610 {
611     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
612     QueueThreadPlan (thread_plan_sp, abort_other_plans);
613     return thread_plan_sp.get();
614 }
615 
616 ThreadPlan *
617 Thread::QueueThreadPlanForStepOut (bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
618         bool stop_other_threads, Vote stop_vote, Vote run_vote)
619 {
620     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote));
621     QueueThreadPlan (thread_plan_sp, abort_other_plans);
622     return thread_plan_sp.get();
623 }
624 
625 ThreadPlan *
626 Thread::QueueThreadPlanForStepThrough (bool abort_other_plans, bool stop_other_threads)
627 {
628     // Try the dynamic loader first:
629     ThreadPlanSP thread_plan_sp(GetProcess().GetDynamicLoader()->GetStepThroughTrampolinePlan (*this, stop_other_threads));
630     // If that didn't come up with anything, try the ObjC runtime plugin:
631     if (thread_plan_sp.get() == NULL)
632     {
633         ObjCLanguageRuntime *objc_runtime = GetProcess().GetObjCLanguageRuntime();
634         if (objc_runtime)
635             thread_plan_sp = objc_runtime->GetStepThroughTrampolinePlan (*this, stop_other_threads);
636     }
637 
638     if (thread_plan_sp.get() == NULL)
639     {
640         thread_plan_sp.reset(new ThreadPlanStepThrough (*this, stop_other_threads));
641         if (thread_plan_sp && !thread_plan_sp->ValidatePlan (NULL))
642             return NULL;
643     }
644     QueueThreadPlan (thread_plan_sp, abort_other_plans);
645     return thread_plan_sp.get();
646 }
647 
648 ThreadPlan *
649 Thread::QueueThreadPlanForCallFunction (bool abort_other_plans,
650                                         Address& function,
651                                         lldb::addr_t arg,
652                                         bool stop_other_threads,
653                                         bool discard_on_error)
654 {
655     ThreadPlanSP thread_plan_sp (new ThreadPlanCallFunction (*this, function, arg, stop_other_threads, discard_on_error));
656     QueueThreadPlan (thread_plan_sp, abort_other_plans);
657     return thread_plan_sp.get();
658 }
659 
660 ThreadPlan *
661 Thread::QueueThreadPlanForCallFunction (bool abort_other_plans,
662                                         Address& function,
663                                         ValueList &args,
664                                         bool stop_other_threads,
665                                         bool discard_on_error)
666 {
667     ThreadPlanSP thread_plan_sp (new ThreadPlanCallFunction (*this, function, args, stop_other_threads, discard_on_error));
668     QueueThreadPlan (thread_plan_sp, abort_other_plans);
669     return thread_plan_sp.get();
670 }
671 
672 ThreadPlan *
673 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
674                                         Address &target_addr,
675                                         bool stop_other_threads)
676 {
677     ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
678     QueueThreadPlan (thread_plan_sp, abort_other_plans);
679     return thread_plan_sp.get();
680 }
681 
682 ThreadPlan *
683 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
684                                        lldb::addr_t *address_list,
685                                        size_t num_addresses,
686                                        bool stop_other_threads)
687 {
688     ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads));
689     QueueThreadPlan (thread_plan_sp, abort_other_plans);
690     return thread_plan_sp.get();
691 
692 }
693 
694 uint32_t
695 Thread::GetIndexID () const
696 {
697     return m_index_id;
698 }
699 
700 void
701 Thread::DumpThreadPlans (lldb_private::Stream *s) const
702 {
703     uint32_t stack_size = m_plan_stack.size();
704     int i;
705     s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4x, stack_size = %d\n", GetIndexID(), GetID(), stack_size);
706     for (i = stack_size - 1; i >= 0; i--)
707     {
708         s->Printf ("Element %d: ", i);
709         s->IndentMore();
710         m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
711         s->IndentLess();
712         s->EOL();
713     }
714 
715     stack_size = m_completed_plan_stack.size();
716     s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
717     for (i = stack_size - 1; i >= 0; i--)
718     {
719         s->Printf ("Element %d: ", i);
720         s->IndentMore();
721         m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
722         s->IndentLess();
723         s->EOL();
724     }
725 
726     stack_size = m_discarded_plan_stack.size();
727     s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
728     for (int i = stack_size - 1; i >= 0; i--)
729     {
730         s->Printf ("Element %d: ", i);
731         s->IndentMore();
732         m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
733         s->IndentLess();
734         s->EOL();
735     }
736 
737 }
738 
739 Target *
740 Thread::CalculateTarget ()
741 {
742     return m_process.CalculateTarget();
743 }
744 
745 Process *
746 Thread::CalculateProcess ()
747 {
748     return &m_process;
749 }
750 
751 Thread *
752 Thread::CalculateThread ()
753 {
754     return this;
755 }
756 
757 StackFrame *
758 Thread::CalculateStackFrame ()
759 {
760     return NULL;
761 }
762 
763 void
764 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
765 {
766     m_process.CalculateExecutionContext (exe_ctx);
767     exe_ctx.thread = this;
768     exe_ctx.frame = NULL;
769 }
770 
771 
772 StackFrameList &
773 Thread::GetStackFrameList ()
774 {
775     if (m_curr_frames_ap.get() == NULL)
776         m_curr_frames_ap.reset (new StackFrameList (*this, m_prev_frames_sp, true));
777     return *m_curr_frames_ap;
778 }
779 
780 
781 
782 uint32_t
783 Thread::GetStackFrameCount()
784 {
785     return GetStackFrameList().GetNumFrames();
786 }
787 
788 
789 void
790 Thread::ClearStackFrames ()
791 {
792     if (m_curr_frames_ap.get() && m_curr_frames_ap->GetNumFrames (false) > 1)
793         m_prev_frames_sp.reset (m_curr_frames_ap.release());
794     else
795         m_curr_frames_ap.release();
796 
797 //    StackFrameList::Merge (m_curr_frames_ap, m_prev_frames_sp);
798 //    assert (m_curr_frames_ap.get() == NULL);
799 }
800 
801 lldb::StackFrameSP
802 Thread::GetStackFrameAtIndex (uint32_t idx)
803 {
804     return GetStackFrameList().GetFrameAtIndex(idx);
805 }
806 
807 uint32_t
808 Thread::GetSelectedFrameIndex ()
809 {
810     return GetStackFrameList().GetSelectedFrameIndex();
811 }
812 
813 
814 lldb::StackFrameSP
815 Thread::GetSelectedFrame ()
816 {
817     return GetStackFrameAtIndex (GetStackFrameList().GetSelectedFrameIndex());
818 }
819 
820 uint32_t
821 Thread::SetSelectedFrame (lldb_private::StackFrame *frame)
822 {
823     return GetStackFrameList().SetSelectedFrame(frame);
824 }
825 
826 void
827 Thread::SetSelectedFrameByIndex (uint32_t idx)
828 {
829     GetStackFrameList().SetSelectedFrameByIndex(idx);
830 }
831 
832 void
833 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
834 {
835     ExecutionContext exe_ctx;
836     SymbolContext frame_sc;
837     CalculateExecutionContext (exe_ctx);
838 
839     if (frame_idx != LLDB_INVALID_INDEX32)
840     {
841         StackFrameSP frame_sp(GetStackFrameAtIndex (frame_idx));
842         if (frame_sp)
843         {
844             exe_ctx.frame = frame_sp.get();
845             frame_sc = exe_ctx.frame->GetSymbolContext(eSymbolContextEverything);
846         }
847     }
848 
849     const char *thread_format = GetProcess().GetTarget().GetDebugger().GetThreadFormat();
850     assert (thread_format);
851     const char *end = NULL;
852     Debugger::FormatPrompt (thread_format,
853                             exe_ctx.frame ? &frame_sc : NULL,
854                             &exe_ctx,
855                             NULL,
856                             strm,
857                             &end);
858 }
859 
860 lldb::ThreadSP
861 Thread::GetSP ()
862 {
863     return m_process.GetThreadList().GetThreadSPForThreadPtr(this);
864 }
865 
866 lldb::UserSettingsControllerSP
867 Thread::GetSettingsController (bool finish)
868 {
869     static UserSettingsControllerSP g_settings_controller (new ThreadSettingsController);
870     static bool initialized = false;
871 
872     if (!initialized)
873     {
874         initialized = UserSettingsController::InitializeSettingsController (g_settings_controller,
875                                                              Thread::ThreadSettingsController::global_settings_table,
876                                                              Thread::ThreadSettingsController::instance_settings_table);
877     }
878 
879     if (finish)
880     {
881         UserSettingsController::FinalizeSettingsController (g_settings_controller);
882         g_settings_controller.reset();
883         initialized = false;
884     }
885 
886     return g_settings_controller;
887 }
888 
889 void
890 Thread::UpdateInstanceName ()
891 {
892     StreamString sstr;
893     const char *name = GetName();
894 
895     if (name && name[0] != '\0')
896         sstr.Printf ("%s", name);
897     else if ((GetIndexID() != 0) || (GetID() != 0))
898         sstr.Printf ("0x%4.4x", GetIndexID(), GetID());
899 
900     if (sstr.GetSize() > 0)
901 	Thread::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
902 }
903 
904 //--------------------------------------------------------------
905 // class Thread::ThreadSettingsController
906 //--------------------------------------------------------------
907 
908 Thread::ThreadSettingsController::ThreadSettingsController () :
909     UserSettingsController ("thread", Process::GetSettingsController())
910 {
911     m_default_settings.reset (new ThreadInstanceSettings (*this, false,
912                                                           InstanceSettings::GetDefaultName().AsCString()));
913 }
914 
915 Thread::ThreadSettingsController::~ThreadSettingsController ()
916 {
917 }
918 
919 lldb::InstanceSettingsSP
920 Thread::ThreadSettingsController::CreateInstanceSettings (const char *instance_name)
921 {
922     ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*(Thread::GetSettingsController().get()),
923                                                                        false, instance_name);
924     lldb::InstanceSettingsSP new_settings_sp (new_settings);
925     return new_settings_sp;
926 }
927 
928 //--------------------------------------------------------------
929 // class ThreadInstanceSettings
930 //--------------------------------------------------------------
931 
932 ThreadInstanceSettings::ThreadInstanceSettings (UserSettingsController &owner, bool live_instance, const char *name) :
933     InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance),
934     m_avoid_regexp_ap ()
935 {
936     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
937     // until the vtables for ThreadInstanceSettings are properly set up, i.e. AFTER all the initializers.
938     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
939     // This is true for CreateInstanceName() too.
940 
941     if (GetInstanceName() == InstanceSettings::InvalidName())
942     {
943         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
944         m_owner.RegisterInstanceSettings (this);
945     }
946 
947     if (live_instance)
948     {
949         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
950         CopyInstanceSettings (pending_settings,false);
951         //m_owner.RemovePendingSettings (m_instance_name);
952     }
953 }
954 
955 ThreadInstanceSettings::ThreadInstanceSettings (const ThreadInstanceSettings &rhs) :
956     InstanceSettings (*(Thread::GetSettingsController().get()), CreateInstanceName().AsCString()),
957     m_avoid_regexp_ap ()
958 {
959     if (m_instance_name != InstanceSettings::GetDefaultName())
960     {
961         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
962         CopyInstanceSettings (pending_settings,false);
963         m_owner.RemovePendingSettings (m_instance_name);
964     }
965     if (rhs.m_avoid_regexp_ap.get() != NULL)
966         m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
967 }
968 
969 ThreadInstanceSettings::~ThreadInstanceSettings ()
970 {
971 }
972 
973 ThreadInstanceSettings&
974 ThreadInstanceSettings::operator= (const ThreadInstanceSettings &rhs)
975 {
976     if (this != &rhs)
977     {
978         if (rhs.m_avoid_regexp_ap.get() != NULL)
979             m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
980         else
981             m_avoid_regexp_ap.reset(NULL);
982     }
983 
984     return *this;
985 }
986 
987 
988 void
989 ThreadInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
990                                                          const char *index_value,
991                                                          const char *value,
992                                                          const ConstString &instance_name,
993                                                          const SettingEntry &entry,
994                                                          lldb::VarSetOperationType op,
995                                                          Error &err,
996                                                          bool pending)
997 {
998     if (var_name == StepAvoidRegexpVarName())
999     {
1000         std::string regexp_text;
1001         if (m_avoid_regexp_ap.get() != NULL)
1002             regexp_text.append (m_avoid_regexp_ap->GetText());
1003         UserSettingsController::UpdateStringVariable (op, regexp_text, value, err);
1004         if (regexp_text.empty())
1005             m_avoid_regexp_ap.reset();
1006         else
1007         {
1008             m_avoid_regexp_ap.reset(new RegularExpression(regexp_text.c_str()));
1009 
1010         }
1011     }
1012 }
1013 
1014 void
1015 ThreadInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
1016                                                bool pending)
1017 {
1018     if (new_settings.get() == NULL)
1019         return;
1020 
1021     ThreadInstanceSettings *new_process_settings = (ThreadInstanceSettings *) new_settings.get();
1022     if (new_process_settings->GetSymbolsToAvoidRegexp() != NULL)
1023         m_avoid_regexp_ap.reset (new RegularExpression (new_process_settings->GetSymbolsToAvoidRegexp()->GetText()));
1024     else
1025         m_avoid_regexp_ap.reset ();
1026 }
1027 
1028 bool
1029 ThreadInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1030                                                   const ConstString &var_name,
1031                                                   StringList &value,
1032                                                   Error *err)
1033 {
1034     if (var_name == StepAvoidRegexpVarName())
1035     {
1036         if (m_avoid_regexp_ap.get() != NULL)
1037         {
1038             std::string regexp_text("\"");
1039             regexp_text.append(m_avoid_regexp_ap->GetText());
1040             regexp_text.append ("\"");
1041             value.AppendString (regexp_text.c_str());
1042         }
1043 
1044     }
1045     else
1046     {
1047         if (err)
1048             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1049         return false;
1050     }
1051     return true;
1052 }
1053 
1054 const ConstString
1055 ThreadInstanceSettings::CreateInstanceName ()
1056 {
1057     static int instance_count = 1;
1058     StreamString sstr;
1059 
1060     sstr.Printf ("thread_%d", instance_count);
1061     ++instance_count;
1062 
1063     const ConstString ret_val (sstr.GetData());
1064     return ret_val;
1065 }
1066 
1067 const ConstString &
1068 ThreadInstanceSettings::StepAvoidRegexpVarName ()
1069 {
1070     static ConstString run_args_var_name ("step-avoid-regexp");
1071 
1072     return run_args_var_name;
1073 }
1074 
1075 //--------------------------------------------------
1076 // ThreadSettingsController Variable Tables
1077 //--------------------------------------------------
1078 
1079 SettingEntry
1080 Thread::ThreadSettingsController::global_settings_table[] =
1081 {
1082   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
1083     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1084 };
1085 
1086 
1087 SettingEntry
1088 Thread::ThreadSettingsController::instance_settings_table[] =
1089 {
1090   //{ "var-name",    var-type,              "default",      enum-table, init'd, hidden, "help-text"},
1091     { "step-avoid-regexp",  eSetVarTypeString,      "",  NULL,       false,  false,  "A regular expression defining functions step-in won't stop in." },
1092     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1093 };
1094 
1095 lldb::StackFrameSP
1096 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1097 {
1098     return GetStackFrameList().GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1099 }
1100