1 //===-- CommandObjectThread.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectThread.h"
10 
11 #include <memory>
12 #include <optional>
13 #include <sstream>
14 
15 #include "CommandObjectThreadUtil.h"
16 #include "CommandObjectTrace.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/ValueObject.h"
19 #include "lldb/Host/OptionParser.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/CommandOptionArgumentTable.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/OptionArgParser.h"
24 #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h"
25 #include "lldb/Interpreter/Options.h"
26 #include "lldb/Symbol/CompileUnit.h"
27 #include "lldb/Symbol/Function.h"
28 #include "lldb/Symbol/LineEntry.h"
29 #include "lldb/Symbol/LineTable.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/RegisterContext.h"
32 #include "lldb/Target/SystemRuntime.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Target/ThreadPlan.h"
36 #include "lldb/Target/ThreadPlanStepInRange.h"
37 #include "lldb/Target/Trace.h"
38 #include "lldb/Target/TraceDumper.h"
39 #include "lldb/Utility/State.h"
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
44 // CommandObjectThreadBacktrace
45 #define LLDB_OPTIONS_thread_backtrace
46 #include "CommandOptions.inc"
47 
48 class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
49 public:
50   class CommandOptions : public Options {
51   public:
52     CommandOptions() {
53       // Keep default values of all options in one place: OptionParsingStarting
54       // ()
55       OptionParsingStarting(nullptr);
56     }
57 
58     ~CommandOptions() override = default;
59 
60     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
61                           ExecutionContext *execution_context) override {
62       Status error;
63       const int short_option = m_getopt_table[option_idx].val;
64 
65       switch (short_option) {
66       case 'c':
67         if (option_arg.getAsInteger(0, m_count)) {
68           m_count = UINT32_MAX;
69           error.SetErrorStringWithFormat(
70               "invalid integer value for option '%c'", short_option);
71         }
72         break;
73       case 's':
74         if (option_arg.getAsInteger(0, m_start))
75           error.SetErrorStringWithFormat(
76               "invalid integer value for option '%c'", short_option);
77         break;
78       case 'e': {
79         bool success;
80         m_extended_backtrace =
81             OptionArgParser::ToBoolean(option_arg, false, &success);
82         if (!success)
83           error.SetErrorStringWithFormat(
84               "invalid boolean value for option '%c'", short_option);
85       } break;
86       default:
87         llvm_unreachable("Unimplemented option");
88       }
89       return error;
90     }
91 
92     void OptionParsingStarting(ExecutionContext *execution_context) override {
93       m_count = UINT32_MAX;
94       m_start = 0;
95       m_extended_backtrace = false;
96     }
97 
98     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
99       return llvm::ArrayRef(g_thread_backtrace_options);
100     }
101 
102     // Instance variables to hold the values for command options.
103     uint32_t m_count;
104     uint32_t m_start;
105     bool m_extended_backtrace;
106   };
107 
108   CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
109       : CommandObjectIterateOverThreads(
110             interpreter, "thread backtrace",
111             "Show thread call stacks.  Defaults to the current thread, thread "
112             "indexes can be specified as arguments.\n"
113             "Use the thread-index \"all\" to see all threads.\n"
114             "Use the thread-index \"unique\" to see threads grouped by unique "
115             "call stacks.\n"
116             "Use 'settings set frame-format' to customize the printing of "
117             "frames in the backtrace and 'settings set thread-format' to "
118             "customize the thread header.",
119             nullptr,
120             eCommandRequiresProcess | eCommandRequiresThread |
121                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
122                 eCommandProcessMustBePaused) {}
123 
124   ~CommandObjectThreadBacktrace() override = default;
125 
126   Options *GetOptions() override { return &m_options; }
127 
128   std::optional<std::string> GetRepeatCommand(Args &current_args,
129                                               uint32_t idx) override {
130     llvm::StringRef count_opt("--count");
131     llvm::StringRef start_opt("--start");
132 
133     // If no "count" was provided, we are dumping the entire backtrace, so
134     // there isn't a repeat command.  So we search for the count option in
135     // the args, and if we find it, we make a copy and insert or modify the
136     // start option's value to start count indices greater.
137 
138     Args copy_args(current_args);
139     size_t num_entries = copy_args.GetArgumentCount();
140     // These two point at the index of the option value if found.
141     size_t count_idx = 0;
142     size_t start_idx = 0;
143     size_t count_val = 0;
144     size_t start_val = 0;
145 
146     for (size_t idx = 0; idx < num_entries; idx++) {
147       llvm::StringRef arg_string = copy_args[idx].ref();
148       if (arg_string.equals("-c") || count_opt.startswith(arg_string)) {
149         idx++;
150         if (idx == num_entries)
151           return std::nullopt;
152         count_idx = idx;
153         if (copy_args[idx].ref().getAsInteger(0, count_val))
154           return std::nullopt;
155       } else if (arg_string.equals("-s") || start_opt.startswith(arg_string)) {
156         idx++;
157         if (idx == num_entries)
158           return std::nullopt;
159         start_idx = idx;
160         if (copy_args[idx].ref().getAsInteger(0, start_val))
161           return std::nullopt;
162       }
163     }
164     if (count_idx == 0)
165       return std::nullopt;
166 
167     std::string new_start_val = llvm::formatv("{0}", start_val + count_val);
168     if (start_idx == 0) {
169       copy_args.AppendArgument(start_opt);
170       copy_args.AppendArgument(new_start_val);
171     } else {
172       copy_args.ReplaceArgumentAtIndex(start_idx, new_start_val);
173     }
174     std::string repeat_command;
175     if (!copy_args.GetQuotedCommandString(repeat_command))
176       return std::nullopt;
177     return repeat_command;
178   }
179 
180 protected:
181   void DoExtendedBacktrace(Thread *thread, CommandReturnObject &result) {
182     SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime();
183     if (runtime) {
184       Stream &strm = result.GetOutputStream();
185       const std::vector<ConstString> &types =
186           runtime->GetExtendedBacktraceTypes();
187       for (auto type : types) {
188         ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread(
189             thread->shared_from_this(), type);
190         if (ext_thread_sp && ext_thread_sp->IsValid()) {
191           const uint32_t num_frames_with_source = 0;
192           const bool stop_format = false;
193           strm.PutChar('\n');
194           if (ext_thread_sp->GetStatus(strm, m_options.m_start,
195                                        m_options.m_count,
196                                        num_frames_with_source, stop_format)) {
197             DoExtendedBacktrace(ext_thread_sp.get(), result);
198           }
199         }
200       }
201     }
202   }
203 
204   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
205     ThreadSP thread_sp =
206         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
207     if (!thread_sp) {
208       result.AppendErrorWithFormat(
209           "thread disappeared while computing backtraces: 0x%" PRIx64 "\n",
210           tid);
211       return false;
212     }
213 
214     Thread *thread = thread_sp.get();
215 
216     Stream &strm = result.GetOutputStream();
217 
218     // Only dump stack info if we processing unique stacks.
219     const bool only_stacks = m_unique_stacks;
220 
221     // Don't show source context when doing backtraces.
222     const uint32_t num_frames_with_source = 0;
223     const bool stop_format = true;
224     if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count,
225                            num_frames_with_source, stop_format, only_stacks)) {
226       result.AppendErrorWithFormat(
227           "error displaying backtrace for thread: \"0x%4.4x\"\n",
228           thread->GetIndexID());
229       return false;
230     }
231     if (m_options.m_extended_backtrace) {
232       if (!INTERRUPT_REQUESTED(GetDebugger(),
233                               "Interrupt skipped extended backtrace")) {
234         DoExtendedBacktrace(thread, result);
235       }
236     }
237 
238     return true;
239   }
240 
241   CommandOptions m_options;
242 };
243 
244 enum StepScope { eStepScopeSource, eStepScopeInstruction };
245 
246 #define LLDB_OPTIONS_thread_step_scope
247 #include "CommandOptions.inc"
248 
249 class ThreadStepScopeOptionGroup : public OptionGroup {
250 public:
251   ThreadStepScopeOptionGroup() {
252     // Keep default values of all options in one place: OptionParsingStarting
253     // ()
254     OptionParsingStarting(nullptr);
255   }
256 
257   ~ThreadStepScopeOptionGroup() override = default;
258 
259   llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
260     return llvm::ArrayRef(g_thread_step_scope_options);
261   }
262 
263   Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
264                         ExecutionContext *execution_context) override {
265     Status error;
266     const int short_option =
267         g_thread_step_scope_options[option_idx].short_option;
268 
269     switch (short_option) {
270     case 'a': {
271       bool success;
272       bool avoid_no_debug =
273           OptionArgParser::ToBoolean(option_arg, true, &success);
274       if (!success)
275         error.SetErrorStringWithFormat("invalid boolean value for option '%c'",
276                                        short_option);
277       else {
278         m_step_in_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
279       }
280     } break;
281 
282     case 'A': {
283       bool success;
284       bool avoid_no_debug =
285           OptionArgParser::ToBoolean(option_arg, true, &success);
286       if (!success)
287         error.SetErrorStringWithFormat("invalid boolean value for option '%c'",
288                                        short_option);
289       else {
290         m_step_out_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
291       }
292     } break;
293 
294     case 'c':
295       if (option_arg.getAsInteger(0, m_step_count))
296         error.SetErrorStringWithFormat("invalid step count '%s'",
297                                        option_arg.str().c_str());
298       break;
299 
300     case 'm': {
301       auto enum_values = GetDefinitions()[option_idx].enum_values;
302       m_run_mode = (lldb::RunMode)OptionArgParser::ToOptionEnum(
303           option_arg, enum_values, eOnlyDuringStepping, error);
304     } break;
305 
306     case 'e':
307       if (option_arg == "block") {
308         m_end_line_is_block_end = true;
309         break;
310       }
311       if (option_arg.getAsInteger(0, m_end_line))
312         error.SetErrorStringWithFormat("invalid end line number '%s'",
313                                        option_arg.str().c_str());
314       break;
315 
316     case 'r':
317       m_avoid_regexp.clear();
318       m_avoid_regexp.assign(std::string(option_arg));
319       break;
320 
321     case 't':
322       m_step_in_target.clear();
323       m_step_in_target.assign(std::string(option_arg));
324       break;
325 
326     default:
327       llvm_unreachable("Unimplemented option");
328     }
329     return error;
330   }
331 
332   void OptionParsingStarting(ExecutionContext *execution_context) override {
333     m_step_in_avoid_no_debug = eLazyBoolCalculate;
334     m_step_out_avoid_no_debug = eLazyBoolCalculate;
335     m_run_mode = eOnlyDuringStepping;
336 
337     // Check if we are in Non-Stop mode
338     TargetSP target_sp =
339         execution_context ? execution_context->GetTargetSP() : TargetSP();
340     ProcessSP process_sp =
341         execution_context ? execution_context->GetProcessSP() : ProcessSP();
342     if (process_sp && process_sp->GetSteppingRunsAllThreads())
343       m_run_mode = eAllThreads;
344 
345     m_avoid_regexp.clear();
346     m_step_in_target.clear();
347     m_step_count = 1;
348     m_end_line = LLDB_INVALID_LINE_NUMBER;
349     m_end_line_is_block_end = false;
350   }
351 
352   // Instance variables to hold the values for command options.
353   LazyBool m_step_in_avoid_no_debug;
354   LazyBool m_step_out_avoid_no_debug;
355   RunMode m_run_mode;
356   std::string m_avoid_regexp;
357   std::string m_step_in_target;
358   uint32_t m_step_count;
359   uint32_t m_end_line;
360   bool m_end_line_is_block_end;
361 };
362 
363 class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed {
364 public:
365   CommandObjectThreadStepWithTypeAndScope(CommandInterpreter &interpreter,
366                                           const char *name, const char *help,
367                                           const char *syntax,
368                                           StepType step_type,
369                                           StepScope step_scope)
370       : CommandObjectParsed(interpreter, name, help, syntax,
371                             eCommandRequiresProcess | eCommandRequiresThread |
372                                 eCommandTryTargetAPILock |
373                                 eCommandProcessMustBeLaunched |
374                                 eCommandProcessMustBePaused),
375         m_step_type(step_type), m_step_scope(step_scope),
376         m_class_options("scripted step") {
377     CommandArgumentEntry arg;
378     CommandArgumentData thread_id_arg;
379 
380     // Define the first (and only) variant of this arg.
381     thread_id_arg.arg_type = eArgTypeThreadID;
382     thread_id_arg.arg_repetition = eArgRepeatOptional;
383 
384     // There is only one variant this argument could be; put it into the
385     // argument entry.
386     arg.push_back(thread_id_arg);
387 
388     // Push the data for the first argument into the m_arguments vector.
389     m_arguments.push_back(arg);
390 
391     if (step_type == eStepTypeScripted) {
392       m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2,
393                            LLDB_OPT_SET_1);
394     }
395     m_all_options.Append(&m_options);
396     m_all_options.Finalize();
397   }
398 
399   ~CommandObjectThreadStepWithTypeAndScope() override = default;
400 
401   void
402   HandleArgumentCompletion(CompletionRequest &request,
403                            OptionElementVector &opt_element_vector) override {
404     if (request.GetCursorIndex())
405       return;
406 
407     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
408         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
409         nullptr);
410   }
411 
412   Options *GetOptions() override { return &m_all_options; }
413 
414 protected:
415   bool DoExecute(Args &command, CommandReturnObject &result) override {
416     Process *process = m_exe_ctx.GetProcessPtr();
417     bool synchronous_execution = m_interpreter.GetSynchronous();
418 
419     const uint32_t num_threads = process->GetThreadList().GetSize();
420     Thread *thread = nullptr;
421 
422     if (command.GetArgumentCount() == 0) {
423       thread = GetDefaultThread();
424 
425       if (thread == nullptr) {
426         result.AppendError("no selected thread in process");
427         return false;
428       }
429     } else {
430       const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
431       uint32_t step_thread_idx;
432 
433       if (!llvm::to_integer(thread_idx_cstr, step_thread_idx)) {
434         result.AppendErrorWithFormat("invalid thread index '%s'.\n",
435                                      thread_idx_cstr);
436         return false;
437       }
438       thread =
439           process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
440       if (thread == nullptr) {
441         result.AppendErrorWithFormat(
442             "Thread index %u is out of range (valid values are 0 - %u).\n",
443             step_thread_idx, num_threads);
444         return false;
445       }
446     }
447 
448     if (m_step_type == eStepTypeScripted) {
449       if (m_class_options.GetName().empty()) {
450         result.AppendErrorWithFormat("empty class name for scripted step.");
451         return false;
452       } else if (!GetDebugger().GetScriptInterpreter()->CheckObjectExists(
453                      m_class_options.GetName().c_str())) {
454         result.AppendErrorWithFormat(
455             "class for scripted step: \"%s\" does not exist.",
456             m_class_options.GetName().c_str());
457         return false;
458       }
459     }
460 
461     if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER &&
462         m_step_type != eStepTypeInto) {
463       result.AppendErrorWithFormat(
464           "end line option is only valid for step into");
465       return false;
466     }
467 
468     const bool abort_other_plans = false;
469     const lldb::RunMode stop_other_threads = m_options.m_run_mode;
470 
471     // This is a bit unfortunate, but not all the commands in this command
472     // object support only while stepping, so I use the bool for them.
473     bool bool_stop_other_threads;
474     if (m_options.m_run_mode == eAllThreads)
475       bool_stop_other_threads = false;
476     else if (m_options.m_run_mode == eOnlyDuringStepping)
477       bool_stop_other_threads = (m_step_type != eStepTypeOut);
478     else
479       bool_stop_other_threads = true;
480 
481     ThreadPlanSP new_plan_sp;
482     Status new_plan_status;
483 
484     if (m_step_type == eStepTypeInto) {
485       StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
486       assert(frame != nullptr);
487 
488       if (frame->HasDebugInformation()) {
489         AddressRange range;
490         SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
491         if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) {
492           Status error;
493           if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range,
494                                                    error)) {
495             result.AppendErrorWithFormat("invalid end-line option: %s.",
496                                          error.AsCString());
497             return false;
498           }
499         } else if (m_options.m_end_line_is_block_end) {
500           Status error;
501           Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
502           if (!block) {
503             result.AppendErrorWithFormat("Could not find the current block.");
504             return false;
505           }
506 
507           AddressRange block_range;
508           Address pc_address = frame->GetFrameCodeAddress();
509           block->GetRangeContainingAddress(pc_address, block_range);
510           if (!block_range.GetBaseAddress().IsValid()) {
511             result.AppendErrorWithFormat(
512                 "Could not find the current block address.");
513             return false;
514           }
515           lldb::addr_t pc_offset_in_block =
516               pc_address.GetFileAddress() -
517               block_range.GetBaseAddress().GetFileAddress();
518           lldb::addr_t range_length =
519               block_range.GetByteSize() - pc_offset_in_block;
520           range = AddressRange(pc_address, range_length);
521         } else {
522           range = sc.line_entry.range;
523         }
524 
525         new_plan_sp = thread->QueueThreadPlanForStepInRange(
526             abort_other_plans, range,
527             frame->GetSymbolContext(eSymbolContextEverything),
528             m_options.m_step_in_target.c_str(), stop_other_threads,
529             new_plan_status, m_options.m_step_in_avoid_no_debug,
530             m_options.m_step_out_avoid_no_debug);
531 
532         if (new_plan_sp && !m_options.m_avoid_regexp.empty()) {
533           ThreadPlanStepInRange *step_in_range_plan =
534               static_cast<ThreadPlanStepInRange *>(new_plan_sp.get());
535           step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
536         }
537       } else
538         new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
539             false, abort_other_plans, bool_stop_other_threads, new_plan_status);
540     } else if (m_step_type == eStepTypeOver) {
541       StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
542 
543       if (frame->HasDebugInformation())
544         new_plan_sp = thread->QueueThreadPlanForStepOverRange(
545             abort_other_plans,
546             frame->GetSymbolContext(eSymbolContextEverything).line_entry,
547             frame->GetSymbolContext(eSymbolContextEverything),
548             stop_other_threads, new_plan_status,
549             m_options.m_step_out_avoid_no_debug);
550       else
551         new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
552             true, abort_other_plans, bool_stop_other_threads, new_plan_status);
553     } else if (m_step_type == eStepTypeTrace) {
554       new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
555           false, abort_other_plans, bool_stop_other_threads, new_plan_status);
556     } else if (m_step_type == eStepTypeTraceOver) {
557       new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction(
558           true, abort_other_plans, bool_stop_other_threads, new_plan_status);
559     } else if (m_step_type == eStepTypeOut) {
560       new_plan_sp = thread->QueueThreadPlanForStepOut(
561           abort_other_plans, nullptr, false, bool_stop_other_threads, eVoteYes,
562           eVoteNoOpinion,
563           thread->GetSelectedFrameIndex(DoNoSelectMostRelevantFrame),
564           new_plan_status, m_options.m_step_out_avoid_no_debug);
565     } else if (m_step_type == eStepTypeScripted) {
566       new_plan_sp = thread->QueueThreadPlanForStepScripted(
567           abort_other_plans, m_class_options.GetName().c_str(),
568           m_class_options.GetStructuredData(), bool_stop_other_threads,
569           new_plan_status);
570     } else {
571       result.AppendError("step type is not supported");
572       return false;
573     }
574 
575     // If we got a new plan, then set it to be a controlling plan (User level
576     // Plans should be controlling plans so that they can be interruptible).
577     // Then resume the process.
578 
579     if (new_plan_sp) {
580       new_plan_sp->SetIsControllingPlan(true);
581       new_plan_sp->SetOkayToDiscard(false);
582 
583       if (m_options.m_step_count > 1) {
584         if (!new_plan_sp->SetIterationCount(m_options.m_step_count)) {
585           result.AppendWarning(
586               "step operation does not support iteration count.");
587         }
588       }
589 
590       process->GetThreadList().SetSelectedThreadByID(thread->GetID());
591 
592       const uint32_t iohandler_id = process->GetIOHandlerID();
593 
594       StreamString stream;
595       Status error;
596       if (synchronous_execution)
597         error = process->ResumeSynchronous(&stream);
598       else
599         error = process->Resume();
600 
601       if (!error.Success()) {
602         result.AppendMessage(error.AsCString());
603         return false;
604       }
605 
606       // There is a race condition where this thread will return up the call
607       // stack to the main command handler and show an (lldb) prompt before
608       // HandlePrivateEvent (from PrivateStateThread) has a chance to call
609       // PushProcessIOHandler().
610       process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
611 
612       if (synchronous_execution) {
613         // If any state changed events had anything to say, add that to the
614         // result
615         if (stream.GetSize() > 0)
616           result.AppendMessage(stream.GetString());
617 
618         process->GetThreadList().SetSelectedThreadByID(thread->GetID());
619         result.SetDidChangeProcessState(true);
620         result.SetStatus(eReturnStatusSuccessFinishNoResult);
621       } else {
622         result.SetStatus(eReturnStatusSuccessContinuingNoResult);
623       }
624     } else {
625       result.SetError(new_plan_status);
626     }
627     return result.Succeeded();
628   }
629 
630   StepType m_step_type;
631   StepScope m_step_scope;
632   ThreadStepScopeOptionGroup m_options;
633   OptionGroupPythonClassWithDict m_class_options;
634   OptionGroupOptions m_all_options;
635 };
636 
637 // CommandObjectThreadContinue
638 
639 class CommandObjectThreadContinue : public CommandObjectParsed {
640 public:
641   CommandObjectThreadContinue(CommandInterpreter &interpreter)
642       : CommandObjectParsed(
643             interpreter, "thread continue",
644             "Continue execution of the current target process.  One "
645             "or more threads may be specified, by default all "
646             "threads continue.",
647             nullptr,
648             eCommandRequiresThread | eCommandTryTargetAPILock |
649                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
650     CommandArgumentEntry arg;
651     CommandArgumentData thread_idx_arg;
652 
653     // Define the first (and only) variant of this arg.
654     thread_idx_arg.arg_type = eArgTypeThreadIndex;
655     thread_idx_arg.arg_repetition = eArgRepeatPlus;
656 
657     // There is only one variant this argument could be; put it into the
658     // argument entry.
659     arg.push_back(thread_idx_arg);
660 
661     // Push the data for the first argument into the m_arguments vector.
662     m_arguments.push_back(arg);
663   }
664 
665   ~CommandObjectThreadContinue() override = default;
666 
667   void
668   HandleArgumentCompletion(CompletionRequest &request,
669                            OptionElementVector &opt_element_vector) override {
670     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
671         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
672         nullptr);
673   }
674 
675   bool DoExecute(Args &command, CommandReturnObject &result) override {
676     bool synchronous_execution = m_interpreter.GetSynchronous();
677 
678     Process *process = m_exe_ctx.GetProcessPtr();
679     if (process == nullptr) {
680       result.AppendError("no process exists. Cannot continue");
681       return false;
682     }
683 
684     StateType state = process->GetState();
685     if ((state == eStateCrashed) || (state == eStateStopped) ||
686         (state == eStateSuspended)) {
687       const size_t argc = command.GetArgumentCount();
688       if (argc > 0) {
689         // These two lines appear at the beginning of both blocks in this
690         // if..else, but that is because we need to release the lock before
691         // calling process->Resume below.
692         std::lock_guard<std::recursive_mutex> guard(
693             process->GetThreadList().GetMutex());
694         const uint32_t num_threads = process->GetThreadList().GetSize();
695         std::vector<Thread *> resume_threads;
696         for (auto &entry : command.entries()) {
697           uint32_t thread_idx;
698           if (entry.ref().getAsInteger(0, thread_idx)) {
699             result.AppendErrorWithFormat(
700                 "invalid thread index argument: \"%s\".\n", entry.c_str());
701             return false;
702           }
703           Thread *thread =
704               process->GetThreadList().FindThreadByIndexID(thread_idx).get();
705 
706           if (thread) {
707             resume_threads.push_back(thread);
708           } else {
709             result.AppendErrorWithFormat("invalid thread index %u.\n",
710                                          thread_idx);
711             return false;
712           }
713         }
714 
715         if (resume_threads.empty()) {
716           result.AppendError("no valid thread indexes were specified");
717           return false;
718         } else {
719           if (resume_threads.size() == 1)
720             result.AppendMessageWithFormat("Resuming thread: ");
721           else
722             result.AppendMessageWithFormat("Resuming threads: ");
723 
724           for (uint32_t idx = 0; idx < num_threads; ++idx) {
725             Thread *thread =
726                 process->GetThreadList().GetThreadAtIndex(idx).get();
727             std::vector<Thread *>::iterator this_thread_pos =
728                 find(resume_threads.begin(), resume_threads.end(), thread);
729 
730             if (this_thread_pos != resume_threads.end()) {
731               resume_threads.erase(this_thread_pos);
732               if (!resume_threads.empty())
733                 result.AppendMessageWithFormat("%u, ", thread->GetIndexID());
734               else
735                 result.AppendMessageWithFormat("%u ", thread->GetIndexID());
736 
737               const bool override_suspend = true;
738               thread->SetResumeState(eStateRunning, override_suspend);
739             } else {
740               thread->SetResumeState(eStateSuspended);
741             }
742           }
743           result.AppendMessageWithFormat("in process %" PRIu64 "\n",
744                                          process->GetID());
745         }
746       } else {
747         // These two lines appear at the beginning of both blocks in this
748         // if..else, but that is because we need to release the lock before
749         // calling process->Resume below.
750         std::lock_guard<std::recursive_mutex> guard(
751             process->GetThreadList().GetMutex());
752         const uint32_t num_threads = process->GetThreadList().GetSize();
753         Thread *current_thread = GetDefaultThread();
754         if (current_thread == nullptr) {
755           result.AppendError("the process doesn't have a current thread");
756           return false;
757         }
758         // Set the actions that the threads should each take when resuming
759         for (uint32_t idx = 0; idx < num_threads; ++idx) {
760           Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
761           if (thread == current_thread) {
762             result.AppendMessageWithFormat("Resuming thread 0x%4.4" PRIx64
763                                            " in process %" PRIu64 "\n",
764                                            thread->GetID(), process->GetID());
765             const bool override_suspend = true;
766             thread->SetResumeState(eStateRunning, override_suspend);
767           } else {
768             thread->SetResumeState(eStateSuspended);
769           }
770         }
771       }
772 
773       StreamString stream;
774       Status error;
775       if (synchronous_execution)
776         error = process->ResumeSynchronous(&stream);
777       else
778         error = process->Resume();
779 
780       // We should not be holding the thread list lock when we do this.
781       if (error.Success()) {
782         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
783                                        process->GetID());
784         if (synchronous_execution) {
785           // If any state changed events had anything to say, add that to the
786           // result
787           if (stream.GetSize() > 0)
788             result.AppendMessage(stream.GetString());
789 
790           result.SetDidChangeProcessState(true);
791           result.SetStatus(eReturnStatusSuccessFinishNoResult);
792         } else {
793           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
794         }
795       } else {
796         result.AppendErrorWithFormat("Failed to resume process: %s\n",
797                                      error.AsCString());
798       }
799     } else {
800       result.AppendErrorWithFormat(
801           "Process cannot be continued from its current state (%s).\n",
802           StateAsCString(state));
803     }
804 
805     return result.Succeeded();
806   }
807 };
808 
809 // CommandObjectThreadUntil
810 
811 #define LLDB_OPTIONS_thread_until
812 #include "CommandOptions.inc"
813 
814 class CommandObjectThreadUntil : public CommandObjectParsed {
815 public:
816   class CommandOptions : public Options {
817   public:
818     uint32_t m_thread_idx = LLDB_INVALID_THREAD_ID;
819     uint32_t m_frame_idx = LLDB_INVALID_FRAME_ID;
820 
821     CommandOptions() {
822       // Keep default values of all options in one place: OptionParsingStarting
823       // ()
824       OptionParsingStarting(nullptr);
825     }
826 
827     ~CommandOptions() override = default;
828 
829     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
830                           ExecutionContext *execution_context) override {
831       Status error;
832       const int short_option = m_getopt_table[option_idx].val;
833 
834       switch (short_option) {
835       case 'a': {
836         lldb::addr_t tmp_addr = OptionArgParser::ToAddress(
837             execution_context, option_arg, LLDB_INVALID_ADDRESS, &error);
838         if (error.Success())
839           m_until_addrs.push_back(tmp_addr);
840       } break;
841       case 't':
842         if (option_arg.getAsInteger(0, m_thread_idx)) {
843           m_thread_idx = LLDB_INVALID_INDEX32;
844           error.SetErrorStringWithFormat("invalid thread index '%s'",
845                                          option_arg.str().c_str());
846         }
847         break;
848       case 'f':
849         if (option_arg.getAsInteger(0, m_frame_idx)) {
850           m_frame_idx = LLDB_INVALID_FRAME_ID;
851           error.SetErrorStringWithFormat("invalid frame index '%s'",
852                                          option_arg.str().c_str());
853         }
854         break;
855       case 'm': {
856         auto enum_values = GetDefinitions()[option_idx].enum_values;
857         lldb::RunMode run_mode = (lldb::RunMode)OptionArgParser::ToOptionEnum(
858             option_arg, enum_values, eOnlyDuringStepping, error);
859 
860         if (error.Success()) {
861           if (run_mode == eAllThreads)
862             m_stop_others = false;
863           else
864             m_stop_others = true;
865         }
866       } break;
867       default:
868         llvm_unreachable("Unimplemented option");
869       }
870       return error;
871     }
872 
873     void OptionParsingStarting(ExecutionContext *execution_context) override {
874       m_thread_idx = LLDB_INVALID_THREAD_ID;
875       m_frame_idx = 0;
876       m_stop_others = false;
877       m_until_addrs.clear();
878     }
879 
880     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
881       return llvm::ArrayRef(g_thread_until_options);
882     }
883 
884     uint32_t m_step_thread_idx = LLDB_INVALID_THREAD_ID;
885     bool m_stop_others = false;
886     std::vector<lldb::addr_t> m_until_addrs;
887 
888     // Instance variables to hold the values for command options.
889   };
890 
891   CommandObjectThreadUntil(CommandInterpreter &interpreter)
892       : CommandObjectParsed(
893             interpreter, "thread until",
894             "Continue until a line number or address is reached by the "
895             "current or specified thread.  Stops when returning from "
896             "the current function as a safety measure.  "
897             "The target line number(s) are given as arguments, and if more "
898             "than one"
899             " is provided, stepping will stop when the first one is hit.",
900             nullptr,
901             eCommandRequiresThread | eCommandTryTargetAPILock |
902                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
903     CommandArgumentEntry arg;
904     CommandArgumentData line_num_arg;
905 
906     // Define the first (and only) variant of this arg.
907     line_num_arg.arg_type = eArgTypeLineNum;
908     line_num_arg.arg_repetition = eArgRepeatPlain;
909 
910     // There is only one variant this argument could be; put it into the
911     // argument entry.
912     arg.push_back(line_num_arg);
913 
914     // Push the data for the first argument into the m_arguments vector.
915     m_arguments.push_back(arg);
916   }
917 
918   ~CommandObjectThreadUntil() override = default;
919 
920   Options *GetOptions() override { return &m_options; }
921 
922 protected:
923   bool DoExecute(Args &command, CommandReturnObject &result) override {
924     bool synchronous_execution = m_interpreter.GetSynchronous();
925 
926     Target *target = &GetSelectedTarget();
927 
928     Process *process = m_exe_ctx.GetProcessPtr();
929     if (process == nullptr) {
930       result.AppendError("need a valid process to step");
931     } else {
932       Thread *thread = nullptr;
933       std::vector<uint32_t> line_numbers;
934 
935       if (command.GetArgumentCount() >= 1) {
936         size_t num_args = command.GetArgumentCount();
937         for (size_t i = 0; i < num_args; i++) {
938           uint32_t line_number;
939           if (!llvm::to_integer(command.GetArgumentAtIndex(i), line_number)) {
940             result.AppendErrorWithFormat("invalid line number: '%s'.\n",
941                                          command.GetArgumentAtIndex(i));
942             return false;
943           } else
944             line_numbers.push_back(line_number);
945         }
946       } else if (m_options.m_until_addrs.empty()) {
947         result.AppendErrorWithFormat("No line number or address provided:\n%s",
948                                      GetSyntax().str().c_str());
949         return false;
950       }
951 
952       if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) {
953         thread = GetDefaultThread();
954       } else {
955         thread = process->GetThreadList()
956                      .FindThreadByIndexID(m_options.m_thread_idx)
957                      .get();
958       }
959 
960       if (thread == nullptr) {
961         const uint32_t num_threads = process->GetThreadList().GetSize();
962         result.AppendErrorWithFormat(
963             "Thread index %u is out of range (valid values are 0 - %u).\n",
964             m_options.m_thread_idx, num_threads);
965         return false;
966       }
967 
968       const bool abort_other_plans = false;
969 
970       StackFrame *frame =
971           thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
972       if (frame == nullptr) {
973         result.AppendErrorWithFormat(
974             "Frame index %u is out of range for thread id %" PRIu64 ".\n",
975             m_options.m_frame_idx, thread->GetID());
976         return false;
977       }
978 
979       ThreadPlanSP new_plan_sp;
980       Status new_plan_status;
981 
982       if (frame->HasDebugInformation()) {
983         // Finally we got here...  Translate the given line number to a bunch
984         // of addresses:
985         SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit));
986         LineTable *line_table = nullptr;
987         if (sc.comp_unit)
988           line_table = sc.comp_unit->GetLineTable();
989 
990         if (line_table == nullptr) {
991           result.AppendErrorWithFormat("Failed to resolve the line table for "
992                                        "frame %u of thread id %" PRIu64 ".\n",
993                                        m_options.m_frame_idx, thread->GetID());
994           return false;
995         }
996 
997         LineEntry function_start;
998         uint32_t index_ptr = 0, end_ptr = UINT32_MAX;
999         std::vector<addr_t> address_list;
1000 
1001         // Find the beginning & end index of the function, but first make
1002         // sure it is valid:
1003         if (!sc.function) {
1004           result.AppendErrorWithFormat("Have debug information but no "
1005                                        "function info - can't get until range.");
1006           return false;
1007         }
1008 
1009         AddressRange fun_addr_range = sc.function->GetAddressRange();
1010         Address fun_start_addr = fun_addr_range.GetBaseAddress();
1011         line_table->FindLineEntryByAddress(fun_start_addr, function_start,
1012                                            &index_ptr);
1013 
1014         Address fun_end_addr(fun_start_addr.GetSection(),
1015                              fun_start_addr.GetOffset() +
1016                                  fun_addr_range.GetByteSize());
1017 
1018         bool all_in_function = true;
1019 
1020         line_table->FindLineEntryByAddress(fun_end_addr, function_start,
1021                                            &end_ptr);
1022 
1023         // Since not all source lines will contribute code, check if we are
1024         // setting the breakpoint on the exact line number or the nearest
1025         // subsequent line number and set breakpoints at all the line table
1026         // entries of the chosen line number (exact or nearest subsequent).
1027         for (uint32_t line_number : line_numbers) {
1028           LineEntry line_entry;
1029           bool exact = false;
1030           uint32_t start_idx_ptr = index_ptr;
1031           start_idx_ptr = sc.comp_unit->FindLineEntry(
1032               index_ptr, line_number, nullptr, exact, &line_entry);
1033           if (start_idx_ptr != UINT32_MAX)
1034             line_number = line_entry.line;
1035           exact = true;
1036           start_idx_ptr = index_ptr;
1037           while (start_idx_ptr <= end_ptr) {
1038             start_idx_ptr = sc.comp_unit->FindLineEntry(
1039                 start_idx_ptr, line_number, nullptr, exact, &line_entry);
1040             if (start_idx_ptr == UINT32_MAX)
1041               break;
1042 
1043             addr_t address =
1044                 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1045             if (address != LLDB_INVALID_ADDRESS) {
1046               if (fun_addr_range.ContainsLoadAddress(address, target))
1047                 address_list.push_back(address);
1048               else
1049                 all_in_function = false;
1050             }
1051             start_idx_ptr++;
1052           }
1053         }
1054 
1055         for (lldb::addr_t address : m_options.m_until_addrs) {
1056           if (fun_addr_range.ContainsLoadAddress(address, target))
1057             address_list.push_back(address);
1058           else
1059             all_in_function = false;
1060         }
1061 
1062         if (address_list.empty()) {
1063           if (all_in_function)
1064             result.AppendErrorWithFormat(
1065                 "No line entries matching until target.\n");
1066           else
1067             result.AppendErrorWithFormat(
1068                 "Until target outside of the current function.\n");
1069 
1070           return false;
1071         }
1072 
1073         new_plan_sp = thread->QueueThreadPlanForStepUntil(
1074             abort_other_plans, &address_list.front(), address_list.size(),
1075             m_options.m_stop_others, m_options.m_frame_idx, new_plan_status);
1076         if (new_plan_sp) {
1077           // User level plans should be controlling plans so they can be
1078           // interrupted
1079           // (e.g. by hitting a breakpoint) and other plans executed by the
1080           // user (stepping around the breakpoint) and then a "continue" will
1081           // resume the original plan.
1082           new_plan_sp->SetIsControllingPlan(true);
1083           new_plan_sp->SetOkayToDiscard(false);
1084         } else {
1085           result.SetError(new_plan_status);
1086           return false;
1087         }
1088       } else {
1089         result.AppendErrorWithFormat("Frame index %u of thread id %" PRIu64
1090                                      " has no debug information.\n",
1091                                      m_options.m_frame_idx, thread->GetID());
1092         return false;
1093       }
1094 
1095       if (!process->GetThreadList().SetSelectedThreadByID(thread->GetID())) {
1096         result.AppendErrorWithFormat(
1097             "Failed to set the selected thread to thread id %" PRIu64 ".\n",
1098             thread->GetID());
1099         return false;
1100       }
1101 
1102       StreamString stream;
1103       Status error;
1104       if (synchronous_execution)
1105         error = process->ResumeSynchronous(&stream);
1106       else
1107         error = process->Resume();
1108 
1109       if (error.Success()) {
1110         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
1111                                        process->GetID());
1112         if (synchronous_execution) {
1113           // If any state changed events had anything to say, add that to the
1114           // result
1115           if (stream.GetSize() > 0)
1116             result.AppendMessage(stream.GetString());
1117 
1118           result.SetDidChangeProcessState(true);
1119           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1120         } else {
1121           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
1122         }
1123       } else {
1124         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
1125                                      error.AsCString());
1126       }
1127     }
1128     return result.Succeeded();
1129   }
1130 
1131   CommandOptions m_options;
1132 };
1133 
1134 // CommandObjectThreadSelect
1135 
1136 class CommandObjectThreadSelect : public CommandObjectParsed {
1137 public:
1138   CommandObjectThreadSelect(CommandInterpreter &interpreter)
1139       : CommandObjectParsed(interpreter, "thread select",
1140                             "Change the currently selected thread.", nullptr,
1141                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1142                                 eCommandProcessMustBeLaunched |
1143                                 eCommandProcessMustBePaused) {
1144     CommandArgumentEntry arg;
1145     CommandArgumentData thread_idx_arg;
1146 
1147     // Define the first (and only) variant of this arg.
1148     thread_idx_arg.arg_type = eArgTypeThreadIndex;
1149     thread_idx_arg.arg_repetition = eArgRepeatPlain;
1150 
1151     // There is only one variant this argument could be; put it into the
1152     // argument entry.
1153     arg.push_back(thread_idx_arg);
1154 
1155     // Push the data for the first argument into the m_arguments vector.
1156     m_arguments.push_back(arg);
1157   }
1158 
1159   ~CommandObjectThreadSelect() override = default;
1160 
1161   void
1162   HandleArgumentCompletion(CompletionRequest &request,
1163                            OptionElementVector &opt_element_vector) override {
1164     if (request.GetCursorIndex())
1165       return;
1166 
1167     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1168         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
1169         nullptr);
1170   }
1171 
1172 protected:
1173   bool DoExecute(Args &command, CommandReturnObject &result) override {
1174     Process *process = m_exe_ctx.GetProcessPtr();
1175     if (process == nullptr) {
1176       result.AppendError("no process");
1177       return false;
1178     } else if (command.GetArgumentCount() != 1) {
1179       result.AppendErrorWithFormat(
1180           "'%s' takes exactly one thread index argument:\nUsage: %s\n",
1181           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1182       return false;
1183     }
1184 
1185     uint32_t index_id;
1186     if (!llvm::to_integer(command.GetArgumentAtIndex(0), index_id)) {
1187       result.AppendErrorWithFormat("Invalid thread index '%s'",
1188                                    command.GetArgumentAtIndex(0));
1189       return false;
1190     }
1191 
1192     Thread *new_thread =
1193         process->GetThreadList().FindThreadByIndexID(index_id).get();
1194     if (new_thread == nullptr) {
1195       result.AppendErrorWithFormat("invalid thread #%s.\n",
1196                                    command.GetArgumentAtIndex(0));
1197       return false;
1198     }
1199 
1200     process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1201     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1202 
1203     return result.Succeeded();
1204   }
1205 };
1206 
1207 // CommandObjectThreadList
1208 
1209 class CommandObjectThreadList : public CommandObjectParsed {
1210 public:
1211   CommandObjectThreadList(CommandInterpreter &interpreter)
1212       : CommandObjectParsed(
1213             interpreter, "thread list",
1214             "Show a summary of each thread in the current target process.  "
1215             "Use 'settings set thread-format' to customize the individual "
1216             "thread listings.",
1217             "thread list",
1218             eCommandRequiresProcess | eCommandTryTargetAPILock |
1219                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1220 
1221   ~CommandObjectThreadList() override = default;
1222 
1223 protected:
1224   bool DoExecute(Args &command, CommandReturnObject &result) override {
1225     Stream &strm = result.GetOutputStream();
1226     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1227     Process *process = m_exe_ctx.GetProcessPtr();
1228     const bool only_threads_with_stop_reason = false;
1229     const uint32_t start_frame = 0;
1230     const uint32_t num_frames = 0;
1231     const uint32_t num_frames_with_source = 0;
1232     process->GetStatus(strm);
1233     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1234                              num_frames, num_frames_with_source, false);
1235     return result.Succeeded();
1236   }
1237 };
1238 
1239 // CommandObjectThreadInfo
1240 #define LLDB_OPTIONS_thread_info
1241 #include "CommandOptions.inc"
1242 
1243 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads {
1244 public:
1245   class CommandOptions : public Options {
1246   public:
1247     CommandOptions() { OptionParsingStarting(nullptr); }
1248 
1249     ~CommandOptions() override = default;
1250 
1251     void OptionParsingStarting(ExecutionContext *execution_context) override {
1252       m_json_thread = false;
1253       m_json_stopinfo = false;
1254     }
1255 
1256     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1257                           ExecutionContext *execution_context) override {
1258       const int short_option = m_getopt_table[option_idx].val;
1259       Status error;
1260 
1261       switch (short_option) {
1262       case 'j':
1263         m_json_thread = true;
1264         break;
1265 
1266       case 's':
1267         m_json_stopinfo = true;
1268         break;
1269 
1270       default:
1271         llvm_unreachable("Unimplemented option");
1272       }
1273       return error;
1274     }
1275 
1276     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1277       return llvm::ArrayRef(g_thread_info_options);
1278     }
1279 
1280     bool m_json_thread;
1281     bool m_json_stopinfo;
1282   };
1283 
1284   CommandObjectThreadInfo(CommandInterpreter &interpreter)
1285       : CommandObjectIterateOverThreads(
1286             interpreter, "thread info",
1287             "Show an extended summary of one or "
1288             "more threads.  Defaults to the "
1289             "current thread.",
1290             "thread info",
1291             eCommandRequiresProcess | eCommandTryTargetAPILock |
1292                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1293     m_add_return = false;
1294   }
1295 
1296   ~CommandObjectThreadInfo() override = default;
1297 
1298   void
1299   HandleArgumentCompletion(CompletionRequest &request,
1300                            OptionElementVector &opt_element_vector) override {
1301     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1302         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
1303         nullptr);
1304   }
1305 
1306   Options *GetOptions() override { return &m_options; }
1307 
1308   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1309     ThreadSP thread_sp =
1310         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1311     if (!thread_sp) {
1312       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1313                                    tid);
1314       return false;
1315     }
1316 
1317     Thread *thread = thread_sp.get();
1318 
1319     Stream &strm = result.GetOutputStream();
1320     if (!thread->GetDescription(strm, eDescriptionLevelFull,
1321                                 m_options.m_json_thread,
1322                                 m_options.m_json_stopinfo)) {
1323       result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1324                                    thread->GetIndexID());
1325       return false;
1326     }
1327     return true;
1328   }
1329 
1330   CommandOptions m_options;
1331 };
1332 
1333 // CommandObjectThreadException
1334 
1335 class CommandObjectThreadException : public CommandObjectIterateOverThreads {
1336 public:
1337   CommandObjectThreadException(CommandInterpreter &interpreter)
1338       : CommandObjectIterateOverThreads(
1339             interpreter, "thread exception",
1340             "Display the current exception object for a thread. Defaults to "
1341             "the current thread.",
1342             "thread exception",
1343             eCommandRequiresProcess | eCommandTryTargetAPILock |
1344                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1345 
1346   ~CommandObjectThreadException() override = default;
1347 
1348   void
1349   HandleArgumentCompletion(CompletionRequest &request,
1350                            OptionElementVector &opt_element_vector) override {
1351     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1352         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
1353         nullptr);
1354   }
1355 
1356   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1357     ThreadSP thread_sp =
1358         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1359     if (!thread_sp) {
1360       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1361                                    tid);
1362       return false;
1363     }
1364 
1365     Stream &strm = result.GetOutputStream();
1366     ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1367     if (exception_object_sp) {
1368       exception_object_sp->Dump(strm);
1369     }
1370 
1371     ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1372     if (exception_thread_sp && exception_thread_sp->IsValid()) {
1373       const uint32_t num_frames_with_source = 0;
1374       const bool stop_format = false;
1375       exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1376                                      num_frames_with_source, stop_format);
1377     }
1378 
1379     return true;
1380   }
1381 };
1382 
1383 class CommandObjectThreadSiginfo : public CommandObjectIterateOverThreads {
1384 public:
1385   CommandObjectThreadSiginfo(CommandInterpreter &interpreter)
1386       : CommandObjectIterateOverThreads(
1387             interpreter, "thread siginfo",
1388             "Display the current siginfo object for a thread. Defaults to "
1389             "the current thread.",
1390             "thread siginfo",
1391             eCommandRequiresProcess | eCommandTryTargetAPILock |
1392                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1393 
1394   ~CommandObjectThreadSiginfo() override = default;
1395 
1396   void
1397   HandleArgumentCompletion(CompletionRequest &request,
1398                            OptionElementVector &opt_element_vector) override {
1399     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1400         GetCommandInterpreter(), lldb::eThreadIndexCompletion, request,
1401         nullptr);
1402   }
1403 
1404   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1405     ThreadSP thread_sp =
1406         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1407     if (!thread_sp) {
1408       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1409                                    tid);
1410       return false;
1411     }
1412 
1413     Stream &strm = result.GetOutputStream();
1414     if (!thread_sp->GetDescription(strm, eDescriptionLevelFull, false, false)) {
1415       result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1416                                    thread_sp->GetIndexID());
1417       return false;
1418     }
1419     ValueObjectSP exception_object_sp = thread_sp->GetSiginfoValue();
1420     if (exception_object_sp)
1421       exception_object_sp->Dump(strm);
1422     else
1423       strm.Printf("(no siginfo)\n");
1424     strm.PutChar('\n');
1425 
1426     return true;
1427   }
1428 };
1429 
1430 // CommandObjectThreadReturn
1431 #define LLDB_OPTIONS_thread_return
1432 #include "CommandOptions.inc"
1433 
1434 class CommandObjectThreadReturn : public CommandObjectRaw {
1435 public:
1436   class CommandOptions : public Options {
1437   public:
1438     CommandOptions() {
1439       // Keep default values of all options in one place: OptionParsingStarting
1440       // ()
1441       OptionParsingStarting(nullptr);
1442     }
1443 
1444     ~CommandOptions() override = default;
1445 
1446     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1447                           ExecutionContext *execution_context) override {
1448       Status error;
1449       const int short_option = m_getopt_table[option_idx].val;
1450 
1451       switch (short_option) {
1452       case 'x': {
1453         bool success;
1454         bool tmp_value =
1455             OptionArgParser::ToBoolean(option_arg, false, &success);
1456         if (success)
1457           m_from_expression = tmp_value;
1458         else {
1459           error.SetErrorStringWithFormat(
1460               "invalid boolean value '%s' for 'x' option",
1461               option_arg.str().c_str());
1462         }
1463       } break;
1464       default:
1465         llvm_unreachable("Unimplemented option");
1466       }
1467       return error;
1468     }
1469 
1470     void OptionParsingStarting(ExecutionContext *execution_context) override {
1471       m_from_expression = false;
1472     }
1473 
1474     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1475       return llvm::ArrayRef(g_thread_return_options);
1476     }
1477 
1478     bool m_from_expression = false;
1479 
1480     // Instance variables to hold the values for command options.
1481   };
1482 
1483   CommandObjectThreadReturn(CommandInterpreter &interpreter)
1484       : CommandObjectRaw(interpreter, "thread return",
1485                          "Prematurely return from a stack frame, "
1486                          "short-circuiting execution of newer frames "
1487                          "and optionally yielding a specified value.  Defaults "
1488                          "to the exiting the current stack "
1489                          "frame.",
1490                          "thread return",
1491                          eCommandRequiresFrame | eCommandTryTargetAPILock |
1492                              eCommandProcessMustBeLaunched |
1493                              eCommandProcessMustBePaused) {
1494     CommandArgumentEntry arg;
1495     CommandArgumentData expression_arg;
1496 
1497     // Define the first (and only) variant of this arg.
1498     expression_arg.arg_type = eArgTypeExpression;
1499     expression_arg.arg_repetition = eArgRepeatOptional;
1500 
1501     // There is only one variant this argument could be; put it into the
1502     // argument entry.
1503     arg.push_back(expression_arg);
1504 
1505     // Push the data for the first argument into the m_arguments vector.
1506     m_arguments.push_back(arg);
1507   }
1508 
1509   ~CommandObjectThreadReturn() override = default;
1510 
1511   Options *GetOptions() override { return &m_options; }
1512 
1513 protected:
1514   bool DoExecute(llvm::StringRef command,
1515                  CommandReturnObject &result) override {
1516     // I am going to handle this by hand, because I don't want you to have to
1517     // say:
1518     // "thread return -- -5".
1519     if (command.startswith("-x")) {
1520       if (command.size() != 2U)
1521         result.AppendWarning("Return values ignored when returning from user "
1522                              "called expressions");
1523 
1524       Thread *thread = m_exe_ctx.GetThreadPtr();
1525       Status error;
1526       error = thread->UnwindInnermostExpression();
1527       if (!error.Success()) {
1528         result.AppendErrorWithFormat("Unwinding expression failed - %s.",
1529                                      error.AsCString());
1530       } else {
1531         bool success =
1532             thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1533         if (success) {
1534           m_exe_ctx.SetFrameSP(
1535               thread->GetSelectedFrame(DoNoSelectMostRelevantFrame));
1536           result.SetStatus(eReturnStatusSuccessFinishResult);
1537         } else {
1538           result.AppendErrorWithFormat(
1539               "Could not select 0th frame after unwinding expression.");
1540         }
1541       }
1542       return result.Succeeded();
1543     }
1544 
1545     ValueObjectSP return_valobj_sp;
1546 
1547     StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1548     uint32_t frame_idx = frame_sp->GetFrameIndex();
1549 
1550     if (frame_sp->IsInlined()) {
1551       result.AppendError("Don't know how to return from inlined frames.");
1552       return false;
1553     }
1554 
1555     if (!command.empty()) {
1556       Target *target = m_exe_ctx.GetTargetPtr();
1557       EvaluateExpressionOptions options;
1558 
1559       options.SetUnwindOnError(true);
1560       options.SetUseDynamic(eNoDynamicValues);
1561 
1562       ExpressionResults exe_results = eExpressionSetupError;
1563       exe_results = target->EvaluateExpression(command, frame_sp.get(),
1564                                                return_valobj_sp, options);
1565       if (exe_results != eExpressionCompleted) {
1566         if (return_valobj_sp)
1567           result.AppendErrorWithFormat(
1568               "Error evaluating result expression: %s",
1569               return_valobj_sp->GetError().AsCString());
1570         else
1571           result.AppendErrorWithFormat(
1572               "Unknown error evaluating result expression.");
1573         return false;
1574       }
1575     }
1576 
1577     Status error;
1578     ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1579     const bool broadcast = true;
1580     error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1581     if (!error.Success()) {
1582       result.AppendErrorWithFormat(
1583           "Error returning from frame %d of thread %d: %s.", frame_idx,
1584           thread_sp->GetIndexID(), error.AsCString());
1585       return false;
1586     }
1587 
1588     result.SetStatus(eReturnStatusSuccessFinishResult);
1589     return true;
1590   }
1591 
1592   CommandOptions m_options;
1593 };
1594 
1595 // CommandObjectThreadJump
1596 #define LLDB_OPTIONS_thread_jump
1597 #include "CommandOptions.inc"
1598 
1599 class CommandObjectThreadJump : public CommandObjectParsed {
1600 public:
1601   class CommandOptions : public Options {
1602   public:
1603     CommandOptions() { OptionParsingStarting(nullptr); }
1604 
1605     ~CommandOptions() override = default;
1606 
1607     void OptionParsingStarting(ExecutionContext *execution_context) override {
1608       m_filenames.Clear();
1609       m_line_num = 0;
1610       m_line_offset = 0;
1611       m_load_addr = LLDB_INVALID_ADDRESS;
1612       m_force = false;
1613     }
1614 
1615     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1616                           ExecutionContext *execution_context) override {
1617       const int short_option = m_getopt_table[option_idx].val;
1618       Status error;
1619 
1620       switch (short_option) {
1621       case 'f':
1622         m_filenames.AppendIfUnique(FileSpec(option_arg));
1623         if (m_filenames.GetSize() > 1)
1624           return Status("only one source file expected.");
1625         break;
1626       case 'l':
1627         if (option_arg.getAsInteger(0, m_line_num))
1628           return Status("invalid line number: '%s'.", option_arg.str().c_str());
1629         break;
1630       case 'b':
1631         if (option_arg.getAsInteger(0, m_line_offset))
1632           return Status("invalid line offset: '%s'.", option_arg.str().c_str());
1633         break;
1634       case 'a':
1635         m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1636                                                  LLDB_INVALID_ADDRESS, &error);
1637         break;
1638       case 'r':
1639         m_force = true;
1640         break;
1641       default:
1642         llvm_unreachable("Unimplemented option");
1643       }
1644       return error;
1645     }
1646 
1647     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1648       return llvm::ArrayRef(g_thread_jump_options);
1649     }
1650 
1651     FileSpecList m_filenames;
1652     uint32_t m_line_num;
1653     int32_t m_line_offset;
1654     lldb::addr_t m_load_addr;
1655     bool m_force;
1656   };
1657 
1658   CommandObjectThreadJump(CommandInterpreter &interpreter)
1659       : CommandObjectParsed(
1660             interpreter, "thread jump",
1661             "Sets the program counter to a new address.", "thread jump",
1662             eCommandRequiresFrame | eCommandTryTargetAPILock |
1663                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1664 
1665   ~CommandObjectThreadJump() override = default;
1666 
1667   Options *GetOptions() override { return &m_options; }
1668 
1669 protected:
1670   bool DoExecute(Args &args, CommandReturnObject &result) override {
1671     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1672     StackFrame *frame = m_exe_ctx.GetFramePtr();
1673     Thread *thread = m_exe_ctx.GetThreadPtr();
1674     Target *target = m_exe_ctx.GetTargetPtr();
1675     const SymbolContext &sym_ctx =
1676         frame->GetSymbolContext(eSymbolContextLineEntry);
1677 
1678     if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1679       // Use this address directly.
1680       Address dest = Address(m_options.m_load_addr);
1681 
1682       lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1683       if (callAddr == LLDB_INVALID_ADDRESS) {
1684         result.AppendErrorWithFormat("Invalid destination address.");
1685         return false;
1686       }
1687 
1688       if (!reg_ctx->SetPC(callAddr)) {
1689         result.AppendErrorWithFormat("Error changing PC value for thread %d.",
1690                                      thread->GetIndexID());
1691         return false;
1692       }
1693     } else {
1694       // Pick either the absolute line, or work out a relative one.
1695       int32_t line = (int32_t)m_options.m_line_num;
1696       if (line == 0)
1697         line = sym_ctx.line_entry.line + m_options.m_line_offset;
1698 
1699       // Try the current file, but override if asked.
1700       FileSpec file = sym_ctx.line_entry.file;
1701       if (m_options.m_filenames.GetSize() == 1)
1702         file = m_options.m_filenames.GetFileSpecAtIndex(0);
1703 
1704       if (!file) {
1705         result.AppendErrorWithFormat(
1706             "No source file available for the current location.");
1707         return false;
1708       }
1709 
1710       std::string warnings;
1711       Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1712 
1713       if (err.Fail()) {
1714         result.SetError(err);
1715         return false;
1716       }
1717 
1718       if (!warnings.empty())
1719         result.AppendWarning(warnings.c_str());
1720     }
1721 
1722     result.SetStatus(eReturnStatusSuccessFinishResult);
1723     return true;
1724   }
1725 
1726   CommandOptions m_options;
1727 };
1728 
1729 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1730 
1731 // CommandObjectThreadPlanList
1732 #define LLDB_OPTIONS_thread_plan_list
1733 #include "CommandOptions.inc"
1734 
1735 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads {
1736 public:
1737   class CommandOptions : public Options {
1738   public:
1739     CommandOptions() {
1740       // Keep default values of all options in one place: OptionParsingStarting
1741       // ()
1742       OptionParsingStarting(nullptr);
1743     }
1744 
1745     ~CommandOptions() override = default;
1746 
1747     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1748                           ExecutionContext *execution_context) override {
1749       const int short_option = m_getopt_table[option_idx].val;
1750 
1751       switch (short_option) {
1752       case 'i':
1753         m_internal = true;
1754         break;
1755       case 't':
1756         lldb::tid_t tid;
1757         if (option_arg.getAsInteger(0, tid))
1758           return Status("invalid tid: '%s'.", option_arg.str().c_str());
1759         m_tids.push_back(tid);
1760         break;
1761       case 'u':
1762         m_unreported = false;
1763         break;
1764       case 'v':
1765         m_verbose = true;
1766         break;
1767       default:
1768         llvm_unreachable("Unimplemented option");
1769       }
1770       return {};
1771     }
1772 
1773     void OptionParsingStarting(ExecutionContext *execution_context) override {
1774       m_verbose = false;
1775       m_internal = false;
1776       m_unreported = true; // The variable is "skip unreported" and we want to
1777                            // skip unreported by default.
1778       m_tids.clear();
1779     }
1780 
1781     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1782       return llvm::ArrayRef(g_thread_plan_list_options);
1783     }
1784 
1785     // Instance variables to hold the values for command options.
1786     bool m_verbose;
1787     bool m_internal;
1788     bool m_unreported;
1789     std::vector<lldb::tid_t> m_tids;
1790   };
1791 
1792   CommandObjectThreadPlanList(CommandInterpreter &interpreter)
1793       : CommandObjectIterateOverThreads(
1794             interpreter, "thread plan list",
1795             "Show thread plans for one or more threads.  If no threads are "
1796             "specified, show the "
1797             "current thread.  Use the thread-index \"all\" to see all threads.",
1798             nullptr,
1799             eCommandRequiresProcess | eCommandRequiresThread |
1800                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1801                 eCommandProcessMustBePaused) {}
1802 
1803   ~CommandObjectThreadPlanList() override = default;
1804 
1805   Options *GetOptions() override { return &m_options; }
1806 
1807   bool DoExecute(Args &command, CommandReturnObject &result) override {
1808     // If we are reporting all threads, dispatch to the Process to do that:
1809     if (command.GetArgumentCount() == 0 && m_options.m_tids.empty()) {
1810       Stream &strm = result.GetOutputStream();
1811       DescriptionLevel desc_level = m_options.m_verbose
1812                                         ? eDescriptionLevelVerbose
1813                                         : eDescriptionLevelFull;
1814       m_exe_ctx.GetProcessPtr()->DumpThreadPlans(
1815           strm, desc_level, m_options.m_internal, true, m_options.m_unreported);
1816       result.SetStatus(eReturnStatusSuccessFinishResult);
1817       return true;
1818     } else {
1819       // Do any TID's that the user may have specified as TID, then do any
1820       // Thread Indexes...
1821       if (!m_options.m_tids.empty()) {
1822         Process *process = m_exe_ctx.GetProcessPtr();
1823         StreamString tmp_strm;
1824         for (lldb::tid_t tid : m_options.m_tids) {
1825           bool success = process->DumpThreadPlansForTID(
1826               tmp_strm, tid, eDescriptionLevelFull, m_options.m_internal,
1827               true /* condense_trivial */, m_options.m_unreported);
1828           // If we didn't find a TID, stop here and return an error.
1829           if (!success) {
1830             result.AppendError("Error dumping plans:");
1831             result.AppendError(tmp_strm.GetString());
1832             return false;
1833           }
1834           // Otherwise, add our data to the output:
1835           result.GetOutputStream() << tmp_strm.GetString();
1836         }
1837       }
1838       return CommandObjectIterateOverThreads::DoExecute(command, result);
1839     }
1840   }
1841 
1842 protected:
1843   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1844     // If we have already handled this from a -t option, skip it here.
1845     if (llvm::is_contained(m_options.m_tids, tid))
1846       return true;
1847 
1848     Process *process = m_exe_ctx.GetProcessPtr();
1849 
1850     Stream &strm = result.GetOutputStream();
1851     DescriptionLevel desc_level = eDescriptionLevelFull;
1852     if (m_options.m_verbose)
1853       desc_level = eDescriptionLevelVerbose;
1854 
1855     process->DumpThreadPlansForTID(strm, tid, desc_level, m_options.m_internal,
1856                                    true /* condense_trivial */,
1857                                    m_options.m_unreported);
1858     return true;
1859   }
1860 
1861   CommandOptions m_options;
1862 };
1863 
1864 class CommandObjectThreadPlanDiscard : public CommandObjectParsed {
1865 public:
1866   CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
1867       : CommandObjectParsed(interpreter, "thread plan discard",
1868                             "Discards thread plans up to and including the "
1869                             "specified index (see 'thread plan list'.)  "
1870                             "Only user visible plans can be discarded.",
1871                             nullptr,
1872                             eCommandRequiresProcess | eCommandRequiresThread |
1873                                 eCommandTryTargetAPILock |
1874                                 eCommandProcessMustBeLaunched |
1875                                 eCommandProcessMustBePaused) {
1876     CommandArgumentEntry arg;
1877     CommandArgumentData plan_index_arg;
1878 
1879     // Define the first (and only) variant of this arg.
1880     plan_index_arg.arg_type = eArgTypeUnsignedInteger;
1881     plan_index_arg.arg_repetition = eArgRepeatPlain;
1882 
1883     // There is only one variant this argument could be; put it into the
1884     // argument entry.
1885     arg.push_back(plan_index_arg);
1886 
1887     // Push the data for the first argument into the m_arguments vector.
1888     m_arguments.push_back(arg);
1889   }
1890 
1891   ~CommandObjectThreadPlanDiscard() override = default;
1892 
1893   void
1894   HandleArgumentCompletion(CompletionRequest &request,
1895                            OptionElementVector &opt_element_vector) override {
1896     if (!m_exe_ctx.HasThreadScope() || request.GetCursorIndex())
1897       return;
1898 
1899     m_exe_ctx.GetThreadPtr()->AutoCompleteThreadPlans(request);
1900   }
1901 
1902   bool DoExecute(Args &args, CommandReturnObject &result) override {
1903     Thread *thread = m_exe_ctx.GetThreadPtr();
1904     if (args.GetArgumentCount() != 1) {
1905       result.AppendErrorWithFormat("Too many arguments, expected one - the "
1906                                    "thread plan index - but got %zu.",
1907                                    args.GetArgumentCount());
1908       return false;
1909     }
1910 
1911     uint32_t thread_plan_idx;
1912     if (!llvm::to_integer(args.GetArgumentAtIndex(0), thread_plan_idx)) {
1913       result.AppendErrorWithFormat(
1914           "Invalid thread index: \"%s\" - should be unsigned int.",
1915           args.GetArgumentAtIndex(0));
1916       return false;
1917     }
1918 
1919     if (thread_plan_idx == 0) {
1920       result.AppendErrorWithFormat(
1921           "You wouldn't really want me to discard the base thread plan.");
1922       return false;
1923     }
1924 
1925     if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
1926       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1927       return true;
1928     } else {
1929       result.AppendErrorWithFormat(
1930           "Could not find User thread plan with index %s.",
1931           args.GetArgumentAtIndex(0));
1932       return false;
1933     }
1934   }
1935 };
1936 
1937 class CommandObjectThreadPlanPrune : public CommandObjectParsed {
1938 public:
1939   CommandObjectThreadPlanPrune(CommandInterpreter &interpreter)
1940       : CommandObjectParsed(interpreter, "thread plan prune",
1941                             "Removes any thread plans associated with "
1942                             "currently unreported threads.  "
1943                             "Specify one or more TID's to remove, or if no "
1944                             "TID's are provides, remove threads for all "
1945                             "unreported threads",
1946                             nullptr,
1947                             eCommandRequiresProcess |
1948                                 eCommandTryTargetAPILock |
1949                                 eCommandProcessMustBeLaunched |
1950                                 eCommandProcessMustBePaused) {
1951     CommandArgumentEntry arg;
1952     CommandArgumentData tid_arg;
1953 
1954     // Define the first (and only) variant of this arg.
1955     tid_arg.arg_type = eArgTypeThreadID;
1956     tid_arg.arg_repetition = eArgRepeatStar;
1957 
1958     // There is only one variant this argument could be; put it into the
1959     // argument entry.
1960     arg.push_back(tid_arg);
1961 
1962     // Push the data for the first argument into the m_arguments vector.
1963     m_arguments.push_back(arg);
1964   }
1965 
1966   ~CommandObjectThreadPlanPrune() override = default;
1967 
1968   bool DoExecute(Args &args, CommandReturnObject &result) override {
1969     Process *process = m_exe_ctx.GetProcessPtr();
1970 
1971     if (args.GetArgumentCount() == 0) {
1972       process->PruneThreadPlans();
1973       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1974       return true;
1975     }
1976 
1977     const size_t num_args = args.GetArgumentCount();
1978 
1979     std::lock_guard<std::recursive_mutex> guard(
1980         process->GetThreadList().GetMutex());
1981 
1982     for (size_t i = 0; i < num_args; i++) {
1983       lldb::tid_t tid;
1984       if (!llvm::to_integer(args.GetArgumentAtIndex(i), tid)) {
1985         result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n",
1986                                      args.GetArgumentAtIndex(i));
1987         return false;
1988       }
1989       if (!process->PruneThreadPlansForTID(tid)) {
1990         result.AppendErrorWithFormat("Could not find unreported tid: \"%s\"\n",
1991                                      args.GetArgumentAtIndex(i));
1992         return false;
1993       }
1994     }
1995     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1996     return true;
1997   }
1998 };
1999 
2000 // CommandObjectMultiwordThreadPlan
2001 
2002 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword {
2003 public:
2004   CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
2005       : CommandObjectMultiword(
2006             interpreter, "plan",
2007             "Commands for managing thread plans that control execution.",
2008             "thread plan <subcommand> [<subcommand objects]") {
2009     LoadSubCommand(
2010         "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
2011     LoadSubCommand(
2012         "discard",
2013         CommandObjectSP(new CommandObjectThreadPlanDiscard(interpreter)));
2014     LoadSubCommand(
2015         "prune",
2016         CommandObjectSP(new CommandObjectThreadPlanPrune(interpreter)));
2017   }
2018 
2019   ~CommandObjectMultiwordThreadPlan() override = default;
2020 };
2021 
2022 // Next are the subcommands of CommandObjectMultiwordTrace
2023 
2024 // CommandObjectTraceExport
2025 
2026 class CommandObjectTraceExport : public CommandObjectMultiword {
2027 public:
2028   CommandObjectTraceExport(CommandInterpreter &interpreter)
2029       : CommandObjectMultiword(
2030             interpreter, "trace thread export",
2031             "Commands for exporting traces of the threads in the current "
2032             "process to different formats.",
2033             "thread trace export <export-plugin> [<subcommand objects>]") {
2034 
2035     unsigned i = 0;
2036     for (llvm::StringRef plugin_name =
2037              PluginManager::GetTraceExporterPluginNameAtIndex(i);
2038          !plugin_name.empty();
2039          plugin_name = PluginManager::GetTraceExporterPluginNameAtIndex(i++)) {
2040       if (ThreadTraceExportCommandCreator command_creator =
2041               PluginManager::GetThreadTraceExportCommandCreatorAtIndex(i)) {
2042         LoadSubCommand(plugin_name, command_creator(interpreter));
2043       }
2044     }
2045   }
2046 };
2047 
2048 // CommandObjectTraceStart
2049 
2050 class CommandObjectTraceStart : public CommandObjectTraceProxy {
2051 public:
2052   CommandObjectTraceStart(CommandInterpreter &interpreter)
2053       : CommandObjectTraceProxy(
2054             /*live_debug_session_only=*/true, interpreter, "thread trace start",
2055             "Start tracing threads with the corresponding trace "
2056             "plug-in for the current process.",
2057             "thread trace start [<trace-options>]") {}
2058 
2059 protected:
2060   lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
2061     return trace.GetThreadTraceStartCommand(m_interpreter);
2062   }
2063 };
2064 
2065 // CommandObjectTraceStop
2066 
2067 class CommandObjectTraceStop : public CommandObjectMultipleThreads {
2068 public:
2069   CommandObjectTraceStop(CommandInterpreter &interpreter)
2070       : CommandObjectMultipleThreads(
2071             interpreter, "thread trace stop",
2072             "Stop tracing threads, including the ones traced with the "
2073             "\"process trace start\" command."
2074             "Defaults to the current thread. Thread indices can be "
2075             "specified as arguments.\n Use the thread-index \"all\" to stop "
2076             "tracing "
2077             "for all existing threads.",
2078             "thread trace stop [<thread-index> <thread-index> ...]",
2079             eCommandRequiresProcess | eCommandTryTargetAPILock |
2080                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2081                 eCommandProcessMustBeTraced) {}
2082 
2083   ~CommandObjectTraceStop() override = default;
2084 
2085   bool DoExecuteOnThreads(Args &command, CommandReturnObject &result,
2086                           llvm::ArrayRef<lldb::tid_t> tids) override {
2087     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2088 
2089     TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2090 
2091     if (llvm::Error err = trace_sp->Stop(tids))
2092       result.AppendError(toString(std::move(err)));
2093     else
2094       result.SetStatus(eReturnStatusSuccessFinishResult);
2095 
2096     return result.Succeeded();
2097   }
2098 };
2099 
2100 static ThreadSP GetSingleThreadFromArgs(ExecutionContext &exe_ctx, Args &args,
2101                                         CommandReturnObject &result) {
2102   if (args.GetArgumentCount() == 0)
2103     return exe_ctx.GetThreadSP();
2104 
2105   const char *arg = args.GetArgumentAtIndex(0);
2106   uint32_t thread_idx;
2107 
2108   if (!llvm::to_integer(arg, thread_idx)) {
2109     result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n", arg);
2110     return nullptr;
2111   }
2112   ThreadSP thread_sp =
2113       exe_ctx.GetProcessRef().GetThreadList().FindThreadByIndexID(thread_idx);
2114   if (!thread_sp)
2115     result.AppendErrorWithFormat("no thread with index: \"%s\"\n", arg);
2116   return thread_sp;
2117 }
2118 
2119 // CommandObjectTraceDumpFunctionCalls
2120 #define LLDB_OPTIONS_thread_trace_dump_function_calls
2121 #include "CommandOptions.inc"
2122 
2123 class CommandObjectTraceDumpFunctionCalls : public CommandObjectParsed {
2124 public:
2125   class CommandOptions : public Options {
2126   public:
2127     CommandOptions() { OptionParsingStarting(nullptr); }
2128 
2129     ~CommandOptions() override = default;
2130 
2131     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2132                           ExecutionContext *execution_context) override {
2133       Status error;
2134       const int short_option = m_getopt_table[option_idx].val;
2135 
2136       switch (short_option) {
2137       case 'j': {
2138         m_dumper_options.json = true;
2139         break;
2140       }
2141       case 'J': {
2142         m_dumper_options.json = true;
2143         m_dumper_options.pretty_print_json = true;
2144         break;
2145       }
2146       case 'F': {
2147         m_output_file.emplace(option_arg);
2148         break;
2149       }
2150       default:
2151         llvm_unreachable("Unimplemented option");
2152       }
2153       return error;
2154     }
2155 
2156     void OptionParsingStarting(ExecutionContext *execution_context) override {
2157       m_dumper_options = {};
2158       m_output_file = std::nullopt;
2159     }
2160 
2161     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2162       return llvm::ArrayRef(g_thread_trace_dump_function_calls_options);
2163     }
2164 
2165     static const size_t kDefaultCount = 20;
2166 
2167     // Instance variables to hold the values for command options.
2168     TraceDumperOptions m_dumper_options;
2169     std::optional<FileSpec> m_output_file;
2170   };
2171 
2172   CommandObjectTraceDumpFunctionCalls(CommandInterpreter &interpreter)
2173       : CommandObjectParsed(
2174             interpreter, "thread trace dump function-calls",
2175             "Dump the traced function-calls for one thread. If no "
2176             "thread is specified, the current thread is used.",
2177             nullptr,
2178             eCommandRequiresProcess | eCommandRequiresThread |
2179                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2180                 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2181     CommandArgumentData thread_arg{eArgTypeThreadIndex, eArgRepeatOptional};
2182     m_arguments.push_back({thread_arg});
2183   }
2184 
2185   ~CommandObjectTraceDumpFunctionCalls() override = default;
2186 
2187   Options *GetOptions() override { return &m_options; }
2188 
2189 protected:
2190   bool DoExecute(Args &args, CommandReturnObject &result) override {
2191     ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2192     if (!thread_sp) {
2193       result.AppendError("invalid thread\n");
2194       return false;
2195     }
2196 
2197     llvm::Expected<TraceCursorSP> cursor_or_error =
2198         m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2199 
2200     if (!cursor_or_error) {
2201       result.AppendError(llvm::toString(cursor_or_error.takeError()));
2202       return false;
2203     }
2204     TraceCursorSP &cursor_sp = *cursor_or_error;
2205 
2206     std::optional<StreamFile> out_file;
2207     if (m_options.m_output_file) {
2208       out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2209                        File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate |
2210                            File::eOpenOptionTruncate);
2211     }
2212 
2213     m_options.m_dumper_options.forwards = true;
2214 
2215     TraceDumper dumper(std::move(cursor_sp),
2216                        out_file ? *out_file : result.GetOutputStream(),
2217                        m_options.m_dumper_options);
2218 
2219     dumper.DumpFunctionCalls();
2220     return true;
2221   }
2222 
2223   CommandOptions m_options;
2224 };
2225 
2226 // CommandObjectTraceDumpInstructions
2227 #define LLDB_OPTIONS_thread_trace_dump_instructions
2228 #include "CommandOptions.inc"
2229 
2230 class CommandObjectTraceDumpInstructions : public CommandObjectParsed {
2231 public:
2232   class CommandOptions : public Options {
2233   public:
2234     CommandOptions() { OptionParsingStarting(nullptr); }
2235 
2236     ~CommandOptions() override = default;
2237 
2238     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2239                           ExecutionContext *execution_context) override {
2240       Status error;
2241       const int short_option = m_getopt_table[option_idx].val;
2242 
2243       switch (short_option) {
2244       case 'c': {
2245         int32_t count;
2246         if (option_arg.empty() || option_arg.getAsInteger(0, count) ||
2247             count < 0)
2248           error.SetErrorStringWithFormat(
2249               "invalid integer value for option '%s'",
2250               option_arg.str().c_str());
2251         else
2252           m_count = count;
2253         break;
2254       }
2255       case 'a': {
2256         m_count = std::numeric_limits<decltype(m_count)>::max();
2257         break;
2258       }
2259       case 's': {
2260         int32_t skip;
2261         if (option_arg.empty() || option_arg.getAsInteger(0, skip) || skip < 0)
2262           error.SetErrorStringWithFormat(
2263               "invalid integer value for option '%s'",
2264               option_arg.str().c_str());
2265         else
2266           m_dumper_options.skip = skip;
2267         break;
2268       }
2269       case 'i': {
2270         uint64_t id;
2271         if (option_arg.empty() || option_arg.getAsInteger(0, id))
2272           error.SetErrorStringWithFormat(
2273               "invalid integer value for option '%s'",
2274               option_arg.str().c_str());
2275         else
2276           m_dumper_options.id = id;
2277         break;
2278       }
2279       case 'F': {
2280         m_output_file.emplace(option_arg);
2281         break;
2282       }
2283       case 'r': {
2284         m_dumper_options.raw = true;
2285         break;
2286       }
2287       case 'f': {
2288         m_dumper_options.forwards = true;
2289         break;
2290       }
2291       case 'k': {
2292         m_dumper_options.show_control_flow_kind = true;
2293         break;
2294       }
2295       case 't': {
2296         m_dumper_options.show_timestamps = true;
2297         break;
2298       }
2299       case 'e': {
2300         m_dumper_options.show_events = true;
2301         break;
2302       }
2303       case 'j': {
2304         m_dumper_options.json = true;
2305         break;
2306       }
2307       case 'J': {
2308         m_dumper_options.pretty_print_json = true;
2309         m_dumper_options.json = true;
2310         break;
2311       }
2312       case 'E': {
2313         m_dumper_options.only_events = true;
2314         m_dumper_options.show_events = true;
2315         break;
2316       }
2317       case 'C': {
2318         m_continue = true;
2319         break;
2320       }
2321       default:
2322         llvm_unreachable("Unimplemented option");
2323       }
2324       return error;
2325     }
2326 
2327     void OptionParsingStarting(ExecutionContext *execution_context) override {
2328       m_count = kDefaultCount;
2329       m_continue = false;
2330       m_output_file = std::nullopt;
2331       m_dumper_options = {};
2332     }
2333 
2334     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2335       return llvm::ArrayRef(g_thread_trace_dump_instructions_options);
2336     }
2337 
2338     static const size_t kDefaultCount = 20;
2339 
2340     // Instance variables to hold the values for command options.
2341     size_t m_count;
2342     size_t m_continue;
2343     std::optional<FileSpec> m_output_file;
2344     TraceDumperOptions m_dumper_options;
2345   };
2346 
2347   CommandObjectTraceDumpInstructions(CommandInterpreter &interpreter)
2348       : CommandObjectParsed(
2349             interpreter, "thread trace dump instructions",
2350             "Dump the traced instructions for one thread. If no "
2351             "thread is specified, show the current thread.",
2352             nullptr,
2353             eCommandRequiresProcess | eCommandRequiresThread |
2354                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
2355                 eCommandProcessMustBePaused | eCommandProcessMustBeTraced) {
2356     CommandArgumentData thread_arg{eArgTypeThreadIndex, eArgRepeatOptional};
2357     m_arguments.push_back({thread_arg});
2358   }
2359 
2360   ~CommandObjectTraceDumpInstructions() override = default;
2361 
2362   Options *GetOptions() override { return &m_options; }
2363 
2364   std::optional<std::string> GetRepeatCommand(Args &current_command_args,
2365                                               uint32_t index) override {
2366     std::string cmd;
2367     current_command_args.GetCommandString(cmd);
2368     if (cmd.find(" --continue") == std::string::npos)
2369       cmd += " --continue";
2370     return cmd;
2371   }
2372 
2373 protected:
2374   bool DoExecute(Args &args, CommandReturnObject &result) override {
2375     ThreadSP thread_sp = GetSingleThreadFromArgs(m_exe_ctx, args, result);
2376     if (!thread_sp) {
2377       result.AppendError("invalid thread\n");
2378       return false;
2379     }
2380 
2381     if (m_options.m_continue && m_last_id) {
2382       // We set up the options to continue one instruction past where
2383       // the previous iteration stopped.
2384       m_options.m_dumper_options.skip = 1;
2385       m_options.m_dumper_options.id = m_last_id;
2386     }
2387 
2388     llvm::Expected<TraceCursorSP> cursor_or_error =
2389         m_exe_ctx.GetTargetSP()->GetTrace()->CreateNewCursor(*thread_sp);
2390 
2391     if (!cursor_or_error) {
2392       result.AppendError(llvm::toString(cursor_or_error.takeError()));
2393       return false;
2394     }
2395     TraceCursorSP &cursor_sp = *cursor_or_error;
2396 
2397     if (m_options.m_dumper_options.id &&
2398         !cursor_sp->HasId(*m_options.m_dumper_options.id)) {
2399       result.AppendError("invalid instruction id\n");
2400       return false;
2401     }
2402 
2403     std::optional<StreamFile> out_file;
2404     if (m_options.m_output_file) {
2405       out_file.emplace(m_options.m_output_file->GetPath().c_str(),
2406                        File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate |
2407                            File::eOpenOptionTruncate);
2408     }
2409 
2410     if (m_options.m_continue && !m_last_id) {
2411       // We need to stop processing data when we already ran out of instructions
2412       // in a previous command. We can fake this by setting the cursor past the
2413       // end of the trace.
2414       cursor_sp->Seek(1, lldb::eTraceCursorSeekTypeEnd);
2415     }
2416 
2417     TraceDumper dumper(std::move(cursor_sp),
2418                        out_file ? *out_file : result.GetOutputStream(),
2419                        m_options.m_dumper_options);
2420 
2421     m_last_id = dumper.DumpInstructions(m_options.m_count);
2422     return true;
2423   }
2424 
2425   CommandOptions m_options;
2426   // Last traversed id used to continue a repeat command. std::nullopt means
2427   // that all the trace has been consumed.
2428   std::optional<lldb::user_id_t> m_last_id;
2429 };
2430 
2431 // CommandObjectTraceDumpInfo
2432 #define LLDB_OPTIONS_thread_trace_dump_info
2433 #include "CommandOptions.inc"
2434 
2435 class CommandObjectTraceDumpInfo : public CommandObjectIterateOverThreads {
2436 public:
2437   class CommandOptions : public Options {
2438   public:
2439     CommandOptions() { OptionParsingStarting(nullptr); }
2440 
2441     ~CommandOptions() override = default;
2442 
2443     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2444                           ExecutionContext *execution_context) override {
2445       Status error;
2446       const int short_option = m_getopt_table[option_idx].val;
2447 
2448       switch (short_option) {
2449       case 'v': {
2450         m_verbose = true;
2451         break;
2452       }
2453       case 'j': {
2454         m_json = true;
2455         break;
2456       }
2457       default:
2458         llvm_unreachable("Unimplemented option");
2459       }
2460       return error;
2461     }
2462 
2463     void OptionParsingStarting(ExecutionContext *execution_context) override {
2464       m_verbose = false;
2465       m_json = false;
2466     }
2467 
2468     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2469       return llvm::ArrayRef(g_thread_trace_dump_info_options);
2470     }
2471 
2472     // Instance variables to hold the values for command options.
2473     bool m_verbose;
2474     bool m_json;
2475   };
2476 
2477   CommandObjectTraceDumpInfo(CommandInterpreter &interpreter)
2478       : CommandObjectIterateOverThreads(
2479             interpreter, "thread trace dump info",
2480             "Dump the traced information for one or more threads.  If no "
2481             "threads are specified, show the current thread. Use the "
2482             "thread-index \"all\" to see all threads.",
2483             nullptr,
2484             eCommandRequiresProcess | eCommandTryTargetAPILock |
2485                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2486                 eCommandProcessMustBeTraced) {}
2487 
2488   ~CommandObjectTraceDumpInfo() override = default;
2489 
2490   Options *GetOptions() override { return &m_options; }
2491 
2492 protected:
2493   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
2494     const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2495     ThreadSP thread_sp =
2496         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2497     trace_sp->DumpTraceInfo(*thread_sp, result.GetOutputStream(),
2498                             m_options.m_verbose, m_options.m_json);
2499     return true;
2500   }
2501 
2502   CommandOptions m_options;
2503 };
2504 
2505 // CommandObjectMultiwordTraceDump
2506 class CommandObjectMultiwordTraceDump : public CommandObjectMultiword {
2507 public:
2508   CommandObjectMultiwordTraceDump(CommandInterpreter &interpreter)
2509       : CommandObjectMultiword(
2510             interpreter, "dump",
2511             "Commands for displaying trace information of the threads "
2512             "in the current process.",
2513             "thread trace dump <subcommand> [<subcommand objects>]") {
2514     LoadSubCommand(
2515         "instructions",
2516         CommandObjectSP(new CommandObjectTraceDumpInstructions(interpreter)));
2517     LoadSubCommand(
2518         "function-calls",
2519         CommandObjectSP(new CommandObjectTraceDumpFunctionCalls(interpreter)));
2520     LoadSubCommand(
2521         "info", CommandObjectSP(new CommandObjectTraceDumpInfo(interpreter)));
2522   }
2523   ~CommandObjectMultiwordTraceDump() override = default;
2524 };
2525 
2526 // CommandObjectMultiwordTrace
2527 class CommandObjectMultiwordTrace : public CommandObjectMultiword {
2528 public:
2529   CommandObjectMultiwordTrace(CommandInterpreter &interpreter)
2530       : CommandObjectMultiword(
2531             interpreter, "trace",
2532             "Commands for operating on traces of the threads in the current "
2533             "process.",
2534             "thread trace <subcommand> [<subcommand objects>]") {
2535     LoadSubCommand("dump", CommandObjectSP(new CommandObjectMultiwordTraceDump(
2536                                interpreter)));
2537     LoadSubCommand("start",
2538                    CommandObjectSP(new CommandObjectTraceStart(interpreter)));
2539     LoadSubCommand("stop",
2540                    CommandObjectSP(new CommandObjectTraceStop(interpreter)));
2541     LoadSubCommand("export",
2542                    CommandObjectSP(new CommandObjectTraceExport(interpreter)));
2543   }
2544 
2545   ~CommandObjectMultiwordTrace() override = default;
2546 };
2547 
2548 // CommandObjectMultiwordThread
2549 
2550 CommandObjectMultiwordThread::CommandObjectMultiwordThread(
2551     CommandInterpreter &interpreter)
2552     : CommandObjectMultiword(interpreter, "thread",
2553                              "Commands for operating on "
2554                              "one or more threads in "
2555                              "the current process.",
2556                              "thread <subcommand> [<subcommand-options>]") {
2557   LoadSubCommand("backtrace", CommandObjectSP(new CommandObjectThreadBacktrace(
2558                                   interpreter)));
2559   LoadSubCommand("continue",
2560                  CommandObjectSP(new CommandObjectThreadContinue(interpreter)));
2561   LoadSubCommand("list",
2562                  CommandObjectSP(new CommandObjectThreadList(interpreter)));
2563   LoadSubCommand("return",
2564                  CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2565   LoadSubCommand("jump",
2566                  CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2567   LoadSubCommand("select",
2568                  CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2569   LoadSubCommand("until",
2570                  CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2571   LoadSubCommand("info",
2572                  CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2573   LoadSubCommand("exception", CommandObjectSP(new CommandObjectThreadException(
2574                                   interpreter)));
2575   LoadSubCommand("siginfo",
2576                  CommandObjectSP(new CommandObjectThreadSiginfo(interpreter)));
2577   LoadSubCommand("step-in",
2578                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2579                      interpreter, "thread step-in",
2580                      "Source level single step, stepping into calls.  Defaults "
2581                      "to current thread unless specified.",
2582                      nullptr, eStepTypeInto, eStepScopeSource)));
2583 
2584   LoadSubCommand("step-out",
2585                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2586                      interpreter, "thread step-out",
2587                      "Finish executing the current stack frame and stop after "
2588                      "returning.  Defaults to current thread unless specified.",
2589                      nullptr, eStepTypeOut, eStepScopeSource)));
2590 
2591   LoadSubCommand("step-over",
2592                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2593                      interpreter, "thread step-over",
2594                      "Source level single step, stepping over calls.  Defaults "
2595                      "to current thread unless specified.",
2596                      nullptr, eStepTypeOver, eStepScopeSource)));
2597 
2598   LoadSubCommand("step-inst",
2599                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2600                      interpreter, "thread step-inst",
2601                      "Instruction level single step, stepping into calls.  "
2602                      "Defaults to current thread unless specified.",
2603                      nullptr, eStepTypeTrace, eStepScopeInstruction)));
2604 
2605   LoadSubCommand("step-inst-over",
2606                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2607                      interpreter, "thread step-inst-over",
2608                      "Instruction level single step, stepping over calls.  "
2609                      "Defaults to current thread unless specified.",
2610                      nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
2611 
2612   LoadSubCommand(
2613       "step-scripted",
2614       CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2615           interpreter, "thread step-scripted",
2616           "Step as instructed by the script class passed in the -C option.  "
2617           "You can also specify a dictionary of key (-k) and value (-v) pairs "
2618           "that will be used to populate an SBStructuredData Dictionary, which "
2619           "will be passed to the constructor of the class implementing the "
2620           "scripted step.  See the Python Reference for more details.",
2621           nullptr, eStepTypeScripted, eStepScopeSource)));
2622 
2623   LoadSubCommand("plan", CommandObjectSP(new CommandObjectMultiwordThreadPlan(
2624                              interpreter)));
2625   LoadSubCommand("trace",
2626                  CommandObjectSP(new CommandObjectMultiwordTrace(interpreter)));
2627 }
2628 
2629 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;
2630