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