xref: /llvm-project/lldb/source/Commands/CommandObjectThread.cpp (revision 7428a18c1e9ba131022184746889b69308c0180d)
1 //===-- CommandObjectThread.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 "CommandObjectThread.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/lldb-private.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Core/SourceManager.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/StringConvert.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/Options.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/LineTable.h"
28 #include "lldb/Symbol/LineEntry.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/RegisterContext.h"
31 #include "lldb/Target/SystemRuntime.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 #include "lldb/Target/ThreadPlan.h"
35 #include "lldb/Target/ThreadPlanStepInstruction.h"
36 #include "lldb/Target/ThreadPlanStepOut.h"
37 #include "lldb/Target/ThreadPlanStepRange.h"
38 #include "lldb/Target/ThreadPlanStepInRange.h"
39 
40 using namespace lldb;
41 using namespace lldb_private;
42 
43 //-------------------------------------------------------------------------
44 // CommandObjectThreadBacktrace
45 //-------------------------------------------------------------------------
46 
47 class CommandObjectIterateOverThreads : public CommandObjectParsed
48 {
49 public:
50     CommandObjectIterateOverThreads (CommandInterpreter &interpreter,
51                          const char *name,
52                          const char *help,
53                          const char *syntax,
54                          uint32_t flags) :
55         CommandObjectParsed (interpreter, name, help, syntax, flags)
56     {
57     }
58 
59     ~CommandObjectIterateOverThreads() override = default;
60 
61     bool
62     DoExecute (Args& command, CommandReturnObject &result) override
63     {
64         result.SetStatus (m_success_return);
65 
66         if (command.GetArgumentCount() == 0)
67         {
68             Thread *thread = m_exe_ctx.GetThreadPtr();
69             if (!HandleOneThread (thread->GetID(), result))
70                 return false;
71             return result.Succeeded();
72         }
73 
74         // Use tids instead of ThreadSPs to prevent deadlocking problems which result from JIT-ing
75         // code while iterating over the (locked) ThreadSP list.
76         std::vector<lldb::tid_t> tids;
77 
78         if (command.GetArgumentCount() == 1 && ::strcmp (command.GetArgumentAtIndex(0), "all") == 0)
79         {
80             Process *process = m_exe_ctx.GetProcessPtr();
81 
82             for (ThreadSP thread_sp : process->Threads())
83                 tids.push_back(thread_sp->GetID());
84         }
85         else
86         {
87             const size_t num_args = command.GetArgumentCount();
88             Process *process = m_exe_ctx.GetProcessPtr();
89 
90             std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
91 
92             for (size_t i = 0; i < num_args; i++)
93             {
94                 bool success;
95 
96                 uint32_t thread_idx = StringConvert::ToUInt32(command.GetArgumentAtIndex(i), 0, 0, &success);
97                 if (!success)
98                 {
99                     result.AppendErrorWithFormat ("invalid thread specification: \"%s\"\n", command.GetArgumentAtIndex(i));
100                     result.SetStatus (eReturnStatusFailed);
101                     return false;
102                 }
103 
104                 ThreadSP thread = process->GetThreadList().FindThreadByIndexID(thread_idx);
105 
106                 if (!thread)
107                 {
108                     result.AppendErrorWithFormat ("no thread with index: \"%s\"\n", command.GetArgumentAtIndex(i));
109                     result.SetStatus (eReturnStatusFailed);
110                     return false;
111                 }
112 
113                 tids.push_back(thread->GetID());
114             }
115         }
116 
117         uint32_t idx = 0;
118         for (const lldb::tid_t &tid : tids)
119         {
120             if (idx != 0 && m_add_return)
121                 result.AppendMessage("");
122 
123             if (!HandleOneThread (tid, result))
124                 return false;
125 
126             ++idx;
127         }
128         return result.Succeeded();
129     }
130 
131 protected:
132     // Override this to do whatever you need to do for one thread.
133     //
134     // If you return false, the iteration will stop, otherwise it will proceed.
135     // The result is set to m_success_return (defaults to eReturnStatusSuccessFinishResult) before the iteration,
136     // so you only need to set the return status in HandleOneThread if you want to indicate an error.
137     // If m_add_return is true, a blank line will be inserted between each of the listings (except the last one.)
138 
139     virtual bool
140     HandleOneThread (lldb::tid_t, CommandReturnObject &result) = 0;
141 
142     ReturnStatus m_success_return = eReturnStatusSuccessFinishResult;
143     bool m_add_return = true;
144 };
145 
146 //-------------------------------------------------------------------------
147 // CommandObjectThreadBacktrace
148 //-------------------------------------------------------------------------
149 
150 class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads
151 {
152 public:
153     class CommandOptions : public Options
154     {
155     public:
156         CommandOptions (CommandInterpreter &interpreter) :
157             Options(interpreter)
158         {
159             // Keep default values of all options in one place: OptionParsingStarting ()
160             OptionParsingStarting ();
161         }
162 
163         ~CommandOptions() override = default;
164 
165         Error
166         SetOptionValue (uint32_t option_idx, const char *option_arg) override
167         {
168             Error error;
169             const int short_option = m_getopt_table[option_idx].val;
170 
171             switch (short_option)
172             {
173                 case 'c':
174                 {
175                     bool success;
176                     int32_t input_count =  StringConvert::ToSInt32 (option_arg, -1, 0, &success);
177                     if (!success)
178                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
179                     if (input_count < -1)
180                         m_count = UINT32_MAX;
181                     else
182                         m_count = input_count;
183                 }
184                 break;
185                 case 's':
186                 {
187                     bool success;
188                     m_start =  StringConvert::ToUInt32 (option_arg, 0, 0, &success);
189                     if (!success)
190                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
191                 }
192                 break;
193                 case 'e':
194                 {
195                     bool success;
196                     m_extended_backtrace =  Args::StringToBoolean (option_arg, false, &success);
197                     if (!success)
198                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
199                 }
200                 break;
201                 default:
202                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
203                     break;
204             }
205             return error;
206         }
207 
208         void
209         OptionParsingStarting () override
210         {
211             m_count = UINT32_MAX;
212             m_start = 0;
213             m_extended_backtrace = false;
214         }
215 
216         const OptionDefinition*
217         GetDefinitions () override
218         {
219             return g_option_table;
220         }
221 
222         // Options table: Required for subclasses of Options.
223 
224         static OptionDefinition g_option_table[];
225 
226         // Instance variables to hold the values for command options.
227         uint32_t m_count;
228         uint32_t m_start;
229         bool     m_extended_backtrace;
230     };
231 
232     CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
233         : CommandObjectIterateOverThreads(
234               interpreter, "thread backtrace", "Show thread call stacks.  Defaults to the current thread, thread "
235                                                "indexes can be specified as arguments.  Use the thread-index \"all\" "
236                                                "to see all threads.",
237               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
238                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
239           m_options(interpreter)
240     {
241     }
242 
243     ~CommandObjectThreadBacktrace() override = default;
244 
245     Options *
246     GetOptions () override
247     {
248         return &m_options;
249     }
250 
251 protected:
252     void
253     DoExtendedBacktrace (Thread *thread, CommandReturnObject &result)
254     {
255         SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime();
256         if (runtime)
257         {
258             Stream &strm = result.GetOutputStream();
259             const std::vector<ConstString> &types = runtime->GetExtendedBacktraceTypes();
260             for (auto type : types)
261             {
262                 ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread (thread->shared_from_this(), type);
263                 if (ext_thread_sp && ext_thread_sp->IsValid ())
264                 {
265                     const uint32_t num_frames_with_source = 0;
266                     if (ext_thread_sp->GetStatus (strm,
267                         m_options.m_start,
268                         m_options.m_count,
269                         num_frames_with_source))
270                     {
271                         DoExtendedBacktrace (ext_thread_sp.get(), result);
272                     }
273                 }
274             }
275         }
276     }
277 
278     bool
279     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
280     {
281         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
282         if (!thread_sp)
283         {
284             result.AppendErrorWithFormat ("thread disappeared while computing backtraces: 0x%" PRIx64 "\n", tid);
285             result.SetStatus (eReturnStatusFailed);
286             return false;
287         }
288 
289         Thread *thread = thread_sp.get();
290 
291         Stream &strm = result.GetOutputStream();
292 
293         // Don't show source context when doing backtraces.
294         const uint32_t num_frames_with_source = 0;
295 
296         if (!thread->GetStatus (strm,
297                                 m_options.m_start,
298                                 m_options.m_count,
299                                 num_frames_with_source))
300         {
301             result.AppendErrorWithFormat ("error displaying backtrace for thread: \"0x%4.4x\"\n", thread->GetIndexID());
302             result.SetStatus (eReturnStatusFailed);
303             return false;
304         }
305         if (m_options.m_extended_backtrace)
306         {
307             DoExtendedBacktrace (thread, result);
308         }
309 
310         return true;
311     }
312 
313     CommandOptions m_options;
314 };
315 
316 OptionDefinition
317 CommandObjectThreadBacktrace::CommandOptions::g_option_table[] =
318 {
319 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many frames to display (-1 for all)"},
320 { LLDB_OPT_SET_1, false, "start", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame in which to start the backtrace"},
321 { LLDB_OPT_SET_1, false, "extended", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Show the extended backtrace, if available"},
322 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
323 };
324 
325 enum StepScope
326 {
327     eStepScopeSource,
328     eStepScopeInstruction
329 };
330 
331 class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed
332 {
333 public:
334     class CommandOptions : public Options
335     {
336     public:
337         CommandOptions (CommandInterpreter &interpreter) :
338             Options (interpreter)
339         {
340             // Keep default values of all options in one place: OptionParsingStarting ()
341             OptionParsingStarting ();
342         }
343 
344         ~CommandOptions() override = default;
345 
346         Error
347         SetOptionValue (uint32_t option_idx, const char *option_arg) override
348         {
349             Error error;
350             const int short_option = m_getopt_table[option_idx].val;
351 
352             switch (short_option)
353             {
354             case 'a':
355                 {
356                     bool success;
357                     bool avoid_no_debug =  Args::StringToBoolean (option_arg, true, &success);
358                     if (!success)
359                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
360                     else
361                     {
362                         m_step_in_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
363                     }
364                 }
365                 break;
366 
367             case 'A':
368                 {
369                     bool success;
370                     bool avoid_no_debug =  Args::StringToBoolean (option_arg, true, &success);
371                     if (!success)
372                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
373                     else
374                     {
375                         m_step_out_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
376                     }
377                 }
378                 break;
379 
380             case 'c':
381                 m_step_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0);
382                 if (m_step_count == UINT32_MAX)
383                     error.SetErrorStringWithFormat ("invalid step count '%s'", option_arg);
384                 break;
385 
386             case 'C':
387                 m_class_name.clear();
388                 m_class_name.assign(option_arg);
389                 break;
390 
391             case 'm':
392                 {
393                     OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values;
394                     m_run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error);
395                 }
396                 break;
397 
398             case 'e':
399                 {
400                     if (strcmp(option_arg, "block") == 0)
401                     {
402                         m_end_line_is_block_end = 1;
403                         break;
404                     }
405                     uint32_t tmp_end_line = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0);
406                     if (tmp_end_line == UINT32_MAX)
407                        error.SetErrorStringWithFormat ("invalid end line number '%s'", option_arg);
408                     else
409                         m_end_line = tmp_end_line;
410                     break;
411                 }
412                 break;
413 
414             case 'r':
415                 m_avoid_regexp.clear();
416                 m_avoid_regexp.assign(option_arg);
417                 break;
418 
419             case 't':
420                 m_step_in_target.clear();
421                 m_step_in_target.assign(option_arg);
422                 break;
423 
424             default:
425                 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
426                 break;
427             }
428             return error;
429         }
430 
431         void
432         OptionParsingStarting () override
433         {
434             m_step_in_avoid_no_debug = eLazyBoolCalculate;
435             m_step_out_avoid_no_debug = eLazyBoolCalculate;
436             m_run_mode = eOnlyDuringStepping;
437 
438             // Check if we are in Non-Stop mode
439             lldb::TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget();
440             if (target_sp && target_sp->GetNonStopModeEnabled())
441                 m_run_mode = eOnlyThisThread;
442 
443             m_avoid_regexp.clear();
444             m_step_in_target.clear();
445             m_class_name.clear();
446             m_step_count = 1;
447             m_end_line = LLDB_INVALID_LINE_NUMBER;
448             m_end_line_is_block_end = false;
449         }
450 
451         const OptionDefinition*
452         GetDefinitions () override
453         {
454             return g_option_table;
455         }
456 
457         // Options table: Required for subclasses of Options.
458 
459         static OptionDefinition g_option_table[];
460 
461         // Instance variables to hold the values for command options.
462         LazyBool m_step_in_avoid_no_debug;
463         LazyBool m_step_out_avoid_no_debug;
464         RunMode m_run_mode;
465         std::string m_avoid_regexp;
466         std::string m_step_in_target;
467         std::string m_class_name;
468         uint32_t m_step_count;
469         uint32_t m_end_line;
470         bool     m_end_line_is_block_end;
471     };
472 
473     CommandObjectThreadStepWithTypeAndScope (CommandInterpreter &interpreter,
474                                              const char *name,
475                                              const char *help,
476                                              const char *syntax,
477                                              StepType step_type,
478                                              StepScope step_scope) :
479         CommandObjectParsed (interpreter, name, help, syntax,
480                              eCommandRequiresProcess       |
481                              eCommandRequiresThread        |
482                              eCommandTryTargetAPILock      |
483                              eCommandProcessMustBeLaunched |
484                              eCommandProcessMustBePaused   ),
485         m_step_type (step_type),
486         m_step_scope (step_scope),
487         m_options (interpreter)
488     {
489         CommandArgumentEntry arg;
490         CommandArgumentData thread_id_arg;
491 
492         // Define the first (and only) variant of this arg.
493         thread_id_arg.arg_type = eArgTypeThreadID;
494         thread_id_arg.arg_repetition = eArgRepeatOptional;
495 
496         // There is only one variant this argument could be; put it into the argument entry.
497         arg.push_back (thread_id_arg);
498 
499         // Push the data for the first argument into the m_arguments vector.
500         m_arguments.push_back (arg);
501     }
502 
503     ~CommandObjectThreadStepWithTypeAndScope() override = default;
504 
505     Options *
506     GetOptions () override
507     {
508         return &m_options;
509     }
510 
511 protected:
512     bool
513     DoExecute (Args& command, CommandReturnObject &result) override
514     {
515         Process *process = m_exe_ctx.GetProcessPtr();
516         bool synchronous_execution = m_interpreter.GetSynchronous();
517 
518         const uint32_t num_threads = process->GetThreadList().GetSize();
519         Thread *thread = nullptr;
520 
521         if (command.GetArgumentCount() == 0)
522         {
523             thread = GetDefaultThread();
524 
525             if (thread == nullptr)
526             {
527                 result.AppendError ("no selected thread in process");
528                 result.SetStatus (eReturnStatusFailed);
529                 return false;
530             }
531         }
532         else
533         {
534             const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
535             uint32_t step_thread_idx = StringConvert::ToUInt32 (thread_idx_cstr, LLDB_INVALID_INDEX32);
536             if (step_thread_idx == LLDB_INVALID_INDEX32)
537             {
538                 result.AppendErrorWithFormat ("invalid thread index '%s'.\n", thread_idx_cstr);
539                 result.SetStatus (eReturnStatusFailed);
540                 return false;
541             }
542             thread = process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
543             if (thread == nullptr)
544             {
545                 result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n",
546                                               step_thread_idx, num_threads);
547                 result.SetStatus (eReturnStatusFailed);
548                 return false;
549             }
550         }
551 
552         if (m_step_type == eStepTypeScripted)
553         {
554             if (m_options.m_class_name.empty())
555             {
556                 result.AppendErrorWithFormat ("empty class name for scripted step.");
557                 result.SetStatus(eReturnStatusFailed);
558                 return false;
559             }
560             else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists(m_options.m_class_name.c_str()))
561             {
562                 result.AppendErrorWithFormat ("class for scripted step: \"%s\" does not exist.", m_options.m_class_name.c_str());
563                 result.SetStatus(eReturnStatusFailed);
564                 return false;
565             }
566         }
567 
568         if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER
569             && m_step_type != eStepTypeInto)
570         {
571             result.AppendErrorWithFormat("end line option is only valid for step into");
572             result.SetStatus(eReturnStatusFailed);
573             return false;
574         }
575 
576         const bool abort_other_plans = false;
577         const lldb::RunMode stop_other_threads = m_options.m_run_mode;
578 
579         // This is a bit unfortunate, but not all the commands in this command object support
580         // only while stepping, so I use the bool for them.
581         bool bool_stop_other_threads;
582         if (m_options.m_run_mode == eAllThreads)
583             bool_stop_other_threads = false;
584         else if (m_options.m_run_mode == eOnlyDuringStepping)
585             bool_stop_other_threads = (m_step_type != eStepTypeOut && m_step_type != eStepTypeScripted);
586         else
587             bool_stop_other_threads = true;
588 
589         ThreadPlanSP new_plan_sp;
590 
591         if (m_step_type == eStepTypeInto)
592         {
593             StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
594             assert(frame != nullptr);
595 
596             if (frame->HasDebugInformation ())
597             {
598                 AddressRange range;
599                 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
600                 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER)
601                 {
602                     Error error;
603                     if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range, error))
604                     {
605                         result.AppendErrorWithFormat("invalid end-line option: %s.", error.AsCString());
606                         result.SetStatus(eReturnStatusFailed);
607                         return false;
608                     }
609                 }
610                 else if (m_options.m_end_line_is_block_end)
611                 {
612                     Error error;
613                     Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
614                     if (!block)
615                     {
616                         result.AppendErrorWithFormat("Could not find the current block.");
617                         result.SetStatus(eReturnStatusFailed);
618                         return false;
619                     }
620 
621                     AddressRange block_range;
622                     Address pc_address = frame->GetFrameCodeAddress();
623                     block->GetRangeContainingAddress(pc_address, block_range);
624                     if (!block_range.GetBaseAddress().IsValid())
625                     {
626                         result.AppendErrorWithFormat("Could not find the current block address.");
627                         result.SetStatus(eReturnStatusFailed);
628                         return false;
629                     }
630                     lldb::addr_t pc_offset_in_block = pc_address.GetFileAddress() - block_range.GetBaseAddress().GetFileAddress();
631                     lldb::addr_t range_length = block_range.GetByteSize() - pc_offset_in_block;
632                     range = AddressRange(pc_address, range_length);
633                 }
634                 else
635                 {
636                     range = sc.line_entry.range;
637                 }
638 
639                 new_plan_sp = thread->QueueThreadPlanForStepInRange (abort_other_plans,
640                                                                      range,
641                                                                      frame->GetSymbolContext(eSymbolContextEverything),
642                                                                      m_options.m_step_in_target.c_str(),
643                                                                      stop_other_threads,
644                                                                      m_options.m_step_in_avoid_no_debug,
645                                                                      m_options.m_step_out_avoid_no_debug);
646 
647                 if (new_plan_sp && !m_options.m_avoid_regexp.empty())
648                 {
649                     ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (new_plan_sp.get());
650                     step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
651                 }
652             }
653             else
654                 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads);
655         }
656         else if (m_step_type == eStepTypeOver)
657         {
658             StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
659 
660             if (frame->HasDebugInformation())
661                 new_plan_sp = thread->QueueThreadPlanForStepOverRange (abort_other_plans,
662                                                                     frame->GetSymbolContext(eSymbolContextEverything).line_entry,
663                                                                     frame->GetSymbolContext(eSymbolContextEverything),
664                                                                     stop_other_threads,
665                                                                     m_options.m_step_out_avoid_no_debug);
666             else
667                 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true,
668                                                                             abort_other_plans,
669                                                                             bool_stop_other_threads);
670         }
671         else if (m_step_type == eStepTypeTrace)
672         {
673             new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads);
674         }
675         else if (m_step_type == eStepTypeTraceOver)
676         {
677             new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true, abort_other_plans, bool_stop_other_threads);
678         }
679         else if (m_step_type == eStepTypeOut)
680         {
681             new_plan_sp = thread->QueueThreadPlanForStepOut(abort_other_plans,
682                                                             nullptr,
683                                                             false,
684                                                             bool_stop_other_threads,
685                                                             eVoteYes,
686                                                             eVoteNoOpinion,
687                                                             thread->GetSelectedFrameIndex(),
688                                                             m_options.m_step_out_avoid_no_debug);
689         }
690         else if (m_step_type == eStepTypeScripted)
691         {
692             new_plan_sp = thread->QueueThreadPlanForStepScripted (abort_other_plans,
693                                                                   m_options.m_class_name.c_str(),
694                                                                   bool_stop_other_threads);
695         }
696         else
697         {
698             result.AppendError ("step type is not supported");
699             result.SetStatus (eReturnStatusFailed);
700             return false;
701         }
702 
703         // If we got a new plan, then set it to be a master plan (User level Plans should be master plans
704         // so that they can be interruptible).  Then resume the process.
705 
706         if (new_plan_sp)
707         {
708             new_plan_sp->SetIsMasterPlan (true);
709             new_plan_sp->SetOkayToDiscard (false);
710 
711             if (m_options.m_step_count > 1)
712             {
713                 if (new_plan_sp->SetIterationCount(m_options.m_step_count))
714                 {
715                     result.AppendWarning ("step operation does not support iteration count.");
716                 }
717             }
718 
719             process->GetThreadList().SetSelectedThreadByID (thread->GetID());
720 
721             const uint32_t iohandler_id = process->GetIOHandlerID();
722 
723             StreamString stream;
724             Error error;
725             if (synchronous_execution)
726                 error = process->ResumeSynchronous (&stream);
727             else
728                 error = process->Resume ();
729 
730             // There is a race condition where this thread will return up the call stack to the main command handler
731             // and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has
732             // a chance to call PushProcessIOHandler().
733             process->SyncIOHandler(iohandler_id, 2000);
734 
735             if (synchronous_execution)
736             {
737                 // If any state changed events had anything to say, add that to the result
738                 if (stream.GetData())
739                     result.AppendMessage(stream.GetData());
740 
741                 process->GetThreadList().SetSelectedThreadByID (thread->GetID());
742                 result.SetDidChangeProcessState (true);
743                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
744             }
745             else
746             {
747                 result.SetStatus (eReturnStatusSuccessContinuingNoResult);
748             }
749         }
750         else
751         {
752             result.AppendError ("Couldn't find thread plan to implement step type.");
753             result.SetStatus (eReturnStatusFailed);
754         }
755         return result.Succeeded();
756     }
757 
758 protected:
759     StepType m_step_type;
760     StepScope m_step_scope;
761     CommandOptions m_options;
762 };
763 
764 static OptionEnumValueElement
765 g_tri_running_mode[] =
766 {
767 { eOnlyThisThread,     "this-thread",    "Run only this thread"},
768 { eAllThreads,         "all-threads",    "Run all threads"},
769 { eOnlyDuringStepping, "while-stepping", "Run only this thread while stepping"},
770 { 0, nullptr, nullptr }
771 };
772 
773 static OptionEnumValueElement
774 g_duo_running_mode[] =
775 {
776 { eOnlyThisThread,     "this-thread",    "Run only this thread"},
777 { eAllThreads,         "all-threads",    "Run all threads"},
778 { 0, nullptr, nullptr }
779 };
780 
781 OptionDefinition
782 CommandObjectThreadStepWithTypeAndScope::CommandOptions::g_option_table[] =
783 {
784 { LLDB_OPT_SET_1, false, "step-in-avoids-no-debug",   'a', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeBoolean,     "A boolean value that sets whether stepping into functions will step over functions with no debug information."},
785 { LLDB_OPT_SET_1, false, "step-out-avoids-no-debug",  'A', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeBoolean,     "A boolean value, if true stepping out of functions will continue to step out till it hits a function with debug information."},
786 { LLDB_OPT_SET_1, false, "count",                     'c', OptionParser::eRequiredArgument, nullptr, nullptr,               1, eArgTypeCount,     "How many times to perform the stepping operation - currently only supported for step-inst and next-inst."},
787 { LLDB_OPT_SET_1, false, "end-linenumber",            'e', OptionParser::eRequiredArgument, nullptr, nullptr,               1, eArgTypeLineNum,     "The line at which to stop stepping - defaults to the next line and only supported for step-in and step-over."
788                                                                                                                                               "  You can also pass the string 'block' to step to the end of the current block."
789                                                                                                                                               "  This is particularly useful in conjunction with --step-target to step through a complex calling sequence."},
790 { LLDB_OPT_SET_1, false, "run-mode",                  'm', OptionParser::eRequiredArgument, nullptr, g_tri_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping the current thread."},
791 { LLDB_OPT_SET_1, false, "step-over-regexp",          'r', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeRegularExpression,   "A regular expression that defines function names to not to stop at when stepping in."},
792 { LLDB_OPT_SET_1, false, "step-in-target",            't', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeFunctionName,   "The name of the directly called function step in should stop at when stepping into."},
793 { LLDB_OPT_SET_2, false, "python-class",              'C', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonClass, "The name of the class that will manage this step - only supported for Scripted Step."},
794 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
795 };
796 
797 //-------------------------------------------------------------------------
798 // CommandObjectThreadContinue
799 //-------------------------------------------------------------------------
800 
801 class CommandObjectThreadContinue : public CommandObjectParsed
802 {
803 public:
804     CommandObjectThreadContinue(CommandInterpreter &interpreter)
805         : CommandObjectParsed(interpreter, "thread continue", "Continue execution of the current target process.  One "
806                                                               "or more threads may be specified, by default all "
807                                                               "threads continue.",
808                               nullptr, eCommandRequiresThread | eCommandTryTargetAPILock |
809                                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
810     {
811         CommandArgumentEntry arg;
812         CommandArgumentData thread_idx_arg;
813 
814         // Define the first (and only) variant of this arg.
815         thread_idx_arg.arg_type = eArgTypeThreadIndex;
816         thread_idx_arg.arg_repetition = eArgRepeatPlus;
817 
818         // There is only one variant this argument could be; put it into the argument entry.
819         arg.push_back (thread_idx_arg);
820 
821         // Push the data for the first argument into the m_arguments vector.
822         m_arguments.push_back (arg);
823     }
824 
825     ~CommandObjectThreadContinue() override = default;
826 
827     bool
828     DoExecute (Args& command, CommandReturnObject &result) override
829     {
830         bool synchronous_execution = m_interpreter.GetSynchronous ();
831 
832         if (!m_interpreter.GetDebugger().GetSelectedTarget())
833         {
834             result.AppendError ("invalid target, create a debug target using the 'target create' command");
835             result.SetStatus (eReturnStatusFailed);
836             return false;
837         }
838 
839         Process *process = m_exe_ctx.GetProcessPtr();
840         if (process == nullptr)
841         {
842             result.AppendError ("no process exists. Cannot continue");
843             result.SetStatus (eReturnStatusFailed);
844             return false;
845         }
846 
847         StateType state = process->GetState();
848         if ((state == eStateCrashed) || (state == eStateStopped) || (state == eStateSuspended))
849         {
850             const size_t argc = command.GetArgumentCount();
851             if (argc > 0)
852             {
853                 // These two lines appear at the beginning of both blocks in
854                 // this if..else, but that is because we need to release the
855                 // lock before calling process->Resume below.
856                 std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
857                 const uint32_t num_threads = process->GetThreadList().GetSize();
858                 std::vector<Thread *> resume_threads;
859                 for (uint32_t i = 0; i < argc; ++i)
860                 {
861                     bool success;
862                     const int base = 0;
863                     uint32_t thread_idx = StringConvert::ToUInt32 (command.GetArgumentAtIndex(i), LLDB_INVALID_INDEX32, base, &success);
864                     if (success)
865                     {
866                         Thread *thread = process->GetThreadList().FindThreadByIndexID(thread_idx).get();
867 
868                         if (thread)
869                         {
870                             resume_threads.push_back(thread);
871                         }
872                         else
873                         {
874                             result.AppendErrorWithFormat("invalid thread index %u.\n", thread_idx);
875                             result.SetStatus (eReturnStatusFailed);
876                             return false;
877                         }
878                     }
879                     else
880                     {
881                         result.AppendErrorWithFormat ("invalid thread index argument: \"%s\".\n", command.GetArgumentAtIndex(i));
882                         result.SetStatus (eReturnStatusFailed);
883                         return false;
884                     }
885                 }
886 
887                 if (resume_threads.empty())
888                 {
889                     result.AppendError ("no valid thread indexes were specified");
890                     result.SetStatus (eReturnStatusFailed);
891                     return false;
892                 }
893                 else
894                 {
895                     if (resume_threads.size() == 1)
896                         result.AppendMessageWithFormat ("Resuming thread: ");
897                     else
898                         result.AppendMessageWithFormat ("Resuming threads: ");
899 
900                     for (uint32_t idx = 0; idx < num_threads; ++idx)
901                     {
902                         Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
903                         std::vector<Thread *>::iterator this_thread_pos = find(resume_threads.begin(), resume_threads.end(), thread);
904 
905                         if (this_thread_pos != resume_threads.end())
906                         {
907                             resume_threads.erase(this_thread_pos);
908                             if (!resume_threads.empty())
909                                 result.AppendMessageWithFormat ("%u, ", thread->GetIndexID());
910                             else
911                                 result.AppendMessageWithFormat ("%u ", thread->GetIndexID());
912 
913                             const bool override_suspend = true;
914                             thread->SetResumeState (eStateRunning, override_suspend);
915                         }
916                         else
917                         {
918                             thread->SetResumeState (eStateSuspended);
919                         }
920                     }
921                     result.AppendMessageWithFormat ("in process %" PRIu64 "\n", process->GetID());
922                 }
923             }
924             else
925             {
926                 // These two lines appear at the beginning of both blocks in
927                 // this if..else, but that is because we need to release the
928                 // lock before calling process->Resume below.
929                 std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
930                 const uint32_t num_threads = process->GetThreadList().GetSize();
931                 Thread *current_thread = GetDefaultThread();
932                 if (current_thread == nullptr)
933                 {
934                     result.AppendError ("the process doesn't have a current thread");
935                     result.SetStatus (eReturnStatusFailed);
936                     return false;
937                 }
938                 // Set the actions that the threads should each take when resuming
939                 for (uint32_t idx = 0; idx < num_threads; ++idx)
940                 {
941                     Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
942                     if (thread == current_thread)
943                     {
944                         result.AppendMessageWithFormat ("Resuming thread 0x%4.4" PRIx64 " in process %" PRIu64 "\n", thread->GetID(), process->GetID());
945                         const bool override_suspend = true;
946                         thread->SetResumeState (eStateRunning, override_suspend);
947                     }
948                     else
949                     {
950                         thread->SetResumeState (eStateSuspended);
951                     }
952                 }
953             }
954 
955             StreamString stream;
956             Error error;
957             if (synchronous_execution)
958                 error = process->ResumeSynchronous (&stream);
959             else
960                 error = process->Resume ();
961 
962             // We should not be holding the thread list lock when we do this.
963             if (error.Success())
964             {
965                 result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID());
966                 if (synchronous_execution)
967                 {
968                     // If any state changed events had anything to say, add that to the result
969                     if (stream.GetData())
970                         result.AppendMessage(stream.GetData());
971 
972                     result.SetDidChangeProcessState (true);
973                     result.SetStatus (eReturnStatusSuccessFinishNoResult);
974                 }
975                 else
976                 {
977                     result.SetStatus (eReturnStatusSuccessContinuingNoResult);
978                 }
979             }
980             else
981             {
982                 result.AppendErrorWithFormat("Failed to resume process: %s\n", error.AsCString());
983                 result.SetStatus (eReturnStatusFailed);
984             }
985         }
986         else
987         {
988             result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n",
989                                           StateAsCString(state));
990             result.SetStatus (eReturnStatusFailed);
991         }
992 
993         return result.Succeeded();
994     }
995 };
996 
997 //-------------------------------------------------------------------------
998 // CommandObjectThreadUntil
999 //-------------------------------------------------------------------------
1000 
1001 class CommandObjectThreadUntil : public CommandObjectParsed
1002 {
1003 public:
1004     class CommandOptions : public Options
1005     {
1006     public:
1007         uint32_t m_thread_idx;
1008         uint32_t m_frame_idx;
1009 
1010         CommandOptions (CommandInterpreter &interpreter) :
1011             Options (interpreter),
1012             m_thread_idx(LLDB_INVALID_THREAD_ID),
1013             m_frame_idx(LLDB_INVALID_FRAME_ID)
1014         {
1015             // Keep default values of all options in one place: OptionParsingStarting ()
1016             OptionParsingStarting ();
1017         }
1018 
1019         ~CommandOptions() override = default;
1020 
1021         Error
1022         SetOptionValue (uint32_t option_idx, const char *option_arg) override
1023         {
1024             Error error;
1025             const int short_option = m_getopt_table[option_idx].val;
1026 
1027             switch (short_option)
1028             {
1029                 case 'a':
1030                 {
1031                     ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
1032                     lldb::addr_t tmp_addr = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
1033                     if (error.Success())
1034                         m_until_addrs.push_back(tmp_addr);
1035                 }
1036                 break;
1037                 case 't':
1038                     m_thread_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_INDEX32);
1039                     if (m_thread_idx == LLDB_INVALID_INDEX32)
1040                     {
1041                         error.SetErrorStringWithFormat ("invalid thread index '%s'", option_arg);
1042                     }
1043                     break;
1044                 case 'f':
1045                     m_frame_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_FRAME_ID);
1046                     if (m_frame_idx == LLDB_INVALID_FRAME_ID)
1047                     {
1048                         error.SetErrorStringWithFormat ("invalid frame index '%s'", option_arg);
1049                     }
1050                     break;
1051                 case 'm':
1052                 {
1053                     OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values;
1054                     lldb::RunMode run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error);
1055 
1056                     if (error.Success())
1057                     {
1058                         if (run_mode == eAllThreads)
1059                             m_stop_others = false;
1060                         else
1061                             m_stop_others = true;
1062                     }
1063                 }
1064                 break;
1065                 default:
1066                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1067                     break;
1068             }
1069             return error;
1070         }
1071 
1072         void
1073         OptionParsingStarting () override
1074         {
1075             m_thread_idx = LLDB_INVALID_THREAD_ID;
1076             m_frame_idx = 0;
1077             m_stop_others = false;
1078             m_until_addrs.clear();
1079         }
1080 
1081         const OptionDefinition*
1082         GetDefinitions () override
1083         {
1084             return g_option_table;
1085         }
1086 
1087         uint32_t m_step_thread_idx;
1088         bool m_stop_others;
1089         std::vector<lldb::addr_t> m_until_addrs;
1090 
1091         // Options table: Required for subclasses of Options.
1092 
1093         static OptionDefinition g_option_table[];
1094 
1095         // Instance variables to hold the values for command options.
1096     };
1097 
1098     CommandObjectThreadUntil(CommandInterpreter &interpreter)
1099         : CommandObjectParsed(interpreter, "thread until", "Continue until a line number or address is reached by the "
1100                                                            "current or specified thread.  Stops when returning from "
1101                                                            "the current function as a safety measure.",
1102                               nullptr, eCommandRequiresThread | eCommandTryTargetAPILock |
1103                                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1104           m_options(interpreter)
1105     {
1106         CommandArgumentEntry arg;
1107         CommandArgumentData line_num_arg;
1108 
1109         // Define the first (and only) variant of this arg.
1110         line_num_arg.arg_type = eArgTypeLineNum;
1111         line_num_arg.arg_repetition = eArgRepeatPlain;
1112 
1113         // There is only one variant this argument could be; put it into the argument entry.
1114         arg.push_back (line_num_arg);
1115 
1116         // Push the data for the first argument into the m_arguments vector.
1117         m_arguments.push_back (arg);
1118     }
1119 
1120     ~CommandObjectThreadUntil() override = default;
1121 
1122     Options *
1123     GetOptions () override
1124     {
1125         return &m_options;
1126     }
1127 
1128 protected:
1129     bool
1130     DoExecute (Args& command, CommandReturnObject &result) override
1131     {
1132         bool synchronous_execution = m_interpreter.GetSynchronous ();
1133 
1134         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1135         if (target == nullptr)
1136         {
1137             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1138             result.SetStatus (eReturnStatusFailed);
1139             return false;
1140         }
1141 
1142         Process *process = m_exe_ctx.GetProcessPtr();
1143         if (process == nullptr)
1144         {
1145             result.AppendError ("need a valid process to step");
1146             result.SetStatus (eReturnStatusFailed);
1147         }
1148         else
1149         {
1150             Thread *thread = nullptr;
1151             std::vector<uint32_t> line_numbers;
1152 
1153             if (command.GetArgumentCount() >= 1)
1154             {
1155                 size_t num_args = command.GetArgumentCount();
1156                 for (size_t i = 0; i < num_args; i++)
1157                 {
1158                     uint32_t line_number;
1159                     line_number = StringConvert::ToUInt32 (command.GetArgumentAtIndex(0), UINT32_MAX);
1160                     if (line_number == UINT32_MAX)
1161                     {
1162                         result.AppendErrorWithFormat ("invalid line number: '%s'.\n", command.GetArgumentAtIndex(0));
1163                         result.SetStatus (eReturnStatusFailed);
1164                         return false;
1165                     }
1166                     else
1167                         line_numbers.push_back(line_number);
1168                 }
1169             }
1170             else if (m_options.m_until_addrs.empty())
1171             {
1172                 result.AppendErrorWithFormat ("No line number or address provided:\n%s", GetSyntax());
1173                 result.SetStatus (eReturnStatusFailed);
1174                 return false;
1175             }
1176 
1177             if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID)
1178             {
1179                 thread = GetDefaultThread();
1180             }
1181             else
1182             {
1183                 thread = process->GetThreadList().FindThreadByIndexID(m_options.m_thread_idx).get();
1184             }
1185 
1186             if (thread == nullptr)
1187             {
1188                 const uint32_t num_threads = process->GetThreadList().GetSize();
1189                 result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n",
1190                                               m_options.m_thread_idx,
1191                                               num_threads);
1192                 result.SetStatus (eReturnStatusFailed);
1193                 return false;
1194             }
1195 
1196             const bool abort_other_plans = false;
1197 
1198             StackFrame *frame = thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1199             if (frame == nullptr)
1200             {
1201                 result.AppendErrorWithFormat ("Frame index %u is out of range for thread %u.\n",
1202                                               m_options.m_frame_idx,
1203                                               m_options.m_thread_idx);
1204                 result.SetStatus (eReturnStatusFailed);
1205                 return false;
1206             }
1207 
1208             ThreadPlanSP new_plan_sp;
1209 
1210             if (frame->HasDebugInformation ())
1211             {
1212                 // Finally we got here...  Translate the given line number to a bunch of addresses:
1213                 SymbolContext sc(frame->GetSymbolContext (eSymbolContextCompUnit));
1214                 LineTable *line_table = nullptr;
1215                 if (sc.comp_unit)
1216                     line_table = sc.comp_unit->GetLineTable();
1217 
1218                 if (line_table == nullptr)
1219                 {
1220                     result.AppendErrorWithFormat ("Failed to resolve the line table for frame %u of thread index %u.\n",
1221                                                  m_options.m_frame_idx, m_options.m_thread_idx);
1222                     result.SetStatus (eReturnStatusFailed);
1223                     return false;
1224                 }
1225 
1226                 LineEntry function_start;
1227                 uint32_t index_ptr = 0, end_ptr;
1228                 std::vector<addr_t> address_list;
1229 
1230                 // Find the beginning & end index of the
1231                 AddressRange fun_addr_range = sc.function->GetAddressRange();
1232                 Address fun_start_addr = fun_addr_range.GetBaseAddress();
1233                 line_table->FindLineEntryByAddress (fun_start_addr, function_start, &index_ptr);
1234 
1235                 Address fun_end_addr(fun_start_addr.GetSection(),
1236                                      fun_start_addr.GetOffset() + fun_addr_range.GetByteSize());
1237 
1238                 bool all_in_function = true;
1239 
1240                 line_table->FindLineEntryByAddress (fun_end_addr, function_start, &end_ptr);
1241 
1242                 for (uint32_t line_number : line_numbers)
1243                 {
1244                     uint32_t start_idx_ptr = index_ptr;
1245                     while (start_idx_ptr <= end_ptr)
1246                     {
1247                         LineEntry line_entry;
1248                         const bool exact = false;
1249                         start_idx_ptr = sc.comp_unit->FindLineEntry(start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry);
1250                         if (start_idx_ptr == UINT32_MAX)
1251                             break;
1252 
1253                         addr_t address = line_entry.range.GetBaseAddress().GetLoadAddress(target);
1254                         if (address != LLDB_INVALID_ADDRESS)
1255                         {
1256                             if (fun_addr_range.ContainsLoadAddress (address, target))
1257                                 address_list.push_back (address);
1258                             else
1259                                 all_in_function = false;
1260                         }
1261                         start_idx_ptr++;
1262                     }
1263                 }
1264 
1265                 for (lldb::addr_t address : m_options.m_until_addrs)
1266                 {
1267                     if (fun_addr_range.ContainsLoadAddress (address, target))
1268                         address_list.push_back (address);
1269                     else
1270                         all_in_function = false;
1271                 }
1272 
1273                 if (address_list.empty())
1274                 {
1275                     if (all_in_function)
1276                         result.AppendErrorWithFormat ("No line entries matching until target.\n");
1277                     else
1278                         result.AppendErrorWithFormat ("Until target outside of the current function.\n");
1279 
1280                     result.SetStatus (eReturnStatusFailed);
1281                     return false;
1282                 }
1283 
1284                 new_plan_sp = thread->QueueThreadPlanForStepUntil (abort_other_plans,
1285                                                                 &address_list.front(),
1286                                                                 address_list.size(),
1287                                                                 m_options.m_stop_others,
1288                                                                 m_options.m_frame_idx);
1289                 // User level plans should be master plans so they can be interrupted (e.g. by hitting a breakpoint)
1290                 // and other plans executed by the user (stepping around the breakpoint) and then a "continue"
1291                 // will resume the original plan.
1292                 new_plan_sp->SetIsMasterPlan (true);
1293                 new_plan_sp->SetOkayToDiscard(false);
1294             }
1295             else
1296             {
1297                 result.AppendErrorWithFormat ("Frame index %u of thread %u has no debug information.\n",
1298                                               m_options.m_frame_idx,
1299                                               m_options.m_thread_idx);
1300                 result.SetStatus (eReturnStatusFailed);
1301                 return false;
1302             }
1303 
1304             process->GetThreadList().SetSelectedThreadByID (m_options.m_thread_idx);
1305 
1306             StreamString stream;
1307             Error error;
1308             if (synchronous_execution)
1309                 error = process->ResumeSynchronous (&stream);
1310             else
1311                 error = process->Resume ();
1312 
1313             if (error.Success())
1314             {
1315                 result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID());
1316                 if (synchronous_execution)
1317                 {
1318                     // If any state changed events had anything to say, add that to the result
1319                     if (stream.GetData())
1320                         result.AppendMessage(stream.GetData());
1321 
1322                     result.SetDidChangeProcessState (true);
1323                     result.SetStatus (eReturnStatusSuccessFinishNoResult);
1324                 }
1325                 else
1326                 {
1327                     result.SetStatus (eReturnStatusSuccessContinuingNoResult);
1328                 }
1329             }
1330             else
1331             {
1332                 result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString());
1333                 result.SetStatus (eReturnStatusFailed);
1334             }
1335 
1336         }
1337         return result.Succeeded();
1338     }
1339 
1340     CommandOptions m_options;
1341 };
1342 
1343 OptionDefinition
1344 CommandObjectThreadUntil::CommandOptions::g_option_table[] =
1345 {
1346 { LLDB_OPT_SET_1, false, "frame",   'f', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeFrameIndex,   "Frame index for until operation - defaults to 0"},
1347 { LLDB_OPT_SET_1, false, "thread",  't', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeThreadIndex,  "Thread index for the thread for until operation"},
1348 { LLDB_OPT_SET_1, false, "run-mode",'m', OptionParser::eRequiredArgument, nullptr, g_duo_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping this one"},
1349 { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeAddressOrExpression, "Run until we reach the specified address, or leave the function - can be specified multiple times."},
1350 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1351 };
1352 
1353 //-------------------------------------------------------------------------
1354 // CommandObjectThreadSelect
1355 //-------------------------------------------------------------------------
1356 
1357 class CommandObjectThreadSelect : public CommandObjectParsed
1358 {
1359 public:
1360     CommandObjectThreadSelect(CommandInterpreter &interpreter)
1361         : CommandObjectParsed(interpreter, "thread select", "Change the currently selected thread.", nullptr,
1362                               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1363                                   eCommandProcessMustBePaused)
1364     {
1365         CommandArgumentEntry arg;
1366         CommandArgumentData thread_idx_arg;
1367 
1368         // Define the first (and only) variant of this arg.
1369         thread_idx_arg.arg_type = eArgTypeThreadIndex;
1370         thread_idx_arg.arg_repetition = eArgRepeatPlain;
1371 
1372         // There is only one variant this argument could be; put it into the argument entry.
1373         arg.push_back (thread_idx_arg);
1374 
1375         // Push the data for the first argument into the m_arguments vector.
1376         m_arguments.push_back (arg);
1377     }
1378 
1379     ~CommandObjectThreadSelect() override = default;
1380 
1381 protected:
1382     bool
1383     DoExecute (Args& command, CommandReturnObject &result) override
1384     {
1385         Process *process = m_exe_ctx.GetProcessPtr();
1386         if (process == nullptr)
1387         {
1388             result.AppendError ("no process");
1389             result.SetStatus (eReturnStatusFailed);
1390             return false;
1391         }
1392         else if (command.GetArgumentCount() != 1)
1393         {
1394             result.AppendErrorWithFormat("'%s' takes exactly one thread index argument:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str());
1395             result.SetStatus (eReturnStatusFailed);
1396             return false;
1397         }
1398 
1399         uint32_t index_id = StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0);
1400 
1401         Thread *new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get();
1402         if (new_thread == nullptr)
1403         {
1404             result.AppendErrorWithFormat ("invalid thread #%s.\n", command.GetArgumentAtIndex(0));
1405             result.SetStatus (eReturnStatusFailed);
1406             return false;
1407         }
1408 
1409         process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1410         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1411 
1412         return result.Succeeded();
1413     }
1414 };
1415 
1416 //-------------------------------------------------------------------------
1417 // CommandObjectThreadList
1418 //-------------------------------------------------------------------------
1419 
1420 class CommandObjectThreadList : public CommandObjectParsed
1421 {
1422 public:
1423     CommandObjectThreadList(CommandInterpreter &interpreter)
1424         : CommandObjectParsed(interpreter, "thread list",
1425                               "Show a summary of each thread in the current target process.", "thread list",
1426                               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1427                                   eCommandProcessMustBePaused)
1428     {
1429     }
1430 
1431     ~CommandObjectThreadList() override = default;
1432 
1433 protected:
1434     bool
1435     DoExecute (Args& command, CommandReturnObject &result) override
1436     {
1437         Stream &strm = result.GetOutputStream();
1438         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1439         Process *process = m_exe_ctx.GetProcessPtr();
1440         const bool only_threads_with_stop_reason = false;
1441         const uint32_t start_frame = 0;
1442         const uint32_t num_frames = 0;
1443         const uint32_t num_frames_with_source = 0;
1444         process->GetStatus(strm);
1445         process->GetThreadStatus (strm,
1446                                   only_threads_with_stop_reason,
1447                                   start_frame,
1448                                   num_frames,
1449                                   num_frames_with_source);
1450         return result.Succeeded();
1451     }
1452 };
1453 
1454 //-------------------------------------------------------------------------
1455 // CommandObjectThreadInfo
1456 //-------------------------------------------------------------------------
1457 
1458 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads
1459 {
1460 public:
1461     class CommandOptions : public Options
1462     {
1463     public:
1464         CommandOptions (CommandInterpreter &interpreter) :
1465             Options (interpreter)
1466         {
1467             OptionParsingStarting ();
1468         }
1469 
1470         ~CommandOptions() override = default;
1471 
1472         void
1473         OptionParsingStarting () override
1474         {
1475             m_json_thread = false;
1476             m_json_stopinfo = false;
1477         }
1478 
1479         Error
1480         SetOptionValue (uint32_t option_idx, const char *option_arg) override
1481         {
1482             const int short_option = m_getopt_table[option_idx].val;
1483             Error error;
1484 
1485             switch (short_option)
1486             {
1487                 case 'j':
1488                     m_json_thread = true;
1489                     break;
1490 
1491                 case 's':
1492                     m_json_stopinfo = true;
1493                     break;
1494 
1495                 default:
1496                     return Error("invalid short option character '%c'", short_option);
1497             }
1498             return error;
1499         }
1500 
1501         const OptionDefinition*
1502         GetDefinitions () override
1503         {
1504             return g_option_table;
1505         }
1506 
1507         bool m_json_thread;
1508         bool m_json_stopinfo;
1509 
1510         static OptionDefinition g_option_table[];
1511     };
1512 
1513     CommandObjectThreadInfo(CommandInterpreter &interpreter)
1514         : CommandObjectIterateOverThreads(
1515               interpreter, "thread info",
1516               "Show an extended summary of one or more threads.  Defaults to the current thread.", "thread info",
1517               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1518                   eCommandProcessMustBePaused),
1519           m_options(interpreter)
1520     {
1521         m_add_return = false;
1522     }
1523 
1524     ~CommandObjectThreadInfo() override = default;
1525 
1526     Options *
1527     GetOptions () override
1528     {
1529         return &m_options;
1530     }
1531 
1532     bool
1533     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
1534     {
1535         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1536         if (!thread_sp)
1537         {
1538             result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid);
1539             result.SetStatus (eReturnStatusFailed);
1540             return false;
1541         }
1542 
1543         Thread *thread = thread_sp.get();
1544 
1545         Stream &strm = result.GetOutputStream();
1546         if (!thread->GetDescription (strm, eDescriptionLevelFull, m_options.m_json_thread, m_options.m_json_stopinfo))
1547         {
1548             result.AppendErrorWithFormat ("error displaying info for thread: \"%d\"\n", thread->GetIndexID());
1549             result.SetStatus (eReturnStatusFailed);
1550             return false;
1551         }
1552         return true;
1553     }
1554 
1555     CommandOptions m_options;
1556 };
1557 
1558 OptionDefinition
1559 CommandObjectThreadInfo::CommandOptions::g_option_table[] =
1560 {
1561     { LLDB_OPT_SET_ALL, false, "json",'j', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the thread info in JSON format."},
1562     { LLDB_OPT_SET_ALL, false, "stop-info",'s', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the extended stop info in JSON format."},
1563 
1564     { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1565 };
1566 
1567 //-------------------------------------------------------------------------
1568 // CommandObjectThreadReturn
1569 //-------------------------------------------------------------------------
1570 
1571 class CommandObjectThreadReturn : public CommandObjectRaw
1572 {
1573 public:
1574     class CommandOptions : public Options
1575     {
1576     public:
1577         CommandOptions (CommandInterpreter &interpreter) :
1578             Options (interpreter),
1579             m_from_expression (false)
1580         {
1581             // Keep default values of all options in one place: OptionParsingStarting ()
1582             OptionParsingStarting ();
1583         }
1584 
1585         ~CommandOptions() override = default;
1586 
1587         Error
1588         SetOptionValue (uint32_t option_idx, const char *option_arg) override
1589         {
1590             Error error;
1591             const int short_option = m_getopt_table[option_idx].val;
1592 
1593             switch (short_option)
1594             {
1595                 case 'x':
1596                 {
1597                     bool success;
1598                     bool tmp_value = Args::StringToBoolean (option_arg, false, &success);
1599                     if (success)
1600                         m_from_expression = tmp_value;
1601                     else
1602                     {
1603                         error.SetErrorStringWithFormat ("invalid boolean value '%s' for 'x' option", option_arg);
1604                     }
1605                 }
1606                 break;
1607                 default:
1608                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1609                     break;
1610             }
1611             return error;
1612         }
1613 
1614         void
1615         OptionParsingStarting () override
1616         {
1617             m_from_expression = false;
1618         }
1619 
1620         const OptionDefinition*
1621         GetDefinitions () override
1622         {
1623             return g_option_table;
1624         }
1625 
1626         bool m_from_expression;
1627 
1628         // Options table: Required for subclasses of Options.
1629 
1630         static OptionDefinition g_option_table[];
1631 
1632         // Instance variables to hold the values for command options.
1633     };
1634 
1635     CommandObjectThreadReturn(CommandInterpreter &interpreter)
1636         : CommandObjectRaw(interpreter, "thread return",
1637                            "Prematurely return from a stack frame, short-circuiting execution of newer frames "
1638                            "and optionally yielding a specified value.  Defaults to the exiting the current stack "
1639                            "frame.",
1640                            "thread return", eCommandRequiresFrame | eCommandTryTargetAPILock |
1641                                                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1642           m_options(interpreter)
1643     {
1644         CommandArgumentEntry arg;
1645         CommandArgumentData expression_arg;
1646 
1647         // Define the first (and only) variant of this arg.
1648         expression_arg.arg_type = eArgTypeExpression;
1649         expression_arg.arg_repetition = eArgRepeatOptional;
1650 
1651         // There is only one variant this argument could be; put it into the argument entry.
1652         arg.push_back (expression_arg);
1653 
1654         // Push the data for the first argument into the m_arguments vector.
1655         m_arguments.push_back (arg);
1656     }
1657 
1658     ~CommandObjectThreadReturn() override = default;
1659 
1660     Options *
1661     GetOptions() override
1662     {
1663         return &m_options;
1664     }
1665 
1666 protected:
1667     bool
1668     DoExecute (const char *command, CommandReturnObject &result) override
1669     {
1670         // I am going to handle this by hand, because I don't want you to have to say:
1671         // "thread return -- -5".
1672         if (command[0] == '-' && command[1] == 'x')
1673         {
1674             if (command && command[2] != '\0')
1675                 result.AppendWarning("Return values ignored when returning from user called expressions");
1676 
1677             Thread *thread = m_exe_ctx.GetThreadPtr();
1678             Error error;
1679             error = thread->UnwindInnermostExpression();
1680             if (!error.Success())
1681             {
1682                 result.AppendErrorWithFormat ("Unwinding expression failed - %s.", error.AsCString());
1683                 result.SetStatus (eReturnStatusFailed);
1684             }
1685             else
1686             {
1687                 bool success = thread->SetSelectedFrameByIndexNoisily (0, result.GetOutputStream());
1688                 if (success)
1689                 {
1690                     m_exe_ctx.SetFrameSP(thread->GetSelectedFrame ());
1691                     result.SetStatus (eReturnStatusSuccessFinishResult);
1692                 }
1693                 else
1694                 {
1695                     result.AppendErrorWithFormat ("Could not select 0th frame after unwinding expression.");
1696                     result.SetStatus (eReturnStatusFailed);
1697                 }
1698             }
1699             return result.Succeeded();
1700         }
1701 
1702         ValueObjectSP return_valobj_sp;
1703 
1704         StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1705         uint32_t frame_idx = frame_sp->GetFrameIndex();
1706 
1707         if (frame_sp->IsInlined())
1708         {
1709             result.AppendError("Don't know how to return from inlined frames.");
1710             result.SetStatus (eReturnStatusFailed);
1711             return false;
1712         }
1713 
1714         if (command && command[0] != '\0')
1715         {
1716             Target *target = m_exe_ctx.GetTargetPtr();
1717             EvaluateExpressionOptions options;
1718 
1719             options.SetUnwindOnError(true);
1720             options.SetUseDynamic(eNoDynamicValues);
1721 
1722             ExpressionResults exe_results = eExpressionSetupError;
1723             exe_results = target->EvaluateExpression (command,
1724                                                       frame_sp.get(),
1725                                                       return_valobj_sp,
1726                                                       options);
1727             if (exe_results != eExpressionCompleted)
1728             {
1729                 if (return_valobj_sp)
1730                     result.AppendErrorWithFormat("Error evaluating result expression: %s", return_valobj_sp->GetError().AsCString());
1731                 else
1732                     result.AppendErrorWithFormat("Unknown error evaluating result expression.");
1733                 result.SetStatus (eReturnStatusFailed);
1734                 return false;
1735             }
1736         }
1737 
1738         Error error;
1739         ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1740         const bool broadcast = true;
1741         error = thread_sp->ReturnFromFrame (frame_sp, return_valobj_sp, broadcast);
1742         if (!error.Success())
1743         {
1744             result.AppendErrorWithFormat("Error returning from frame %d of thread %d: %s.", frame_idx, thread_sp->GetIndexID(), error.AsCString());
1745             result.SetStatus (eReturnStatusFailed);
1746             return false;
1747         }
1748 
1749         result.SetStatus (eReturnStatusSuccessFinishResult);
1750         return true;
1751     }
1752 
1753     CommandOptions m_options;
1754 };
1755 
1756 OptionDefinition
1757 CommandObjectThreadReturn::CommandOptions::g_option_table[] =
1758 {
1759 { LLDB_OPT_SET_ALL, false, "from-expression",  'x', OptionParser::eNoArgument, nullptr, nullptr,               0, eArgTypeNone,     "Return from the innermost expression evaluation."},
1760 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1761 };
1762 
1763 //-------------------------------------------------------------------------
1764 // CommandObjectThreadJump
1765 //-------------------------------------------------------------------------
1766 
1767 class CommandObjectThreadJump : public CommandObjectParsed
1768 {
1769 public:
1770     class CommandOptions : public Options
1771     {
1772     public:
1773         CommandOptions (CommandInterpreter &interpreter) :
1774             Options (interpreter)
1775         {
1776             OptionParsingStarting ();
1777         }
1778 
1779         ~CommandOptions() override = default;
1780 
1781         void
1782         OptionParsingStarting () override
1783         {
1784             m_filenames.Clear();
1785             m_line_num = 0;
1786             m_line_offset = 0;
1787             m_load_addr = LLDB_INVALID_ADDRESS;
1788             m_force = false;
1789         }
1790 
1791         Error
1792         SetOptionValue (uint32_t option_idx, const char *option_arg) override
1793         {
1794             bool success;
1795             const int short_option = m_getopt_table[option_idx].val;
1796             Error error;
1797 
1798             switch (short_option)
1799             {
1800                 case 'f':
1801                     m_filenames.AppendIfUnique (FileSpec(option_arg, false));
1802                     if (m_filenames.GetSize() > 1)
1803                         return Error("only one source file expected.");
1804                     break;
1805                 case 'l':
1806                     m_line_num = StringConvert::ToUInt32 (option_arg, 0, 0, &success);
1807                     if (!success || m_line_num == 0)
1808                         return Error("invalid line number: '%s'.", option_arg);
1809                     break;
1810                 case 'b':
1811                     m_line_offset = StringConvert::ToSInt32 (option_arg, 0, 0, &success);
1812                     if (!success)
1813                         return Error("invalid line offset: '%s'.", option_arg);
1814                     break;
1815                 case 'a':
1816                     {
1817                         ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
1818                         m_load_addr = Args::StringToAddress(&exe_ctx, option_arg, LLDB_INVALID_ADDRESS, &error);
1819                     }
1820                     break;
1821                 case 'r':
1822                     m_force = true;
1823                     break;
1824                  default:
1825                     return Error("invalid short option character '%c'", short_option);
1826             }
1827             return error;
1828         }
1829 
1830         const OptionDefinition*
1831         GetDefinitions () override
1832         {
1833             return g_option_table;
1834         }
1835 
1836         FileSpecList m_filenames;
1837         uint32_t m_line_num;
1838         int32_t m_line_offset;
1839         lldb::addr_t m_load_addr;
1840         bool m_force;
1841 
1842         static OptionDefinition g_option_table[];
1843     };
1844 
1845     CommandObjectThreadJump (CommandInterpreter &interpreter) :
1846         CommandObjectParsed (interpreter,
1847                           "thread jump",
1848                           "Sets the program counter to a new address.",
1849                           "thread jump",
1850                           eCommandRequiresFrame         |
1851                           eCommandTryTargetAPILock      |
1852                           eCommandProcessMustBeLaunched |
1853                           eCommandProcessMustBePaused   ),
1854         m_options (interpreter)
1855     {
1856     }
1857 
1858     ~CommandObjectThreadJump() override = default;
1859 
1860     Options *
1861     GetOptions() override
1862     {
1863         return &m_options;
1864     }
1865 
1866 protected:
1867     bool DoExecute (Args& args, CommandReturnObject &result) override
1868     {
1869         RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1870         StackFrame *frame = m_exe_ctx.GetFramePtr();
1871         Thread *thread = m_exe_ctx.GetThreadPtr();
1872         Target *target = m_exe_ctx.GetTargetPtr();
1873         const SymbolContext &sym_ctx = frame->GetSymbolContext (eSymbolContextLineEntry);
1874 
1875         if (m_options.m_load_addr != LLDB_INVALID_ADDRESS)
1876         {
1877             // Use this address directly.
1878             Address dest = Address(m_options.m_load_addr);
1879 
1880             lldb::addr_t callAddr = dest.GetCallableLoadAddress (target);
1881             if (callAddr == LLDB_INVALID_ADDRESS)
1882             {
1883                 result.AppendErrorWithFormat ("Invalid destination address.");
1884                 result.SetStatus (eReturnStatusFailed);
1885                 return false;
1886             }
1887 
1888             if (!reg_ctx->SetPC (callAddr))
1889             {
1890                 result.AppendErrorWithFormat ("Error changing PC value for thread %d.", thread->GetIndexID());
1891                 result.SetStatus (eReturnStatusFailed);
1892                 return false;
1893             }
1894         }
1895         else
1896         {
1897             // Pick either the absolute line, or work out a relative one.
1898             int32_t line = (int32_t)m_options.m_line_num;
1899             if (line == 0)
1900                 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1901 
1902             // Try the current file, but override if asked.
1903             FileSpec file = sym_ctx.line_entry.file;
1904             if (m_options.m_filenames.GetSize() == 1)
1905                 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1906 
1907             if (!file)
1908             {
1909                 result.AppendErrorWithFormat ("No source file available for the current location.");
1910                 result.SetStatus (eReturnStatusFailed);
1911                 return false;
1912             }
1913 
1914             std::string warnings;
1915             Error err = thread->JumpToLine (file, line, m_options.m_force, &warnings);
1916 
1917             if (err.Fail())
1918             {
1919                 result.SetError (err);
1920                 return false;
1921             }
1922 
1923             if (!warnings.empty())
1924                 result.AppendWarning (warnings.c_str());
1925         }
1926 
1927         result.SetStatus (eReturnStatusSuccessFinishResult);
1928         return true;
1929     }
1930 
1931     CommandOptions m_options;
1932 };
1933 
1934 OptionDefinition
1935 CommandObjectThreadJump::CommandOptions::g_option_table[] =
1936 {
1937     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,
1938         "Specifies the source file to jump to."},
1939 
1940     { LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum,
1941         "Specifies the line number to jump to."},
1942 
1943     { LLDB_OPT_SET_2, true, "by", 'b', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset,
1944         "Jumps by a relative line offset from the current line."},
1945 
1946     { LLDB_OPT_SET_3, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression,
1947         "Jumps to a specific address."},
1948 
1949     { LLDB_OPT_SET_1|
1950       LLDB_OPT_SET_2|
1951       LLDB_OPT_SET_3, false, "force",'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone,"Allows the PC to leave the current function."},
1952 
1953     { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1954 };
1955 
1956 //-------------------------------------------------------------------------
1957 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1958 //-------------------------------------------------------------------------
1959 
1960 //-------------------------------------------------------------------------
1961 // CommandObjectThreadPlanList
1962 //-------------------------------------------------------------------------
1963 
1964 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads
1965 {
1966 public:
1967     class CommandOptions : public Options
1968     {
1969     public:
1970         CommandOptions (CommandInterpreter &interpreter) :
1971             Options(interpreter)
1972         {
1973             // Keep default values of all options in one place: OptionParsingStarting ()
1974             OptionParsingStarting ();
1975         }
1976 
1977         ~CommandOptions() override = default;
1978 
1979         Error
1980         SetOptionValue (uint32_t option_idx, const char *option_arg) override
1981         {
1982             Error error;
1983             const int short_option = m_getopt_table[option_idx].val;
1984 
1985             switch (short_option)
1986             {
1987                 case 'i':
1988                     m_internal = true;
1989                     break;
1990                 case 'v':
1991                     m_verbose = true;
1992                     break;
1993                 default:
1994                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1995                     break;
1996             }
1997             return error;
1998         }
1999 
2000         void
2001         OptionParsingStarting () override
2002         {
2003             m_verbose = false;
2004             m_internal = false;
2005         }
2006 
2007         const OptionDefinition*
2008         GetDefinitions () override
2009         {
2010             return g_option_table;
2011         }
2012 
2013         // Options table: Required for subclasses of Options.
2014 
2015         static OptionDefinition g_option_table[];
2016 
2017         // Instance variables to hold the values for command options.
2018         bool m_verbose;
2019         bool m_internal;
2020     };
2021 
2022     CommandObjectThreadPlanList(CommandInterpreter &interpreter)
2023         : CommandObjectIterateOverThreads(
2024               interpreter, "thread plan list",
2025               "Show thread plans for one or more threads.  If no threads are specified, show the "
2026               "current thread.  Use the thread-index \"all\" to see all threads.",
2027               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
2028                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
2029           m_options(interpreter)
2030     {
2031     }
2032 
2033     ~CommandObjectThreadPlanList() override = default;
2034 
2035     Options *
2036     GetOptions () override
2037     {
2038         return &m_options;
2039     }
2040 
2041 protected:
2042     bool
2043     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
2044     {
2045         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2046         if (!thread_sp)
2047         {
2048             result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid);
2049             result.SetStatus (eReturnStatusFailed);
2050             return false;
2051         }
2052 
2053         Thread *thread = thread_sp.get();
2054 
2055         Stream &strm = result.GetOutputStream();
2056         DescriptionLevel desc_level = eDescriptionLevelFull;
2057         if (m_options.m_verbose)
2058             desc_level = eDescriptionLevelVerbose;
2059 
2060         thread->DumpThreadPlans (&strm, desc_level, m_options.m_internal, true);
2061         return true;
2062     }
2063 
2064     CommandOptions m_options;
2065 };
2066 
2067 OptionDefinition
2068 CommandObjectThreadPlanList::CommandOptions::g_option_table[] =
2069 {
2070 { LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display more information about the thread plans"},
2071 { LLDB_OPT_SET_1, false, "internal", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display internal as well as user thread plans"},
2072 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
2073 };
2074 
2075 class CommandObjectThreadPlanDiscard : public CommandObjectParsed
2076 {
2077 public:
2078     CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
2079         : CommandObjectParsed(
2080               interpreter, "thread plan discard",
2081               "Discards thread plans up to and including the specified index (see 'thread plan list'.)  "
2082               "Only user visible plans can be discarded.",
2083               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
2084                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
2085     {
2086         CommandArgumentEntry arg;
2087         CommandArgumentData plan_index_arg;
2088 
2089         // Define the first (and only) variant of this arg.
2090         plan_index_arg.arg_type = eArgTypeUnsignedInteger;
2091         plan_index_arg.arg_repetition = eArgRepeatPlain;
2092 
2093         // There is only one variant this argument could be; put it into the argument entry.
2094         arg.push_back (plan_index_arg);
2095 
2096         // Push the data for the first argument into the m_arguments vector.
2097         m_arguments.push_back (arg);
2098     }
2099 
2100     ~CommandObjectThreadPlanDiscard() override = default;
2101 
2102     bool
2103     DoExecute (Args& args, CommandReturnObject &result) override
2104     {
2105         Thread *thread = m_exe_ctx.GetThreadPtr();
2106         if (args.GetArgumentCount() != 1)
2107         {
2108             result.AppendErrorWithFormat("Too many arguments, expected one - the thread plan index - but got %zu.",
2109                                          args.GetArgumentCount());
2110             result.SetStatus (eReturnStatusFailed);
2111             return false;
2112         }
2113 
2114         bool success;
2115         uint32_t thread_plan_idx = StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success);
2116         if (!success)
2117         {
2118             result.AppendErrorWithFormat("Invalid thread index: \"%s\" - should be unsigned int.",
2119                                          args.GetArgumentAtIndex(0));
2120             result.SetStatus (eReturnStatusFailed);
2121             return false;
2122         }
2123 
2124         if (thread_plan_idx == 0)
2125         {
2126             result.AppendErrorWithFormat("You wouldn't really want me to discard the base thread plan.");
2127             result.SetStatus (eReturnStatusFailed);
2128             return false;
2129         }
2130 
2131         if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx))
2132         {
2133             result.SetStatus(eReturnStatusSuccessFinishNoResult);
2134             return true;
2135         }
2136         else
2137         {
2138             result.AppendErrorWithFormat("Could not find User thread plan with index %s.",
2139                                          args.GetArgumentAtIndex(0));
2140             result.SetStatus (eReturnStatusFailed);
2141             return false;
2142         }
2143     }
2144 };
2145 
2146 //-------------------------------------------------------------------------
2147 // CommandObjectMultiwordThreadPlan
2148 //-------------------------------------------------------------------------
2149 
2150 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword
2151 {
2152 public:
2153     CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
2154         : CommandObjectMultiword(interpreter, "plan", "Commands for managing thread plans that control execution.",
2155                                  "thread plan <subcommand> [<subcommand objects]")
2156     {
2157         LoadSubCommand ("list", CommandObjectSP (new CommandObjectThreadPlanList (interpreter)));
2158         LoadSubCommand ("discard", CommandObjectSP (new CommandObjectThreadPlanDiscard (interpreter)));
2159     }
2160 
2161     ~CommandObjectMultiwordThreadPlan() override = default;
2162 };
2163 
2164 //-------------------------------------------------------------------------
2165 // CommandObjectMultiwordThread
2166 //-------------------------------------------------------------------------
2167 
2168 CommandObjectMultiwordThread::CommandObjectMultiwordThread(CommandInterpreter &interpreter)
2169     : CommandObjectMultiword(interpreter, "thread",
2170                              "Commands for operating on one or more threads in the current process.",
2171                              "thread <subcommand> [<subcommand-options>]")
2172 {
2173     LoadSubCommand ("backtrace",  CommandObjectSP (new CommandObjectThreadBacktrace (interpreter)));
2174     LoadSubCommand ("continue",   CommandObjectSP (new CommandObjectThreadContinue (interpreter)));
2175     LoadSubCommand ("list",       CommandObjectSP (new CommandObjectThreadList (interpreter)));
2176     LoadSubCommand ("return",     CommandObjectSP (new CommandObjectThreadReturn (interpreter)));
2177     LoadSubCommand ("jump",       CommandObjectSP (new CommandObjectThreadJump (interpreter)));
2178     LoadSubCommand ("select",     CommandObjectSP (new CommandObjectThreadSelect (interpreter)));
2179     LoadSubCommand ("until",      CommandObjectSP (new CommandObjectThreadUntil (interpreter)));
2180     LoadSubCommand ("info",       CommandObjectSP (new CommandObjectThreadInfo (interpreter)));
2181     LoadSubCommand("step-in",
2182                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2183                        interpreter, "thread step-in",
2184                        "Source level single step, stepping into calls.  Defaults to current thread unless specified.",
2185                        nullptr, eStepTypeInto, eStepScopeSource)));
2186 
2187     LoadSubCommand("step-out",
2188                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2189                        interpreter, "thread step-out", "Finish executing the current stack frame and stop after "
2190                                                        "returning.  Defaults to current thread unless specified.",
2191                        nullptr, eStepTypeOut, eStepScopeSource)));
2192 
2193     LoadSubCommand("step-over",
2194                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2195                        interpreter, "thread step-over",
2196                        "Source level single step, stepping over calls.  Defaults to current thread unless specified.",
2197                        nullptr, eStepTypeOver, eStepScopeSource)));
2198 
2199     LoadSubCommand(
2200         "step-inst",
2201         CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2202             interpreter, "thread step-inst",
2203             "Instruction level single step, stepping into calls.  Defaults to current thread unless specified.",
2204             nullptr, eStepTypeTrace, eStepScopeInstruction)));
2205 
2206     LoadSubCommand(
2207         "step-inst-over",
2208         CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2209             interpreter, "thread step-inst-over",
2210             "Instruction level single step, stepping over calls.  Defaults to current thread unless specified.",
2211             nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
2212 
2213     LoadSubCommand ("step-scripted", CommandObjectSP (new CommandObjectThreadStepWithTypeAndScope (
2214                                                     interpreter,
2215                                                     "thread step-scripted",
2216                                                     "Step as instructed by the script class passed in the -C option.",
2217                                                     nullptr,
2218                                                     eStepTypeScripted,
2219                                                     eStepScopeSource)));
2220 
2221     LoadSubCommand ("plan", CommandObjectSP (new CommandObjectMultiwordThreadPlan(interpreter)));
2222 }
2223 
2224 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;
2225