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