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.SetThreadPtr (this);
916     exe_ctx.SetFramePtr (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     StackFrameSP frame_sp;
947     SymbolContext frame_sc;
948     CalculateExecutionContext (exe_ctx);
949 
950     if (frame_idx != LLDB_INVALID_INDEX32)
951     {
952         frame_sp = GetStackFrameAtIndex (frame_idx);
953         if (frame_sp)
954         {
955             exe_ctx.SetFrameSP(frame_sp);
956             frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
957         }
958     }
959 
960     const char *thread_format = GetProcess().GetTarget().GetDebugger().GetThreadFormat();
961     assert (thread_format);
962     const char *end = NULL;
963     Debugger::FormatPrompt (thread_format,
964                             frame_sp ? &frame_sc : NULL,
965                             &exe_ctx,
966                             NULL,
967                             strm,
968                             &end);
969 }
970 
971 lldb::ThreadSP
972 Thread::GetSP ()
973 {
974     // This object contains an instrusive ref count base class so we can
975     // easily make a shared pointer to this object
976     return ThreadSP(this);
977 }
978 
979 
980 void
981 Thread::SettingsInitialize ()
982 {
983     UserSettingsControllerSP &usc = GetSettingsController();
984     usc.reset (new SettingsController);
985     UserSettingsController::InitializeSettingsController (usc,
986                                                           SettingsController::global_settings_table,
987                                                           SettingsController::instance_settings_table);
988 
989     // Now call SettingsInitialize() on each 'child' setting of Thread.
990     // Currently there are none.
991 }
992 
993 void
994 Thread::SettingsTerminate ()
995 {
996     // Must call SettingsTerminate() on each 'child' setting of Thread before terminating Thread settings.
997     // Currently there are none.
998 
999     // Now terminate Thread Settings.
1000 
1001     UserSettingsControllerSP &usc = GetSettingsController();
1002     UserSettingsController::FinalizeSettingsController (usc);
1003     usc.reset();
1004 }
1005 
1006 UserSettingsControllerSP &
1007 Thread::GetSettingsController ()
1008 {
1009     static UserSettingsControllerSP g_settings_controller;
1010     return g_settings_controller;
1011 }
1012 
1013 void
1014 Thread::UpdateInstanceName ()
1015 {
1016     StreamString sstr;
1017     const char *name = GetName();
1018 
1019     if (name && name[0] != '\0')
1020         sstr.Printf ("%s", name);
1021     else if ((GetIndexID() != 0) || (GetID() != 0))
1022         sstr.Printf ("0x%4.4x", GetIndexID());
1023 
1024     if (sstr.GetSize() > 0)
1025 	Thread::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1026 }
1027 
1028 lldb::StackFrameSP
1029 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1030 {
1031     return GetStackFrameList().GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1032 }
1033 
1034 const char *
1035 Thread::StopReasonAsCString (lldb::StopReason reason)
1036 {
1037     switch (reason)
1038     {
1039     case eStopReasonInvalid:      return "invalid";
1040     case eStopReasonNone:         return "none";
1041     case eStopReasonTrace:        return "trace";
1042     case eStopReasonBreakpoint:   return "breakpoint";
1043     case eStopReasonWatchpoint:   return "watchpoint";
1044     case eStopReasonSignal:       return "signal";
1045     case eStopReasonException:    return "exception";
1046     case eStopReasonPlanComplete: return "plan complete";
1047     }
1048 
1049 
1050     static char unknown_state_string[64];
1051     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
1052     return unknown_state_string;
1053 }
1054 
1055 const char *
1056 Thread::RunModeAsCString (lldb::RunMode mode)
1057 {
1058     switch (mode)
1059     {
1060     case eOnlyThisThread:     return "only this thread";
1061     case eAllThreads:         return "all threads";
1062     case eOnlyDuringStepping: return "only during stepping";
1063     }
1064 
1065     static char unknown_state_string[64];
1066     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
1067     return unknown_state_string;
1068 }
1069 
1070 size_t
1071 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
1072 {
1073     size_t num_frames_shown = 0;
1074     strm.Indent();
1075     strm.Printf("%c ", GetProcess().GetThreadList().GetSelectedThread().get() == this ? '*' : ' ');
1076     if (GetProcess().GetTarget().GetDebugger().GetUseExternalEditor())
1077     {
1078         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1079         if (frame_sp)
1080         {
1081             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
1082             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
1083             {
1084                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
1085             }
1086         }
1087     }
1088 
1089     DumpUsingSettingsFormat (strm, start_frame);
1090 
1091     if (num_frames > 0)
1092     {
1093         strm.IndentMore();
1094 
1095         const bool show_frame_info = true;
1096         const uint32_t source_lines_before = 3;
1097         const uint32_t source_lines_after = 3;
1098         strm.IndentMore ();
1099         num_frames_shown = GetStackFrameList ().GetStatus (strm,
1100                                                            start_frame,
1101                                                            num_frames,
1102                                                            show_frame_info,
1103                                                            num_frames_with_source,
1104                                                            source_lines_before,
1105                                                            source_lines_after);
1106         strm.IndentLess();
1107         strm.IndentLess();
1108     }
1109     return num_frames_shown;
1110 }
1111 
1112 size_t
1113 Thread::GetStackFrameStatus (Stream& strm,
1114                              uint32_t first_frame,
1115                              uint32_t num_frames,
1116                              bool show_frame_info,
1117                              uint32_t num_frames_with_source,
1118                              uint32_t source_lines_before,
1119                              uint32_t source_lines_after)
1120 {
1121     return GetStackFrameList().GetStatus (strm,
1122                                           first_frame,
1123                                           num_frames,
1124                                           show_frame_info,
1125                                           num_frames_with_source,
1126                                           source_lines_before,
1127                                           source_lines_after);
1128 }
1129 
1130 bool
1131 Thread::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
1132 {
1133     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1134     if (frame_sp)
1135     {
1136         checkpoint.SetStackID(frame_sp->GetStackID());
1137         return frame_sp->GetRegisterContext()->ReadAllRegisterValues (checkpoint.GetData());
1138     }
1139     return false;
1140 }
1141 
1142 bool
1143 Thread::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
1144 {
1145     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1146     if (frame_sp)
1147     {
1148         bool ret = frame_sp->GetRegisterContext()->WriteAllRegisterValues (checkpoint.GetData());
1149 
1150         // Clear out all stack frames as our world just changed.
1151         ClearStackFrames();
1152         frame_sp->GetRegisterContext()->InvalidateIfNeeded(true);
1153 
1154         return ret;
1155     }
1156     return false;
1157 }
1158 
1159 Unwind *
1160 Thread::GetUnwinder ()
1161 {
1162     if (m_unwinder_ap.get() == NULL)
1163     {
1164         const ArchSpec target_arch (GetProcess().GetTarget().GetArchitecture ());
1165         const llvm::Triple::ArchType machine = target_arch.GetMachine();
1166         switch (machine)
1167         {
1168             case llvm::Triple::x86_64:
1169             case llvm::Triple::x86:
1170             case llvm::Triple::arm:
1171             case llvm::Triple::thumb:
1172                 m_unwinder_ap.reset (new UnwindLLDB (*this));
1173                 break;
1174 
1175             default:
1176                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1177                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
1178                 break;
1179         }
1180     }
1181     return m_unwinder_ap.get();
1182 }
1183 
1184 
1185 #pragma mark "Thread::SettingsController"
1186 //--------------------------------------------------------------
1187 // class Thread::SettingsController
1188 //--------------------------------------------------------------
1189 
1190 Thread::SettingsController::SettingsController () :
1191     UserSettingsController ("thread", Process::GetSettingsController())
1192 {
1193     m_default_settings.reset (new ThreadInstanceSettings (*this, false,
1194                                                           InstanceSettings::GetDefaultName().AsCString()));
1195 }
1196 
1197 Thread::SettingsController::~SettingsController ()
1198 {
1199 }
1200 
1201 lldb::InstanceSettingsSP
1202 Thread::SettingsController::CreateInstanceSettings (const char *instance_name)
1203 {
1204     ThreadInstanceSettings *new_settings = new ThreadInstanceSettings (*GetSettingsController(),
1205                                                                        false,
1206                                                                        instance_name);
1207     lldb::InstanceSettingsSP new_settings_sp (new_settings);
1208     return new_settings_sp;
1209 }
1210 
1211 #pragma mark "ThreadInstanceSettings"
1212 //--------------------------------------------------------------
1213 // class ThreadInstanceSettings
1214 //--------------------------------------------------------------
1215 
1216 ThreadInstanceSettings::ThreadInstanceSettings (UserSettingsController &owner, bool live_instance, const char *name) :
1217     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1218     m_avoid_regexp_ap (),
1219     m_trace_enabled (false)
1220 {
1221     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1222     // until the vtables for ThreadInstanceSettings are properly set up, i.e. AFTER all the initializers.
1223     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1224     // This is true for CreateInstanceName() too.
1225 
1226     if (GetInstanceName() == InstanceSettings::InvalidName())
1227     {
1228         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1229         m_owner.RegisterInstanceSettings (this);
1230     }
1231 
1232     if (live_instance)
1233     {
1234         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1235         CopyInstanceSettings (pending_settings,false);
1236         //m_owner.RemovePendingSettings (m_instance_name);
1237     }
1238 }
1239 
1240 ThreadInstanceSettings::ThreadInstanceSettings (const ThreadInstanceSettings &rhs) :
1241     InstanceSettings (*Thread::GetSettingsController(), CreateInstanceName().AsCString()),
1242     m_avoid_regexp_ap (),
1243     m_trace_enabled (rhs.m_trace_enabled)
1244 {
1245     if (m_instance_name != InstanceSettings::GetDefaultName())
1246     {
1247         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1248         CopyInstanceSettings (pending_settings,false);
1249         m_owner.RemovePendingSettings (m_instance_name);
1250     }
1251     if (rhs.m_avoid_regexp_ap.get() != NULL)
1252         m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1253 }
1254 
1255 ThreadInstanceSettings::~ThreadInstanceSettings ()
1256 {
1257 }
1258 
1259 ThreadInstanceSettings&
1260 ThreadInstanceSettings::operator= (const ThreadInstanceSettings &rhs)
1261 {
1262     if (this != &rhs)
1263     {
1264         if (rhs.m_avoid_regexp_ap.get() != NULL)
1265             m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1266         else
1267             m_avoid_regexp_ap.reset(NULL);
1268     }
1269     m_trace_enabled = rhs.m_trace_enabled;
1270     return *this;
1271 }
1272 
1273 
1274 void
1275 ThreadInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1276                                                          const char *index_value,
1277                                                          const char *value,
1278                                                          const ConstString &instance_name,
1279                                                          const SettingEntry &entry,
1280                                                          VarSetOperationType op,
1281                                                          Error &err,
1282                                                          bool pending)
1283 {
1284     if (var_name == StepAvoidRegexpVarName())
1285     {
1286         std::string regexp_text;
1287         if (m_avoid_regexp_ap.get() != NULL)
1288             regexp_text.append (m_avoid_regexp_ap->GetText());
1289         UserSettingsController::UpdateStringVariable (op, regexp_text, value, err);
1290         if (regexp_text.empty())
1291             m_avoid_regexp_ap.reset();
1292         else
1293         {
1294             m_avoid_regexp_ap.reset(new RegularExpression(regexp_text.c_str()));
1295 
1296         }
1297     }
1298     else if (var_name == GetTraceThreadVarName())
1299     {
1300         bool success;
1301         bool result = Args::StringToBoolean(value, false, &success);
1302 
1303         if (success)
1304         {
1305             m_trace_enabled = result;
1306             if (!pending)
1307             {
1308                 Thread *myself = static_cast<Thread *> (this);
1309                 myself->EnableTracer(m_trace_enabled, true);
1310             }
1311         }
1312         else
1313         {
1314             err.SetErrorStringWithFormat ("Bad value \"%s\" for trace-thread, should be Boolean.", value);
1315         }
1316 
1317     }
1318 }
1319 
1320 void
1321 ThreadInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
1322                                                bool pending)
1323 {
1324     if (new_settings.get() == NULL)
1325         return;
1326 
1327     ThreadInstanceSettings *new_process_settings = (ThreadInstanceSettings *) new_settings.get();
1328     if (new_process_settings->GetSymbolsToAvoidRegexp() != NULL)
1329         m_avoid_regexp_ap.reset (new RegularExpression (new_process_settings->GetSymbolsToAvoidRegexp()->GetText()));
1330     else
1331         m_avoid_regexp_ap.reset ();
1332 }
1333 
1334 bool
1335 ThreadInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1336                                                   const ConstString &var_name,
1337                                                   StringList &value,
1338                                                   Error *err)
1339 {
1340     if (var_name == StepAvoidRegexpVarName())
1341     {
1342         if (m_avoid_regexp_ap.get() != NULL)
1343         {
1344             std::string regexp_text("\"");
1345             regexp_text.append(m_avoid_regexp_ap->GetText());
1346             regexp_text.append ("\"");
1347             value.AppendString (regexp_text.c_str());
1348         }
1349 
1350     }
1351     else if (var_name == GetTraceThreadVarName())
1352     {
1353         value.AppendString(m_trace_enabled ? "true" : "false");
1354     }
1355     else
1356     {
1357         if (err)
1358             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1359         return false;
1360     }
1361     return true;
1362 }
1363 
1364 const ConstString
1365 ThreadInstanceSettings::CreateInstanceName ()
1366 {
1367     static int instance_count = 1;
1368     StreamString sstr;
1369 
1370     sstr.Printf ("thread_%d", instance_count);
1371     ++instance_count;
1372 
1373     const ConstString ret_val (sstr.GetData());
1374     return ret_val;
1375 }
1376 
1377 const ConstString &
1378 ThreadInstanceSettings::StepAvoidRegexpVarName ()
1379 {
1380     static ConstString step_avoid_var_name ("step-avoid-regexp");
1381 
1382     return step_avoid_var_name;
1383 }
1384 
1385 const ConstString &
1386 ThreadInstanceSettings::GetTraceThreadVarName ()
1387 {
1388     static ConstString trace_thread_var_name ("trace-thread");
1389 
1390     return trace_thread_var_name;
1391 }
1392 
1393 //--------------------------------------------------
1394 // SettingsController Variable Tables
1395 //--------------------------------------------------
1396 
1397 SettingEntry
1398 Thread::SettingsController::global_settings_table[] =
1399 {
1400   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
1401     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1402 };
1403 
1404 
1405 SettingEntry
1406 Thread::SettingsController::instance_settings_table[] =
1407 {
1408   //{ "var-name",    var-type,              "default",      enum-table, init'd, hidden, "help-text"},
1409     { "step-avoid-regexp",  eSetVarTypeString,      "",  NULL,       false,  false,  "A regular expression defining functions step-in won't stop in." },
1410     { "trace-thread",  eSetVarTypeBoolean,      "false",  NULL,       false,  false,  "If true, this thread will single-step and log execution." },
1411     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1412 };
1413