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 #include "Plugins/Process/Utility/UnwindLLDB.h"
40 #include "UnwindMacOSXFrameBackchain.h"
41 
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 Thread::Thread (Process &process, lldb::tid_t tid) :
47     UserID (tid),
48     ThreadInstanceSettings (*GetSettingsController()),
49     m_process (process),
50     m_actual_stop_info_sp (),
51     m_index_id (process.GetNextThreadIndexID ()),
52     m_reg_context_sp (),
53     m_state (eStateUnloaded),
54     m_state_mutex (Mutex::eMutexTypeRecursive),
55     m_plan_stack (),
56     m_completed_plan_stack(),
57     m_curr_frames_sp (),
58     m_prev_frames_sp (),
59     m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER),
60     m_resume_state (eStateRunning),
61     m_unwinder_ap (),
62     m_destroy_called (false),
63     m_thread_stop_reason_stop_id (0)
64 
65 {
66     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
67     if (log)
68         log->Printf ("%p Thread::Thread(tid = 0x%4.4x)", this, GetID());
69 
70     QueueFundamentalPlan(true);
71     UpdateInstanceName();
72 }
73 
74 
75 Thread::~Thread()
76 {
77     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
78     if (log)
79         log->Printf ("%p Thread::~Thread(tid = 0x%4.4x)", this, GetID());
80     /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor.
81     assert (m_destroy_called);
82 }
83 
84 void
85 Thread::DestroyThread ()
86 {
87     m_plan_stack.clear();
88     m_discarded_plan_stack.clear();
89     m_completed_plan_stack.clear();
90     m_destroy_called = true;
91 }
92 
93 lldb::StopInfoSP
94 Thread::GetStopInfo ()
95 {
96     ThreadPlanSP plan_sp (GetCompletedPlan());
97     if (plan_sp)
98         return StopInfo::CreateStopReasonWithPlan (plan_sp);
99     else
100     {
101         if (m_actual_stop_info_sp
102             && m_actual_stop_info_sp->IsValid()
103             && m_thread_stop_reason_stop_id == m_process.GetStopID())
104             return m_actual_stop_info_sp;
105         else
106             return GetPrivateStopReason ();
107     }
108 }
109 
110 void
111 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp)
112 {
113     m_actual_stop_info_sp = stop_info_sp;
114     if (m_actual_stop_info_sp)
115         m_actual_stop_info_sp->MakeStopInfoValid();
116     m_thread_stop_reason_stop_id = GetProcess().GetStopID();
117 }
118 
119 void
120 Thread::SetStopInfoToNothing()
121 {
122     // Note, we can't just NULL out the private reason, or the native thread implementation will try to
123     // go calculate it again.  For now, just set it to a Unix Signal with an invalid signal number.
124     SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this,  LLDB_INVALID_SIGNAL_NUMBER));
125 }
126 
127 bool
128 Thread::ThreadStoppedForAReason (void)
129 {
130     return GetPrivateStopReason () != NULL;
131 }
132 
133 bool
134 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state)
135 {
136     if (!SaveFrameZeroState(saved_state.register_backup))
137         return false;
138 
139     saved_state.stop_info_sp = GetStopInfo();
140     saved_state.orig_stop_id = GetProcess().GetStopID();
141 
142     return true;
143 }
144 
145 bool
146 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state)
147 {
148     RestoreSaveFrameZero(saved_state.register_backup);
149     if (saved_state.stop_info_sp)
150         saved_state.stop_info_sp->MakeStopInfoValid();
151     SetStopInfo(saved_state.stop_info_sp);
152     return true;
153 }
154 
155 StateType
156 Thread::GetState() const
157 {
158     // If any other threads access this we will need a mutex for it
159     Mutex::Locker locker(m_state_mutex);
160     return m_state;
161 }
162 
163 void
164 Thread::SetState(StateType state)
165 {
166     Mutex::Locker locker(m_state_mutex);
167     m_state = state;
168 }
169 
170 void
171 Thread::WillStop()
172 {
173     ThreadPlan *current_plan = GetCurrentPlan();
174 
175     // FIXME: I may decide to disallow threads with no plans.  In which
176     // case this should go to an assert.
177 
178     if (!current_plan)
179         return;
180 
181     current_plan->WillStop();
182 }
183 
184 void
185 Thread::SetupForResume ()
186 {
187     if (GetResumeState() != eStateSuspended)
188     {
189 
190         // If we're at a breakpoint push the step-over breakpoint plan.  Do this before
191         // telling the current plan it will resume, since we might change what the current
192         // plan is.
193 
194         lldb::addr_t pc = GetRegisterContext()->GetPC();
195         BreakpointSiteSP bp_site_sp = GetProcess().GetBreakpointSiteList().FindByAddress(pc);
196         if (bp_site_sp && bp_site_sp->IsEnabled())
197         {
198             // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
199             // special to step over a breakpoint.
200 
201             ThreadPlan *cur_plan = GetCurrentPlan();
202 
203             if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
204             {
205                 ThreadPlanStepOverBreakpoint *step_bp_plan = new ThreadPlanStepOverBreakpoint (*this);
206                 if (step_bp_plan)
207                 {
208                     ThreadPlanSP step_bp_plan_sp;
209                     step_bp_plan->SetPrivate (true);
210 
211                     if (GetCurrentPlan()->RunState() != eStateStepping)
212                     {
213                         step_bp_plan->SetAutoContinue(true);
214                     }
215                     step_bp_plan_sp.reset (step_bp_plan);
216                     QueueThreadPlan (step_bp_plan_sp, false);
217                 }
218             }
219         }
220     }
221 }
222 
223 bool
224 Thread::WillResume (StateType resume_state)
225 {
226     // At this point clear the completed plan stack.
227     m_completed_plan_stack.clear();
228     m_discarded_plan_stack.clear();
229 
230     StopInfo *stop_info = GetPrivateStopReason().get();
231     if (stop_info)
232         stop_info->WillResume (resume_state);
233 
234     // Tell all the plans that we are about to resume in case they need to clear any state.
235     // We distinguish between the plan on the top of the stack and the lower
236     // plans in case a plan needs to do any special business before it runs.
237 
238     ThreadPlan *plan_ptr = GetCurrentPlan();
239     plan_ptr->WillResume(resume_state, true);
240 
241     while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
242     {
243         plan_ptr->WillResume (resume_state, false);
244     }
245 
246     m_actual_stop_info_sp.reset();
247     return true;
248 }
249 
250 void
251 Thread::DidResume ()
252 {
253     SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER);
254 }
255 
256 bool
257 Thread::ShouldStop (Event* event_ptr)
258 {
259     ThreadPlan *current_plan = GetCurrentPlan();
260     bool should_stop = true;
261 
262     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
263     if (log)
264     {
265         StreamString s;
266         DumpThreadPlans(&s);
267         log->PutCString (s.GetData());
268     }
269 
270     // The top most plan always gets to do the trace log...
271     current_plan->DoTraceLog ();
272 
273     if (current_plan->PlanExplainsStop())
274     {
275         bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
276 
277         // We're starting from the base plan, so just let it decide;
278         if (PlanIsBasePlan(current_plan))
279         {
280             should_stop = current_plan->ShouldStop (event_ptr);
281             if (log)
282                 log->Printf("Base plan says should stop: %i.", should_stop);
283         }
284         else
285         {
286             // Otherwise, don't let the base plan override what the other plans say to do, since
287             // presumably if there were other plans they would know what to do...
288             while (1)
289             {
290                 if (PlanIsBasePlan(current_plan))
291                     break;
292 
293                 should_stop = current_plan->ShouldStop(event_ptr);
294                 if (log)
295                     log->Printf("Plan %s should stop: %d.", current_plan->GetName(), should_stop);
296                 if (current_plan->MischiefManaged())
297                 {
298                     if (should_stop)
299                         current_plan->WillStop();
300 
301                     // If a Master Plan wants to stop, and wants to stick on the stack, we let it.
302                     // Otherwise, see if the plan's parent wants to stop.
303 
304                     if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard())
305                     {
306                         PopPlan();
307                         break;
308                     }
309                     else
310                     {
311 
312                         PopPlan();
313 
314                         current_plan = GetCurrentPlan();
315                         if (current_plan == NULL)
316                         {
317                             break;
318                         }
319                     }
320 
321                 }
322                 else
323                 {
324                     break;
325                 }
326             }
327         }
328         if (over_ride_stop)
329             should_stop = false;
330     }
331     else if (current_plan->TracerExplainsStop())
332     {
333         return false;
334     }
335     else
336     {
337         // If the current plan doesn't explain the stop, then, find one that
338         // does and let it handle the situation.
339         ThreadPlan *plan_ptr = current_plan;
340         while ((plan_ptr = GetPreviousPlan(plan_ptr)) != NULL)
341         {
342             if (plan_ptr->PlanExplainsStop())
343             {
344                 should_stop = plan_ptr->ShouldStop (event_ptr);
345                 break;
346             }
347 
348         }
349     }
350 
351     return should_stop;
352 }
353 
354 Vote
355 Thread::ShouldReportStop (Event* event_ptr)
356 {
357     StateType thread_state = GetResumeState ();
358     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
359 
360     if (thread_state == eStateSuspended || thread_state == eStateInvalid)
361     {
362         if (log)
363             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote %i (state was suspended or invalid)\n", GetID(), eVoteNoOpinion);
364         return eVoteNoOpinion;
365     }
366 
367     if (m_completed_plan_stack.size() > 0)
368     {
369         // Don't use GetCompletedPlan here, since that suppresses private plans.
370         if (log)
371             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote  for complete stack's back plan\n", GetID());
372         return m_completed_plan_stack.back()->ShouldReportStop (event_ptr);
373     }
374     else
375     {
376         if (log)
377             log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4x: returning vote  for current plan\n", GetID());
378         return GetCurrentPlan()->ShouldReportStop (event_ptr);
379     }
380 }
381 
382 Vote
383 Thread::ShouldReportRun (Event* event_ptr)
384 {
385     StateType thread_state = GetResumeState ();
386 
387     if (thread_state == eStateSuspended
388             || thread_state == eStateInvalid)
389     {
390         return eVoteNoOpinion;
391     }
392 
393     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
394     if (m_completed_plan_stack.size() > 0)
395     {
396         // Don't use GetCompletedPlan here, since that suppresses private plans.
397         if (log)
398             log->Printf ("Current Plan for thread %d (0x%4.4x): %s being asked whether we should report run.",
399                          GetIndexID(),
400                          GetID(),
401                          m_completed_plan_stack.back()->GetName());
402 
403         return m_completed_plan_stack.back()->ShouldReportRun (event_ptr);
404     }
405     else
406     {
407         if (log)
408             log->Printf ("Current Plan for thread %d (0x%4.4x): %s being asked whether we should report run.",
409                          GetIndexID(),
410                          GetID(),
411                          GetCurrentPlan()->GetName());
412 
413         return GetCurrentPlan()->ShouldReportRun (event_ptr);
414      }
415 }
416 
417 bool
418 Thread::MatchesSpec (const ThreadSpec *spec)
419 {
420     if (spec == NULL)
421         return true;
422 
423     return spec->ThreadPassesBasicTests(this);
424 }
425 
426 void
427 Thread::PushPlan (ThreadPlanSP &thread_plan_sp)
428 {
429     if (thread_plan_sp)
430     {
431         // If the thread plan doesn't already have a tracer, give it its parent's tracer:
432         if (!thread_plan_sp->GetThreadPlanTracer())
433             thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer());
434         m_plan_stack.push_back (thread_plan_sp);
435 
436         thread_plan_sp->DidPush();
437 
438         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
439         if (log)
440         {
441             StreamString s;
442             thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull);
443             log->Printf("Pushing plan: \"%s\", tid = 0x%4.4x.",
444                         s.GetData(),
445                         thread_plan_sp->GetThread().GetID());
446         }
447     }
448 }
449 
450 void
451 Thread::PopPlan ()
452 {
453     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
454 
455     if (m_plan_stack.empty())
456         return;
457     else
458     {
459         ThreadPlanSP &plan = m_plan_stack.back();
460         if (log)
461         {
462             log->Printf("Popping plan: \"%s\", tid = 0x%4.4x.", plan->GetName(), plan->GetThread().GetID());
463         }
464         m_completed_plan_stack.push_back (plan);
465         plan->WillPop();
466         m_plan_stack.pop_back();
467     }
468 }
469 
470 void
471 Thread::DiscardPlan ()
472 {
473     if (m_plan_stack.size() > 1)
474     {
475         ThreadPlanSP &plan = m_plan_stack.back();
476         m_discarded_plan_stack.push_back (plan);
477         plan->WillPop();
478         m_plan_stack.pop_back();
479     }
480 }
481 
482 ThreadPlan *
483 Thread::GetCurrentPlan ()
484 {
485     if (m_plan_stack.empty())
486         return NULL;
487     else
488         return m_plan_stack.back().get();
489 }
490 
491 ThreadPlanSP
492 Thread::GetCompletedPlan ()
493 {
494     ThreadPlanSP empty_plan_sp;
495     if (!m_completed_plan_stack.empty())
496     {
497         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
498         {
499             ThreadPlanSP completed_plan_sp;
500             completed_plan_sp = m_completed_plan_stack[i];
501             if (!completed_plan_sp->GetPrivate ())
502             return completed_plan_sp;
503         }
504     }
505     return empty_plan_sp;
506 }
507 
508 bool
509 Thread::IsThreadPlanDone (ThreadPlan *plan)
510 {
511     if (!m_completed_plan_stack.empty())
512     {
513         for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--)
514         {
515             if (m_completed_plan_stack[i].get() == plan)
516                 return true;
517         }
518     }
519     return false;
520 }
521 
522 bool
523 Thread::WasThreadPlanDiscarded (ThreadPlan *plan)
524 {
525     if (!m_discarded_plan_stack.empty())
526     {
527         for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--)
528         {
529             if (m_discarded_plan_stack[i].get() == plan)
530                 return true;
531         }
532     }
533     return false;
534 }
535 
536 ThreadPlan *
537 Thread::GetPreviousPlan (ThreadPlan *current_plan)
538 {
539     if (current_plan == NULL)
540         return NULL;
541 
542     int stack_size = m_completed_plan_stack.size();
543     for (int i = stack_size - 1; i > 0; i--)
544     {
545         if (current_plan == m_completed_plan_stack[i].get())
546             return m_completed_plan_stack[i-1].get();
547     }
548 
549     if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan)
550     {
551         if (m_plan_stack.size() > 0)
552             return m_plan_stack.back().get();
553         else
554             return NULL;
555     }
556 
557     stack_size = m_plan_stack.size();
558     for (int i = stack_size - 1; i > 0; i--)
559     {
560         if (current_plan == m_plan_stack[i].get())
561             return m_plan_stack[i-1].get();
562     }
563     return NULL;
564 }
565 
566 void
567 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans)
568 {
569     if (abort_other_plans)
570        DiscardThreadPlans(true);
571 
572     PushPlan (thread_plan_sp);
573 }
574 
575 
576 void
577 Thread::EnableTracer (bool value, bool single_stepping)
578 {
579     int stack_size = m_plan_stack.size();
580     for (int i = 0; i < stack_size; i++)
581     {
582         if (m_plan_stack[i]->GetThreadPlanTracer())
583         {
584             m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
585             m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
586         }
587     }
588 }
589 
590 void
591 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp)
592 {
593     int stack_size = m_plan_stack.size();
594     for (int i = 0; i < stack_size; i++)
595         m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
596 }
597 
598 void
599 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp)
600 {
601     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
602     if (log)
603     {
604         log->Printf("Discarding thread plans for thread tid = 0x%4.4x, up to %p", GetID(), up_to_plan_sp.get());
605     }
606 
607     int stack_size = m_plan_stack.size();
608 
609     // If the input plan is NULL, discard all plans.  Otherwise make sure this plan is in the
610     // stack, and if so discard up to and including it.
611 
612     if (up_to_plan_sp.get() == NULL)
613     {
614         for (int i = stack_size - 1; i > 0; i--)
615             DiscardPlan();
616     }
617     else
618     {
619         bool found_it = false;
620         for (int i = stack_size - 1; i > 0; i--)
621         {
622             if (m_plan_stack[i] == up_to_plan_sp)
623                 found_it = true;
624         }
625         if (found_it)
626         {
627             bool last_one = false;
628             for (int i = stack_size - 1; i > 0 && !last_one ; i--)
629             {
630                 if (GetCurrentPlan() == up_to_plan_sp.get())
631                     last_one = true;
632                 DiscardPlan();
633             }
634         }
635     }
636     return;
637 }
638 
639 void
640 Thread::DiscardThreadPlans(bool force)
641 {
642     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
643     if (log)
644     {
645         log->Printf("Discarding thread plans for thread (tid = 0x%4.4x, force %d)", GetID(), force);
646     }
647 
648     if (force)
649     {
650         int stack_size = m_plan_stack.size();
651         for (int i = stack_size - 1; i > 0; i--)
652         {
653             DiscardPlan();
654         }
655         return;
656     }
657 
658     while (1)
659     {
660 
661         int master_plan_idx;
662         bool discard;
663 
664         // Find the first master plan, see if it wants discarding, and if yes discard up to it.
665         for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--)
666         {
667             if (m_plan_stack[master_plan_idx]->IsMasterPlan())
668             {
669                 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
670                 break;
671             }
672         }
673 
674         if (discard)
675         {
676             // First pop all the dependent plans:
677             for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--)
678             {
679 
680                 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop"
681                 // for the plan leaves it in a state that it is safe to pop the plan
682                 // with no more notice?
683                 DiscardPlan();
684             }
685 
686             // Now discard the master plan itself.
687             // The bottom-most plan never gets discarded.  "OkayToDiscard" for it means
688             // discard it's dependent plans, but not it...
689             if (master_plan_idx > 0)
690             {
691                 DiscardPlan();
692             }
693         }
694         else
695         {
696             // If the master plan doesn't want to get discarded, then we're done.
697             break;
698         }
699 
700     }
701 }
702 
703 ThreadPlan *
704 Thread::QueueFundamentalPlan (bool abort_other_plans)
705 {
706     ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this));
707     QueueThreadPlan (thread_plan_sp, abort_other_plans);
708     return thread_plan_sp.get();
709 }
710 
711 ThreadPlan *
712 Thread::QueueThreadPlanForStepSingleInstruction
713 (
714     bool step_over,
715     bool abort_other_plans,
716     bool stop_other_threads
717 )
718 {
719     ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
720     QueueThreadPlan (thread_plan_sp, abort_other_plans);
721     return thread_plan_sp.get();
722 }
723 
724 ThreadPlan *
725 Thread::QueueThreadPlanForStepRange
726 (
727     bool abort_other_plans,
728     StepType type,
729     const AddressRange &range,
730     const SymbolContext &addr_context,
731     lldb::RunMode stop_other_threads,
732     bool avoid_code_without_debug_info
733 )
734 {
735     ThreadPlanSP thread_plan_sp;
736     if (type == eStepTypeInto)
737     {
738         ThreadPlanStepInRange *plan = new ThreadPlanStepInRange (*this, range, addr_context, stop_other_threads);
739         if (avoid_code_without_debug_info)
740             plan->GetFlags().Set (ThreadPlanShouldStopHere::eAvoidNoDebug);
741         else
742             plan->GetFlags().Clear (ThreadPlanShouldStopHere::eAvoidNoDebug);
743         thread_plan_sp.reset (plan);
744     }
745     else
746         thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads));
747 
748     QueueThreadPlan (thread_plan_sp, abort_other_plans);
749     return thread_plan_sp.get();
750 }
751 
752 
753 ThreadPlan *
754 Thread::QueueThreadPlanForStepOverBreakpointPlan (bool abort_other_plans)
755 {
756     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
757     QueueThreadPlan (thread_plan_sp, abort_other_plans);
758     return thread_plan_sp.get();
759 }
760 
761 ThreadPlan *
762 Thread::QueueThreadPlanForStepOut
763 (
764     bool abort_other_plans,
765     SymbolContext *addr_context,
766     bool first_insn,
767     bool stop_other_threads,
768     Vote stop_vote,
769     Vote run_vote,
770     uint32_t frame_idx
771 )
772 {
773     ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this,
774                                                         addr_context,
775                                                         first_insn,
776                                                         stop_other_threads,
777                                                         stop_vote,
778                                                         run_vote,
779                                                         frame_idx));
780     QueueThreadPlan (thread_plan_sp, abort_other_plans);
781     return thread_plan_sp.get();
782 }
783 
784 ThreadPlan *
785 Thread::QueueThreadPlanForStepThrough (bool abort_other_plans, bool stop_other_threads)
786 {
787     // Try the dynamic loader first:
788     ThreadPlanSP thread_plan_sp(GetProcess().GetDynamicLoader()->GetStepThroughTrampolinePlan (*this, stop_other_threads));
789     // If that didn't come up with anything, try the ObjC runtime plugin:
790     if (thread_plan_sp.get() == NULL)
791     {
792         ObjCLanguageRuntime *objc_runtime = GetProcess().GetObjCLanguageRuntime();
793         if (objc_runtime)
794             thread_plan_sp = objc_runtime->GetStepThroughTrampolinePlan (*this, stop_other_threads);
795     }
796 
797     if (thread_plan_sp.get() == NULL)
798     {
799         thread_plan_sp.reset(new ThreadPlanStepThrough (*this, stop_other_threads));
800         if (thread_plan_sp && !thread_plan_sp->ValidatePlan (NULL))
801             return NULL;
802     }
803     QueueThreadPlan (thread_plan_sp, abort_other_plans);
804     return thread_plan_sp.get();
805 }
806 
807 ThreadPlan *
808 Thread::QueueThreadPlanForCallFunction (bool abort_other_plans,
809                                         Address& function,
810                                         lldb::addr_t arg,
811                                         bool stop_other_threads,
812                                         bool discard_on_error)
813 {
814     ThreadPlanSP thread_plan_sp (new ThreadPlanCallFunction (*this, function, arg, stop_other_threads, discard_on_error));
815     QueueThreadPlan (thread_plan_sp, abort_other_plans);
816     return thread_plan_sp.get();
817 }
818 
819 ThreadPlan *
820 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans,
821                                         Address &target_addr,
822                                         bool stop_other_threads)
823 {
824     ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads));
825     QueueThreadPlan (thread_plan_sp, abort_other_plans);
826     return thread_plan_sp.get();
827 }
828 
829 ThreadPlan *
830 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans,
831                                      lldb::addr_t *address_list,
832                                      size_t num_addresses,
833                                      bool stop_other_threads,
834                                      uint32_t frame_idx)
835 {
836     ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx));
837     QueueThreadPlan (thread_plan_sp, abort_other_plans);
838     return thread_plan_sp.get();
839 
840 }
841 
842 uint32_t
843 Thread::GetIndexID () const
844 {
845     return m_index_id;
846 }
847 
848 void
849 Thread::DumpThreadPlans (lldb_private::Stream *s) const
850 {
851     uint32_t stack_size = m_plan_stack.size();
852     int i;
853     s->Printf ("Plan Stack for thread #%u: tid = 0x%4.4x, stack_size = %d\n", GetIndexID(), GetID(), stack_size);
854     for (i = stack_size - 1; i >= 0; i--)
855     {
856         s->Printf ("Element %d: ", i);
857         s->IndentMore();
858         m_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
859         s->IndentLess();
860         s->EOL();
861     }
862 
863     stack_size = m_completed_plan_stack.size();
864     s->Printf ("Completed Plan Stack: %d elements.\n", stack_size);
865     for (i = stack_size - 1; i >= 0; i--)
866     {
867         s->Printf ("Element %d: ", i);
868         s->IndentMore();
869         m_completed_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
870         s->IndentLess();
871         s->EOL();
872     }
873 
874     stack_size = m_discarded_plan_stack.size();
875     s->Printf ("Discarded Plan Stack: %d elements.\n", stack_size);
876     for (i = stack_size - 1; i >= 0; i--)
877     {
878         s->Printf ("Element %d: ", i);
879         s->IndentMore();
880         m_discarded_plan_stack[i]->GetDescription (s, eDescriptionLevelFull);
881         s->IndentLess();
882         s->EOL();
883     }
884 
885 }
886 
887 Target *
888 Thread::CalculateTarget ()
889 {
890     return m_process.CalculateTarget();
891 }
892 
893 Process *
894 Thread::CalculateProcess ()
895 {
896     return &m_process;
897 }
898 
899 Thread *
900 Thread::CalculateThread ()
901 {
902     return this;
903 }
904 
905 StackFrame *
906 Thread::CalculateStackFrame ()
907 {
908     return NULL;
909 }
910 
911 void
912 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx)
913 {
914     m_process.CalculateExecutionContext (exe_ctx);
915     exe_ctx.thread = this;
916     exe_ctx.frame = NULL;
917 }
918 
919 
920 StackFrameList &
921 Thread::GetStackFrameList ()
922 {
923     if (!m_curr_frames_sp)
924         m_curr_frames_sp.reset (new StackFrameList (*this, m_prev_frames_sp, true));
925     return *m_curr_frames_sp;
926 }
927 
928 void
929 Thread::ClearStackFrames ()
930 {
931     if (m_curr_frames_sp && m_curr_frames_sp->GetNumFrames (false) > 1)
932         m_prev_frames_sp.swap (m_curr_frames_sp);
933     m_curr_frames_sp.reset();
934 }
935 
936 lldb::StackFrameSP
937 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
938 {
939     return GetStackFrameList().GetFrameWithConcreteFrameIndex (unwind_idx);
940 }
941 
942 void
943 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
944 {
945     ExecutionContext exe_ctx;
946     SymbolContext frame_sc;
947     CalculateExecutionContext (exe_ctx);
948 
949     if (frame_idx != LLDB_INVALID_INDEX32)
950     {
951         StackFrameSP frame_sp(GetStackFrameAtIndex (frame_idx));
952         if (frame_sp)
953         {
954             exe_ctx.frame = frame_sp.get();
955             frame_sc = exe_ctx.frame->GetSymbolContext(eSymbolContextEverything);
956         }
957     }
958 
959     const char *thread_format = GetProcess().GetTarget().GetDebugger().GetThreadFormat();
960     assert (thread_format);
961     const char *end = NULL;
962     Debugger::FormatPrompt (thread_format,
963                             exe_ctx.frame ? &frame_sc : NULL,
964                             &exe_ctx,
965                             NULL,
966                             strm,
967                             &end);
968 }
969 
970 lldb::ThreadSP
971 Thread::GetSP ()
972 {
973     return m_process.GetThreadList().GetThreadSPForThreadPtr(this);
974 }
975 
976 
977 void
978 Thread::SettingsInitialize ()
979 {
980     UserSettingsControllerSP &usc = GetSettingsController();
981     usc.reset (new SettingsController);
982     UserSettingsController::InitializeSettingsController (usc,
983                                                           SettingsController::global_settings_table,
984                                                           SettingsController::instance_settings_table);
985 
986     // Now call SettingsInitialize() on each 'child' setting of Thread.
987     // Currently there are none.
988 }
989 
990 void
991 Thread::SettingsTerminate ()
992 {
993     // Must call SettingsTerminate() on each 'child' setting of Thread before terminating Thread settings.
994     // Currently there are none.
995 
996     // Now terminate Thread Settings.
997 
998     UserSettingsControllerSP &usc = GetSettingsController();
999     UserSettingsController::FinalizeSettingsController (usc);
1000     usc.reset();
1001 }
1002 
1003 UserSettingsControllerSP &
1004 Thread::GetSettingsController ()
1005 {
1006     static UserSettingsControllerSP g_settings_controller;
1007     return g_settings_controller;
1008 }
1009 
1010 void
1011 Thread::UpdateInstanceName ()
1012 {
1013     StreamString sstr;
1014     const char *name = GetName();
1015 
1016     if (name && name[0] != '\0')
1017         sstr.Printf ("%s", name);
1018     else if ((GetIndexID() != 0) || (GetID() != 0))
1019         sstr.Printf ("0x%4.4x", GetIndexID(), GetID());
1020 
1021     if (sstr.GetSize() > 0)
1022 	Thread::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1023 }
1024 
1025 lldb::StackFrameSP
1026 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1027 {
1028     return GetStackFrameList().GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1029 }
1030 
1031 const char *
1032 Thread::StopReasonAsCString (lldb::StopReason reason)
1033 {
1034     switch (reason)
1035     {
1036     case eStopReasonInvalid:      return "invalid";
1037     case eStopReasonNone:         return "none";
1038     case eStopReasonTrace:        return "trace";
1039     case eStopReasonBreakpoint:   return "breakpoint";
1040     case eStopReasonWatchpoint:   return "watchpoint";
1041     case eStopReasonSignal:       return "signal";
1042     case eStopReasonException:    return "exception";
1043     case eStopReasonPlanComplete: return "plan complete";
1044     }
1045 
1046 
1047     static char unknown_state_string[64];
1048     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
1049     return unknown_state_string;
1050 }
1051 
1052 const char *
1053 Thread::RunModeAsCString (lldb::RunMode mode)
1054 {
1055     switch (mode)
1056     {
1057     case eOnlyThisThread:     return "only this thread";
1058     case eAllThreads:         return "all threads";
1059     case eOnlyDuringStepping: return "only during stepping";
1060     }
1061 
1062     static char unknown_state_string[64];
1063     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
1064     return unknown_state_string;
1065 }
1066 
1067 size_t
1068 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
1069 {
1070     size_t num_frames_shown = 0;
1071     strm.Indent();
1072     strm.Printf("%c ", GetProcess().GetThreadList().GetSelectedThread().get() == this ? '*' : ' ');
1073     if (GetProcess().GetTarget().GetDebugger().GetUseExternalEditor())
1074     {
1075         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1076         if (frame_sp)
1077         {
1078             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
1079             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
1080             {
1081                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
1082             }
1083         }
1084     }
1085 
1086     DumpUsingSettingsFormat (strm, start_frame);
1087 
1088     if (num_frames > 0)
1089     {
1090         strm.IndentMore();
1091 
1092         const bool show_frame_info = true;
1093         const uint32_t source_lines_before = 3;
1094         const uint32_t source_lines_after = 3;
1095         strm.IndentMore ();
1096         num_frames_shown = GetStackFrameList ().GetStatus (strm,
1097                                                            start_frame,
1098                                                            num_frames,
1099                                                            show_frame_info,
1100                                                            num_frames_with_source,
1101                                                            source_lines_before,
1102                                                            source_lines_after);
1103         strm.IndentLess();
1104         strm.IndentLess();
1105     }
1106     return num_frames_shown;
1107 }
1108 
1109 size_t
1110 Thread::GetStackFrameStatus (Stream& strm,
1111                              uint32_t first_frame,
1112                              uint32_t num_frames,
1113                              bool show_frame_info,
1114                              uint32_t num_frames_with_source,
1115                              uint32_t source_lines_before,
1116                              uint32_t source_lines_after)
1117 {
1118     return GetStackFrameList().GetStatus (strm,
1119                                           first_frame,
1120                                           num_frames,
1121                                           show_frame_info,
1122                                           num_frames_with_source,
1123                                           source_lines_before,
1124                                           source_lines_after);
1125 }
1126 
1127 bool
1128 Thread::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
1129 {
1130     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1131     if (frame_sp)
1132     {
1133         checkpoint.SetStackID(frame_sp->GetStackID());
1134         return frame_sp->GetRegisterContext()->ReadAllRegisterValues (checkpoint.GetData());
1135     }
1136     return false;
1137 }
1138 
1139 bool
1140 Thread::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
1141 {
1142     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1143     if (frame_sp)
1144     {
1145         bool ret = frame_sp->GetRegisterContext()->WriteAllRegisterValues (checkpoint.GetData());
1146 
1147         // Clear out all stack frames as our world just changed.
1148         ClearStackFrames();
1149         frame_sp->GetRegisterContext()->InvalidateIfNeeded(true);
1150 
1151         return ret;
1152     }
1153     return false;
1154 }
1155 
1156 Unwind *
1157 Thread::GetUnwinder ()
1158 {
1159     if (m_unwinder_ap.get() == NULL)
1160     {
1161         const ArchSpec target_arch (GetProcess().GetTarget().GetArchitecture ());
1162         const llvm::Triple::ArchType machine = target_arch.GetMachine();
1163         switch (machine)
1164         {
1165             case llvm::Triple::x86_64:
1166             case llvm::Triple::x86:
1167             case llvm::Triple::arm:
1168             case llvm::Triple::thumb:
1169                 m_unwinder_ap.reset (new UnwindLLDB (*this));
1170                 break;
1171 
1172             default:
1173                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1174                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
1175                 break;
1176         }
1177     }
1178     return m_unwinder_ap.get();
1179 }
1180 
1181 
1182 #pragma mark "Thread::SettingsController"
1183 //--------------------------------------------------------------
1184 // class Thread::SettingsController
1185 //--------------------------------------------------------------
1186 
1187 Thread::SettingsController::SettingsController () :
1188     UserSettingsController ("thread", Process::GetSettingsController())
1189 {
1190     m_default_settings.reset (new ThreadInstanceSettings (*this, false,
1191                                                           InstanceSettings::GetDefaultName().AsCString()));
1192 }
1193 
1194 Thread::SettingsController::~SettingsController ()
1195 {
1196 }
1197 
1198 lldb::InstanceSettingsSP
1199 Thread::SettingsController::CreateInstanceSettings (const char *instance_name)
1200 {
1201     ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*GetSettingsController(),
1202                                                                        false,
1203                                                                        instance_name);
1204     lldb::InstanceSettingsSP new_settings_sp (new_settings);
1205     return new_settings_sp;
1206 }
1207 
1208 #pragma mark "ThreadInstanceSettings"
1209 //--------------------------------------------------------------
1210 // class ThreadInstanceSettings
1211 //--------------------------------------------------------------
1212 
1213 ThreadInstanceSettings::ThreadInstanceSettings (UserSettingsController &owner, bool live_instance, const char *name) :
1214     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1215     m_avoid_regexp_ap (),
1216     m_trace_enabled (false)
1217 {
1218     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1219     // until the vtables for ThreadInstanceSettings are properly set up, i.e. AFTER all the initializers.
1220     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1221     // This is true for CreateInstanceName() too.
1222 
1223     if (GetInstanceName() == InstanceSettings::InvalidName())
1224     {
1225         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1226         m_owner.RegisterInstanceSettings (this);
1227     }
1228 
1229     if (live_instance)
1230     {
1231         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1232         CopyInstanceSettings (pending_settings,false);
1233         //m_owner.RemovePendingSettings (m_instance_name);
1234     }
1235 }
1236 
1237 ThreadInstanceSettings::ThreadInstanceSettings (const ThreadInstanceSettings &rhs) :
1238     InstanceSettings (*Thread::GetSettingsController(), CreateInstanceName().AsCString()),
1239     m_avoid_regexp_ap (),
1240     m_trace_enabled (rhs.m_trace_enabled)
1241 {
1242     if (m_instance_name != InstanceSettings::GetDefaultName())
1243     {
1244         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1245         CopyInstanceSettings (pending_settings,false);
1246         m_owner.RemovePendingSettings (m_instance_name);
1247     }
1248     if (rhs.m_avoid_regexp_ap.get() != NULL)
1249         m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1250 }
1251 
1252 ThreadInstanceSettings::~ThreadInstanceSettings ()
1253 {
1254 }
1255 
1256 ThreadInstanceSettings&
1257 ThreadInstanceSettings::operator= (const ThreadInstanceSettings &rhs)
1258 {
1259     if (this != &rhs)
1260     {
1261         if (rhs.m_avoid_regexp_ap.get() != NULL)
1262             m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1263         else
1264             m_avoid_regexp_ap.reset(NULL);
1265     }
1266     m_trace_enabled = rhs.m_trace_enabled;
1267     return *this;
1268 }
1269 
1270 
1271 void
1272 ThreadInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1273                                                          const char *index_value,
1274                                                          const char *value,
1275                                                          const ConstString &instance_name,
1276                                                          const SettingEntry &entry,
1277                                                          VarSetOperationType op,
1278                                                          Error &err,
1279                                                          bool pending)
1280 {
1281     if (var_name == StepAvoidRegexpVarName())
1282     {
1283         std::string regexp_text;
1284         if (m_avoid_regexp_ap.get() != NULL)
1285             regexp_text.append (m_avoid_regexp_ap->GetText());
1286         UserSettingsController::UpdateStringVariable (op, regexp_text, value, err);
1287         if (regexp_text.empty())
1288             m_avoid_regexp_ap.reset();
1289         else
1290         {
1291             m_avoid_regexp_ap.reset(new RegularExpression(regexp_text.c_str()));
1292 
1293         }
1294     }
1295     else if (var_name == GetTraceThreadVarName())
1296     {
1297         bool success;
1298         bool result = Args::StringToBoolean(value, false, &success);
1299 
1300         if (success)
1301         {
1302             m_trace_enabled = result;
1303             if (!pending)
1304             {
1305                 Thread *myself = static_cast<Thread *> (this);
1306                 myself->EnableTracer(m_trace_enabled, true);
1307             }
1308         }
1309         else
1310         {
1311             err.SetErrorStringWithFormat ("Bad value \"%s\" for trace-thread, should be Boolean.", value);
1312         }
1313 
1314     }
1315 }
1316 
1317 void
1318 ThreadInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
1319                                                bool pending)
1320 {
1321     if (new_settings.get() == NULL)
1322         return;
1323 
1324     ThreadInstanceSettings *new_process_settings = (ThreadInstanceSettings *) new_settings.get();
1325     if (new_process_settings->GetSymbolsToAvoidRegexp() != NULL)
1326         m_avoid_regexp_ap.reset (new RegularExpression (new_process_settings->GetSymbolsToAvoidRegexp()->GetText()));
1327     else
1328         m_avoid_regexp_ap.reset ();
1329 }
1330 
1331 bool
1332 ThreadInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1333                                                   const ConstString &var_name,
1334                                                   StringList &value,
1335                                                   Error *err)
1336 {
1337     if (var_name == StepAvoidRegexpVarName())
1338     {
1339         if (m_avoid_regexp_ap.get() != NULL)
1340         {
1341             std::string regexp_text("\"");
1342             regexp_text.append(m_avoid_regexp_ap->GetText());
1343             regexp_text.append ("\"");
1344             value.AppendString (regexp_text.c_str());
1345         }
1346 
1347     }
1348     else if (var_name == GetTraceThreadVarName())
1349     {
1350         value.AppendString(m_trace_enabled ? "true" : "false");
1351     }
1352     else
1353     {
1354         if (err)
1355             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1356         return false;
1357     }
1358     return true;
1359 }
1360 
1361 const ConstString
1362 ThreadInstanceSettings::CreateInstanceName ()
1363 {
1364     static int instance_count = 1;
1365     StreamString sstr;
1366 
1367     sstr.Printf ("thread_%d", instance_count);
1368     ++instance_count;
1369 
1370     const ConstString ret_val (sstr.GetData());
1371     return ret_val;
1372 }
1373 
1374 const ConstString &
1375 ThreadInstanceSettings::StepAvoidRegexpVarName ()
1376 {
1377     static ConstString step_avoid_var_name ("step-avoid-regexp");
1378 
1379     return step_avoid_var_name;
1380 }
1381 
1382 const ConstString &
1383 ThreadInstanceSettings::GetTraceThreadVarName ()
1384 {
1385     static ConstString trace_thread_var_name ("trace-thread");
1386 
1387     return trace_thread_var_name;
1388 }
1389 
1390 //--------------------------------------------------
1391 // SettingsController Variable Tables
1392 //--------------------------------------------------
1393 
1394 SettingEntry
1395 Thread::SettingsController::global_settings_table[] =
1396 {
1397   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
1398     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1399 };
1400 
1401 
1402 SettingEntry
1403 Thread::SettingsController::instance_settings_table[] =
1404 {
1405   //{ "var-name",    var-type,              "default",      enum-table, init'd, hidden, "help-text"},
1406     { "step-avoid-regexp",  eSetVarTypeString,      "",  NULL,       false,  false,  "A regular expression defining functions step-in won't stop in." },
1407     { "trace-thread",  eSetVarTypeBoolean,      "false",  NULL,       false,  false,  "If true, this thread will single-step and log execution." },
1408     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1409 };
1410