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     if (m_curr_frames_sp && m_curr_frames_sp->GetNumFrames (false) > 1)
1073         m_prev_frames_sp.swap (m_curr_frames_sp);
1074     m_curr_frames_sp.reset();
1075 }
1076 
1077 lldb::StackFrameSP
1078 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx)
1079 {
1080     return GetStackFrameList().GetFrameWithConcreteFrameIndex (unwind_idx);
1081 }
1082 
1083 void
1084 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx)
1085 {
1086     ExecutionContext exe_ctx (shared_from_this());
1087     Process *process = exe_ctx.GetProcessPtr();
1088     if (process == NULL)
1089         return;
1090 
1091     StackFrameSP frame_sp;
1092     SymbolContext frame_sc;
1093     if (frame_idx != LLDB_INVALID_INDEX32)
1094     {
1095         frame_sp = GetStackFrameAtIndex (frame_idx);
1096         if (frame_sp)
1097         {
1098             exe_ctx.SetFrameSP(frame_sp);
1099             frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1100         }
1101     }
1102 
1103     const char *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1104     assert (thread_format);
1105     const char *end = NULL;
1106     Debugger::FormatPrompt (thread_format,
1107                             frame_sp ? &frame_sc : NULL,
1108                             &exe_ctx,
1109                             NULL,
1110                             strm,
1111                             &end);
1112 }
1113 
1114 void
1115 Thread::SettingsInitialize ()
1116 {
1117     UserSettingsController::InitializeSettingsController (GetSettingsController(),
1118                                                           SettingsController::global_settings_table,
1119                                                           SettingsController::instance_settings_table);
1120 
1121     // Now call SettingsInitialize() on each 'child' setting of Thread.
1122     // Currently there are none.
1123 }
1124 
1125 void
1126 Thread::SettingsTerminate ()
1127 {
1128     // Must call SettingsTerminate() on each 'child' setting of Thread before terminating Thread settings.
1129     // Currently there are none.
1130 
1131     // Now terminate Thread Settings.
1132 
1133     UserSettingsControllerSP &usc = GetSettingsController();
1134     UserSettingsController::FinalizeSettingsController (usc);
1135     usc.reset();
1136 }
1137 
1138 UserSettingsControllerSP &
1139 Thread::GetSettingsController ()
1140 {
1141     static UserSettingsControllerSP g_settings_controller_sp;
1142     if (!g_settings_controller_sp)
1143     {
1144         g_settings_controller_sp.reset (new Thread::SettingsController);
1145         // The first shared pointer to Target::SettingsController in
1146         // g_settings_controller_sp must be fully created above so that
1147         // the TargetInstanceSettings can use a weak_ptr to refer back
1148         // to the master setttings controller
1149         InstanceSettingsSP default_instance_settings_sp (new ThreadInstanceSettings (g_settings_controller_sp,
1150                                                                                      false,
1151                                                                                      InstanceSettings::GetDefaultName().AsCString()));
1152 
1153         g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
1154     }
1155     return g_settings_controller_sp;
1156 }
1157 
1158 void
1159 Thread::UpdateInstanceName ()
1160 {
1161     StreamString sstr;
1162     const char *name = GetName();
1163 
1164     if (name && name[0] != '\0')
1165         sstr.Printf ("%s", name);
1166     else if ((GetIndexID() != 0) || (GetID() != 0))
1167         sstr.Printf ("0x%4.4x", GetIndexID());
1168 
1169     if (sstr.GetSize() > 0)
1170 	Thread::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1171 }
1172 
1173 lldb::StackFrameSP
1174 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
1175 {
1176     return GetStackFrameList().GetStackFrameSPForStackFramePtr (stack_frame_ptr);
1177 }
1178 
1179 const char *
1180 Thread::StopReasonAsCString (lldb::StopReason reason)
1181 {
1182     switch (reason)
1183     {
1184     case eStopReasonInvalid:      return "invalid";
1185     case eStopReasonNone:         return "none";
1186     case eStopReasonTrace:        return "trace";
1187     case eStopReasonBreakpoint:   return "breakpoint";
1188     case eStopReasonWatchpoint:   return "watchpoint";
1189     case eStopReasonSignal:       return "signal";
1190     case eStopReasonException:    return "exception";
1191     case eStopReasonPlanComplete: return "plan complete";
1192     }
1193 
1194 
1195     static char unknown_state_string[64];
1196     snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason);
1197     return unknown_state_string;
1198 }
1199 
1200 const char *
1201 Thread::RunModeAsCString (lldb::RunMode mode)
1202 {
1203     switch (mode)
1204     {
1205     case eOnlyThisThread:     return "only this thread";
1206     case eAllThreads:         return "all threads";
1207     case eOnlyDuringStepping: return "only during stepping";
1208     }
1209 
1210     static char unknown_state_string[64];
1211     snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode);
1212     return unknown_state_string;
1213 }
1214 
1215 size_t
1216 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source)
1217 {
1218     ExecutionContext exe_ctx (shared_from_this());
1219     Target *target = exe_ctx.GetTargetPtr();
1220     Process *process = exe_ctx.GetProcessPtr();
1221     size_t num_frames_shown = 0;
1222     strm.Indent();
1223     bool is_selected = false;
1224     if (process)
1225     {
1226         if (process->GetThreadList().GetSelectedThread().get() == this)
1227             is_selected = true;
1228     }
1229     strm.Printf("%c ", is_selected ? '*' : ' ');
1230     if (target && target->GetDebugger().GetUseExternalEditor())
1231     {
1232         StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1233         if (frame_sp)
1234         {
1235             SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry));
1236             if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file)
1237             {
1238                 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
1239             }
1240         }
1241     }
1242 
1243     DumpUsingSettingsFormat (strm, start_frame);
1244 
1245     if (num_frames > 0)
1246     {
1247         strm.IndentMore();
1248 
1249         const bool show_frame_info = true;
1250         const uint32_t source_lines_before = 3;
1251         const uint32_t source_lines_after = 3;
1252         strm.IndentMore ();
1253         num_frames_shown = GetStackFrameList ().GetStatus (strm,
1254                                                            start_frame,
1255                                                            num_frames,
1256                                                            show_frame_info,
1257                                                            num_frames_with_source,
1258                                                            source_lines_before,
1259                                                            source_lines_after);
1260         strm.IndentLess();
1261         strm.IndentLess();
1262     }
1263     return num_frames_shown;
1264 }
1265 
1266 size_t
1267 Thread::GetStackFrameStatus (Stream& strm,
1268                              uint32_t first_frame,
1269                              uint32_t num_frames,
1270                              bool show_frame_info,
1271                              uint32_t num_frames_with_source,
1272                              uint32_t source_lines_before,
1273                              uint32_t source_lines_after)
1274 {
1275     return GetStackFrameList().GetStatus (strm,
1276                                           first_frame,
1277                                           num_frames,
1278                                           show_frame_info,
1279                                           num_frames_with_source,
1280                                           source_lines_before,
1281                                           source_lines_after);
1282 }
1283 
1284 bool
1285 Thread::SaveFrameZeroState (RegisterCheckpoint &checkpoint)
1286 {
1287     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1288     if (frame_sp)
1289     {
1290         checkpoint.SetStackID(frame_sp->GetStackID());
1291         return frame_sp->GetRegisterContext()->ReadAllRegisterValues (checkpoint.GetData());
1292     }
1293     return false;
1294 }
1295 
1296 bool
1297 Thread::RestoreSaveFrameZero (const RegisterCheckpoint &checkpoint)
1298 {
1299     lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0));
1300     if (frame_sp)
1301     {
1302         bool ret = frame_sp->GetRegisterContext()->WriteAllRegisterValues (checkpoint.GetData());
1303 
1304         // Clear out all stack frames as our world just changed.
1305         ClearStackFrames();
1306         frame_sp->GetRegisterContext()->InvalidateIfNeeded(true);
1307 
1308         return ret;
1309     }
1310     return false;
1311 }
1312 
1313 Unwind *
1314 Thread::GetUnwinder ()
1315 {
1316     if (m_unwinder_ap.get() == NULL)
1317     {
1318         const ArchSpec target_arch (CalculateTarget()->GetArchitecture ());
1319         const llvm::Triple::ArchType machine = target_arch.GetMachine();
1320         switch (machine)
1321         {
1322             case llvm::Triple::x86_64:
1323             case llvm::Triple::x86:
1324             case llvm::Triple::arm:
1325             case llvm::Triple::thumb:
1326                 m_unwinder_ap.reset (new UnwindLLDB (*this));
1327                 break;
1328 
1329             default:
1330                 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1331                     m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this));
1332                 break;
1333         }
1334     }
1335     return m_unwinder_ap.get();
1336 }
1337 
1338 
1339 #pragma mark "Thread::SettingsController"
1340 //--------------------------------------------------------------
1341 // class Thread::SettingsController
1342 //--------------------------------------------------------------
1343 
1344 Thread::SettingsController::SettingsController () :
1345     UserSettingsController ("thread", Process::GetSettingsController())
1346 {
1347 }
1348 
1349 Thread::SettingsController::~SettingsController ()
1350 {
1351 }
1352 
1353 lldb::InstanceSettingsSP
1354 Thread::SettingsController::CreateInstanceSettings (const char *instance_name)
1355 {
1356     lldb::InstanceSettingsSP new_settings_sp (new ThreadInstanceSettings (GetSettingsController(),
1357                                                                           false,
1358                                                                           instance_name));
1359     return new_settings_sp;
1360 }
1361 
1362 #pragma mark "ThreadInstanceSettings"
1363 //--------------------------------------------------------------
1364 // class ThreadInstanceSettings
1365 //--------------------------------------------------------------
1366 
1367 ThreadInstanceSettings::ThreadInstanceSettings (const UserSettingsControllerSP &owner_sp, bool live_instance, const char *name) :
1368     InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1369     m_avoid_regexp_ap (),
1370     m_trace_enabled (false)
1371 {
1372     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1373     // until the vtables for ThreadInstanceSettings are properly set up, i.e. AFTER all the initializers.
1374     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1375     // This is true for CreateInstanceName() too.
1376 
1377     if (GetInstanceName() == InstanceSettings::InvalidName())
1378     {
1379         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1380         owner_sp->RegisterInstanceSettings (this);
1381     }
1382 
1383     if (live_instance)
1384     {
1385         CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name),false);
1386     }
1387 }
1388 
1389 ThreadInstanceSettings::ThreadInstanceSettings (const ThreadInstanceSettings &rhs) :
1390     InstanceSettings (Thread::GetSettingsController(), CreateInstanceName().AsCString()),
1391     m_avoid_regexp_ap (),
1392     m_trace_enabled (rhs.m_trace_enabled)
1393 {
1394     if (m_instance_name != InstanceSettings::GetDefaultName())
1395     {
1396         UserSettingsControllerSP owner_sp (m_owner_wp.lock());
1397         if (owner_sp)
1398         {
1399             CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
1400             owner_sp->RemovePendingSettings (m_instance_name);
1401         }
1402     }
1403     if (rhs.m_avoid_regexp_ap.get() != NULL)
1404         m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1405 }
1406 
1407 ThreadInstanceSettings::~ThreadInstanceSettings ()
1408 {
1409 }
1410 
1411 ThreadInstanceSettings&
1412 ThreadInstanceSettings::operator= (const ThreadInstanceSettings &rhs)
1413 {
1414     if (this != &rhs)
1415     {
1416         if (rhs.m_avoid_regexp_ap.get() != NULL)
1417             m_avoid_regexp_ap.reset(new RegularExpression(rhs.m_avoid_regexp_ap->GetText()));
1418         else
1419             m_avoid_regexp_ap.reset(NULL);
1420     }
1421     m_trace_enabled = rhs.m_trace_enabled;
1422     return *this;
1423 }
1424 
1425 
1426 void
1427 ThreadInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1428                                                          const char *index_value,
1429                                                          const char *value,
1430                                                          const ConstString &instance_name,
1431                                                          const SettingEntry &entry,
1432                                                          VarSetOperationType op,
1433                                                          Error &err,
1434                                                          bool pending)
1435 {
1436     if (var_name == StepAvoidRegexpVarName())
1437     {
1438         std::string regexp_text;
1439         if (m_avoid_regexp_ap.get() != NULL)
1440             regexp_text.append (m_avoid_regexp_ap->GetText());
1441         UserSettingsController::UpdateStringVariable (op, regexp_text, value, err);
1442         if (regexp_text.empty())
1443             m_avoid_regexp_ap.reset();
1444         else
1445         {
1446             m_avoid_regexp_ap.reset(new RegularExpression(regexp_text.c_str()));
1447 
1448         }
1449     }
1450     else if (var_name == GetTraceThreadVarName())
1451     {
1452         bool success;
1453         bool result = Args::StringToBoolean(value, false, &success);
1454 
1455         if (success)
1456         {
1457             m_trace_enabled = result;
1458             if (!pending)
1459             {
1460                 Thread *myself = static_cast<Thread *> (this);
1461                 myself->EnableTracer(m_trace_enabled, true);
1462             }
1463         }
1464         else
1465         {
1466             err.SetErrorStringWithFormat ("Bad value \"%s\" for trace-thread, should be Boolean.", value);
1467         }
1468 
1469     }
1470 }
1471 
1472 void
1473 ThreadInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
1474                                                bool pending)
1475 {
1476     if (new_settings.get() == NULL)
1477         return;
1478 
1479     ThreadInstanceSettings *new_process_settings = (ThreadInstanceSettings *) new_settings.get();
1480     if (new_process_settings->GetSymbolsToAvoidRegexp() != NULL)
1481         m_avoid_regexp_ap.reset (new RegularExpression (new_process_settings->GetSymbolsToAvoidRegexp()->GetText()));
1482     else
1483         m_avoid_regexp_ap.reset ();
1484 }
1485 
1486 bool
1487 ThreadInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1488                                                   const ConstString &var_name,
1489                                                   StringList &value,
1490                                                   Error *err)
1491 {
1492     if (var_name == StepAvoidRegexpVarName())
1493     {
1494         if (m_avoid_regexp_ap.get() != NULL)
1495         {
1496             std::string regexp_text("\"");
1497             regexp_text.append(m_avoid_regexp_ap->GetText());
1498             regexp_text.append ("\"");
1499             value.AppendString (regexp_text.c_str());
1500         }
1501 
1502     }
1503     else if (var_name == GetTraceThreadVarName())
1504     {
1505         value.AppendString(m_trace_enabled ? "true" : "false");
1506     }
1507     else
1508     {
1509         if (err)
1510             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1511         return false;
1512     }
1513     return true;
1514 }
1515 
1516 const ConstString
1517 ThreadInstanceSettings::CreateInstanceName ()
1518 {
1519     static int instance_count = 1;
1520     StreamString sstr;
1521 
1522     sstr.Printf ("thread_%d", instance_count);
1523     ++instance_count;
1524 
1525     const ConstString ret_val (sstr.GetData());
1526     return ret_val;
1527 }
1528 
1529 const ConstString &
1530 ThreadInstanceSettings::StepAvoidRegexpVarName ()
1531 {
1532     static ConstString step_avoid_var_name ("step-avoid-regexp");
1533 
1534     return step_avoid_var_name;
1535 }
1536 
1537 const ConstString &
1538 ThreadInstanceSettings::GetTraceThreadVarName ()
1539 {
1540     static ConstString trace_thread_var_name ("trace-thread");
1541 
1542     return trace_thread_var_name;
1543 }
1544 
1545 //--------------------------------------------------
1546 // SettingsController Variable Tables
1547 //--------------------------------------------------
1548 
1549 SettingEntry
1550 Thread::SettingsController::global_settings_table[] =
1551 {
1552   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
1553     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1554 };
1555 
1556 
1557 SettingEntry
1558 Thread::SettingsController::instance_settings_table[] =
1559 {
1560   //{ "var-name",    var-type,              "default",      enum-table, init'd, hidden, "help-text"},
1561     { "step-avoid-regexp",  eSetVarTypeString,      "",  NULL,       false,  false,  "A regular expression defining functions step-in won't stop in." },
1562     { "trace-thread",  eSetVarTypeBoolean,      "false",  NULL,       false,  false,  "If true, this thread will single-step and log execution." },
1563     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1564 };
1565