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