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