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