xref: /llvm-project/lldb/source/Commands/CommandObjectThread.cpp (revision 28c878aeb29a7e7a9ae8f748de6a3c41482b97be)
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 %u.\n",
988             m_options.m_frame_idx, m_options.m_thread_idx);
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 index %u.\n",
1006                                        m_options.m_frame_idx,
1007                                        m_options.m_thread_idx);
1008           return false;
1009         }
1010 
1011         LineEntry function_start;
1012         uint32_t index_ptr = 0, end_ptr;
1013         std::vector<addr_t> address_list;
1014 
1015         // Find the beginning & end index of the function, but first make
1016         // sure it is valid:
1017         if (!sc.function) {
1018           result.AppendErrorWithFormat("Have debug information but no "
1019                                        "function info - can't get until range.");
1020           return false;
1021         }
1022 
1023         AddressRange fun_addr_range = sc.function->GetAddressRange();
1024         Address fun_start_addr = fun_addr_range.GetBaseAddress();
1025         line_table->FindLineEntryByAddress(fun_start_addr, function_start,
1026                                            &index_ptr);
1027 
1028         Address fun_end_addr(fun_start_addr.GetSection(),
1029                              fun_start_addr.GetOffset() +
1030                                  fun_addr_range.GetByteSize());
1031 
1032         bool all_in_function = true;
1033 
1034         line_table->FindLineEntryByAddress(fun_end_addr, function_start,
1035                                            &end_ptr);
1036 
1037         for (uint32_t line_number : line_numbers) {
1038           uint32_t start_idx_ptr = index_ptr;
1039           while (start_idx_ptr <= end_ptr) {
1040             LineEntry line_entry;
1041             const bool exact = false;
1042             start_idx_ptr = sc.comp_unit->FindLineEntry(
1043                 start_idx_ptr, line_number, nullptr, exact, &line_entry);
1044             if (start_idx_ptr == UINT32_MAX)
1045               break;
1046 
1047             addr_t address =
1048                 line_entry.range.GetBaseAddress().GetLoadAddress(target);
1049             if (address != LLDB_INVALID_ADDRESS) {
1050               if (fun_addr_range.ContainsLoadAddress(address, target))
1051                 address_list.push_back(address);
1052               else
1053                 all_in_function = false;
1054             }
1055             start_idx_ptr++;
1056           }
1057         }
1058 
1059         for (lldb::addr_t address : m_options.m_until_addrs) {
1060           if (fun_addr_range.ContainsLoadAddress(address, target))
1061             address_list.push_back(address);
1062           else
1063             all_in_function = false;
1064         }
1065 
1066         if (address_list.empty()) {
1067           if (all_in_function)
1068             result.AppendErrorWithFormat(
1069                 "No line entries matching until target.\n");
1070           else
1071             result.AppendErrorWithFormat(
1072                 "Until target outside of the current function.\n");
1073 
1074           return false;
1075         }
1076 
1077         new_plan_sp = thread->QueueThreadPlanForStepUntil(
1078             abort_other_plans, &address_list.front(), address_list.size(),
1079             m_options.m_stop_others, m_options.m_frame_idx, new_plan_status);
1080         if (new_plan_sp) {
1081           // User level plans should be controlling plans so they can be
1082           // interrupted
1083           // (e.g. by hitting a breakpoint) and other plans executed by the
1084           // user (stepping around the breakpoint) and then a "continue" will
1085           // resume the original plan.
1086           new_plan_sp->SetIsControllingPlan(true);
1087           new_plan_sp->SetOkayToDiscard(false);
1088         } else {
1089           result.SetError(new_plan_status);
1090           return false;
1091         }
1092       } else {
1093         result.AppendErrorWithFormat(
1094             "Frame index %u of thread %u has no debug information.\n",
1095             m_options.m_frame_idx, m_options.m_thread_idx);
1096         return false;
1097       }
1098 
1099       process->GetThreadList().SetSelectedThreadByID(m_options.m_thread_idx);
1100 
1101       StreamString stream;
1102       Status error;
1103       if (synchronous_execution)
1104         error = process->ResumeSynchronous(&stream);
1105       else
1106         error = process->Resume();
1107 
1108       if (error.Success()) {
1109         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
1110                                        process->GetID());
1111         if (synchronous_execution) {
1112           // If any state changed events had anything to say, add that to the
1113           // result
1114           if (stream.GetSize() > 0)
1115             result.AppendMessage(stream.GetString());
1116 
1117           result.SetDidChangeProcessState(true);
1118           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1119         } else {
1120           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
1121         }
1122       } else {
1123         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
1124                                      error.AsCString());
1125       }
1126     }
1127     return result.Succeeded();
1128   }
1129 
1130   CommandOptions m_options;
1131 };
1132 
1133 // CommandObjectThreadSelect
1134 
1135 class CommandObjectThreadSelect : public CommandObjectParsed {
1136 public:
1137   CommandObjectThreadSelect(CommandInterpreter &interpreter)
1138       : CommandObjectParsed(interpreter, "thread select",
1139                             "Change the currently selected thread.", nullptr,
1140                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1141                                 eCommandProcessMustBeLaunched |
1142                                 eCommandProcessMustBePaused) {
1143     CommandArgumentEntry arg;
1144     CommandArgumentData thread_idx_arg;
1145 
1146     // Define the first (and only) variant of this arg.
1147     thread_idx_arg.arg_type = eArgTypeThreadIndex;
1148     thread_idx_arg.arg_repetition = eArgRepeatPlain;
1149 
1150     // There is only one variant this argument could be; put it into the
1151     // argument entry.
1152     arg.push_back(thread_idx_arg);
1153 
1154     // Push the data for the first argument into the m_arguments vector.
1155     m_arguments.push_back(arg);
1156   }
1157 
1158   ~CommandObjectThreadSelect() override = default;
1159 
1160   void
1161   HandleArgumentCompletion(CompletionRequest &request,
1162                            OptionElementVector &opt_element_vector) override {
1163     if (request.GetCursorIndex())
1164       return;
1165 
1166     CommandCompletions::InvokeCommonCompletionCallbacks(
1167         GetCommandInterpreter(), CommandCompletions::eThreadIndexCompletion,
1168         request, nullptr);
1169   }
1170 
1171 protected:
1172   bool DoExecute(Args &command, CommandReturnObject &result) override {
1173     Process *process = m_exe_ctx.GetProcessPtr();
1174     if (process == nullptr) {
1175       result.AppendError("no process");
1176       return false;
1177     } else if (command.GetArgumentCount() != 1) {
1178       result.AppendErrorWithFormat(
1179           "'%s' takes exactly one thread index argument:\nUsage: %s\n",
1180           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1181       return false;
1182     }
1183 
1184     uint32_t index_id;
1185     if (!llvm::to_integer(command.GetArgumentAtIndex(0), index_id)) {
1186       result.AppendErrorWithFormat("Invalid thread index '%s'",
1187                                    command.GetArgumentAtIndex(0));
1188       return false;
1189     }
1190 
1191     Thread *new_thread =
1192         process->GetThreadList().FindThreadByIndexID(index_id).get();
1193     if (new_thread == nullptr) {
1194       result.AppendErrorWithFormat("invalid thread #%s.\n",
1195                                    command.GetArgumentAtIndex(0));
1196       return false;
1197     }
1198 
1199     process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1200     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1201 
1202     return result.Succeeded();
1203   }
1204 };
1205 
1206 // CommandObjectThreadList
1207 
1208 class CommandObjectThreadList : public CommandObjectParsed {
1209 public:
1210   CommandObjectThreadList(CommandInterpreter &interpreter)
1211       : CommandObjectParsed(
1212             interpreter, "thread list",
1213             "Show a summary of each thread in the current target process.  "
1214             "Use 'settings set thread-format' to customize the individual "
1215             "thread listings.",
1216             "thread list",
1217             eCommandRequiresProcess | eCommandTryTargetAPILock |
1218                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1219 
1220   ~CommandObjectThreadList() override = default;
1221 
1222 protected:
1223   bool DoExecute(Args &command, CommandReturnObject &result) override {
1224     Stream &strm = result.GetOutputStream();
1225     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1226     Process *process = m_exe_ctx.GetProcessPtr();
1227     const bool only_threads_with_stop_reason = false;
1228     const uint32_t start_frame = 0;
1229     const uint32_t num_frames = 0;
1230     const uint32_t num_frames_with_source = 0;
1231     process->GetStatus(strm);
1232     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1233                              num_frames, num_frames_with_source, false);
1234     return result.Succeeded();
1235   }
1236 };
1237 
1238 // CommandObjectThreadInfo
1239 #define LLDB_OPTIONS_thread_info
1240 #include "CommandOptions.inc"
1241 
1242 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads {
1243 public:
1244   class CommandOptions : public Options {
1245   public:
1246     CommandOptions() { OptionParsingStarting(nullptr); }
1247 
1248     ~CommandOptions() override = default;
1249 
1250     void OptionParsingStarting(ExecutionContext *execution_context) override {
1251       m_json_thread = false;
1252       m_json_stopinfo = false;
1253     }
1254 
1255     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1256                           ExecutionContext *execution_context) override {
1257       const int short_option = m_getopt_table[option_idx].val;
1258       Status error;
1259 
1260       switch (short_option) {
1261       case 'j':
1262         m_json_thread = true;
1263         break;
1264 
1265       case 's':
1266         m_json_stopinfo = true;
1267         break;
1268 
1269       default:
1270         llvm_unreachable("Unimplemented option");
1271       }
1272       return error;
1273     }
1274 
1275     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1276       return llvm::makeArrayRef(g_thread_info_options);
1277     }
1278 
1279     bool m_json_thread;
1280     bool m_json_stopinfo;
1281   };
1282 
1283   CommandObjectThreadInfo(CommandInterpreter &interpreter)
1284       : CommandObjectIterateOverThreads(
1285             interpreter, "thread info",
1286             "Show an extended summary of one or "
1287             "more threads.  Defaults to the "
1288             "current thread.",
1289             "thread info",
1290             eCommandRequiresProcess | eCommandTryTargetAPILock |
1291                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1292     m_add_return = false;
1293   }
1294 
1295   ~CommandObjectThreadInfo() override = default;
1296 
1297   void
1298   HandleArgumentCompletion(CompletionRequest &request,
1299                            OptionElementVector &opt_element_vector) override {
1300     CommandCompletions::InvokeCommonCompletionCallbacks(
1301         GetCommandInterpreter(), CommandCompletions::eThreadIndexCompletion,
1302         request, nullptr);
1303   }
1304 
1305   Options *GetOptions() override { return &m_options; }
1306 
1307   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1308     ThreadSP thread_sp =
1309         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1310     if (!thread_sp) {
1311       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1312                                    tid);
1313       return false;
1314     }
1315 
1316     Thread *thread = thread_sp.get();
1317 
1318     Stream &strm = result.GetOutputStream();
1319     if (!thread->GetDescription(strm, eDescriptionLevelFull,
1320                                 m_options.m_json_thread,
1321                                 m_options.m_json_stopinfo)) {
1322       result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1323                                    thread->GetIndexID());
1324       return false;
1325     }
1326     return true;
1327   }
1328 
1329   CommandOptions m_options;
1330 };
1331 
1332 // CommandObjectThreadException
1333 
1334 class CommandObjectThreadException : public CommandObjectIterateOverThreads {
1335 public:
1336   CommandObjectThreadException(CommandInterpreter &interpreter)
1337       : CommandObjectIterateOverThreads(
1338             interpreter, "thread exception",
1339             "Display the current exception object for a thread. Defaults to "
1340             "the current thread.",
1341             "thread exception",
1342             eCommandRequiresProcess | eCommandTryTargetAPILock |
1343                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1344 
1345   ~CommandObjectThreadException() override = default;
1346 
1347   void
1348   HandleArgumentCompletion(CompletionRequest &request,
1349                            OptionElementVector &opt_element_vector) override {
1350     CommandCompletions::InvokeCommonCompletionCallbacks(
1351         GetCommandInterpreter(), CommandCompletions::eThreadIndexCompletion,
1352         request, nullptr);
1353   }
1354 
1355   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1356     ThreadSP thread_sp =
1357         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1358     if (!thread_sp) {
1359       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1360                                    tid);
1361       return false;
1362     }
1363 
1364     Stream &strm = result.GetOutputStream();
1365     ValueObjectSP exception_object_sp = thread_sp->GetCurrentException();
1366     if (exception_object_sp) {
1367       exception_object_sp->Dump(strm);
1368     }
1369 
1370     ThreadSP exception_thread_sp = thread_sp->GetCurrentExceptionBacktrace();
1371     if (exception_thread_sp && exception_thread_sp->IsValid()) {
1372       const uint32_t num_frames_with_source = 0;
1373       const bool stop_format = false;
1374       exception_thread_sp->GetStatus(strm, 0, UINT32_MAX,
1375                                      num_frames_with_source, stop_format);
1376     }
1377 
1378     return true;
1379   }
1380 };
1381 
1382 class CommandObjectThreadSiginfo : public CommandObjectIterateOverThreads {
1383 public:
1384   CommandObjectThreadSiginfo(CommandInterpreter &interpreter)
1385       : CommandObjectIterateOverThreads(
1386             interpreter, "thread siginfo",
1387             "Display the current siginfo object for a thread. Defaults to "
1388             "the current thread.",
1389             "thread siginfo",
1390             eCommandRequiresProcess | eCommandTryTargetAPILock |
1391                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1392 
1393   ~CommandObjectThreadSiginfo() override = default;
1394 
1395   void
1396   HandleArgumentCompletion(CompletionRequest &request,
1397                            OptionElementVector &opt_element_vector) override {
1398     CommandCompletions::InvokeCommonCompletionCallbacks(
1399         GetCommandInterpreter(), CommandCompletions::eThreadIndexCompletion,
1400         request, nullptr);
1401   }
1402 
1403   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1404     ThreadSP thread_sp =
1405         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1406     if (!thread_sp) {
1407       result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n",
1408                                    tid);
1409       return false;
1410     }
1411 
1412     Stream &strm = result.GetOutputStream();
1413     if (!thread_sp->GetDescription(strm, eDescriptionLevelFull, false, false)) {
1414       result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n",
1415                                    thread_sp->GetIndexID());
1416       return false;
1417     }
1418     ValueObjectSP exception_object_sp = thread_sp->GetSiginfoValue();
1419     if (exception_object_sp)
1420       exception_object_sp->Dump(strm);
1421     else
1422       strm.Printf("(no siginfo)\n");
1423     strm.PutChar('\n');
1424 
1425     return true;
1426   }
1427 };
1428 
1429 // CommandObjectThreadReturn
1430 #define LLDB_OPTIONS_thread_return
1431 #include "CommandOptions.inc"
1432 
1433 class CommandObjectThreadReturn : public CommandObjectRaw {
1434 public:
1435   class CommandOptions : public Options {
1436   public:
1437     CommandOptions() {
1438       // Keep default values of all options in one place: OptionParsingStarting
1439       // ()
1440       OptionParsingStarting(nullptr);
1441     }
1442 
1443     ~CommandOptions() override = default;
1444 
1445     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1446                           ExecutionContext *execution_context) override {
1447       Status error;
1448       const int short_option = m_getopt_table[option_idx].val;
1449 
1450       switch (short_option) {
1451       case 'x': {
1452         bool success;
1453         bool tmp_value =
1454             OptionArgParser::ToBoolean(option_arg, false, &success);
1455         if (success)
1456           m_from_expression = tmp_value;
1457         else {
1458           error.SetErrorStringWithFormat(
1459               "invalid boolean value '%s' for 'x' option",
1460               option_arg.str().c_str());
1461         }
1462       } break;
1463       default:
1464         llvm_unreachable("Unimplemented option");
1465       }
1466       return error;
1467     }
1468 
1469     void OptionParsingStarting(ExecutionContext *execution_context) override {
1470       m_from_expression = false;
1471     }
1472 
1473     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1474       return llvm::makeArrayRef(g_thread_return_options);
1475     }
1476 
1477     bool m_from_expression = false;
1478 
1479     // Instance variables to hold the values for command options.
1480   };
1481 
1482   CommandObjectThreadReturn(CommandInterpreter &interpreter)
1483       : CommandObjectRaw(interpreter, "thread return",
1484                          "Prematurely return from a stack frame, "
1485                          "short-circuiting execution of newer frames "
1486                          "and optionally yielding a specified value.  Defaults "
1487                          "to the exiting the current stack "
1488                          "frame.",
1489                          "thread return",
1490                          eCommandRequiresFrame | eCommandTryTargetAPILock |
1491                              eCommandProcessMustBeLaunched |
1492                              eCommandProcessMustBePaused) {
1493     CommandArgumentEntry arg;
1494     CommandArgumentData expression_arg;
1495 
1496     // Define the first (and only) variant of this arg.
1497     expression_arg.arg_type = eArgTypeExpression;
1498     expression_arg.arg_repetition = eArgRepeatOptional;
1499 
1500     // There is only one variant this argument could be; put it into the
1501     // argument entry.
1502     arg.push_back(expression_arg);
1503 
1504     // Push the data for the first argument into the m_arguments vector.
1505     m_arguments.push_back(arg);
1506   }
1507 
1508   ~CommandObjectThreadReturn() override = default;
1509 
1510   Options *GetOptions() override { return &m_options; }
1511 
1512 protected:
1513   bool DoExecute(llvm::StringRef command,
1514                  CommandReturnObject &result) override {
1515     // I am going to handle this by hand, because I don't want you to have to
1516     // say:
1517     // "thread return -- -5".
1518     if (command.startswith("-x")) {
1519       if (command.size() != 2U)
1520         result.AppendWarning("Return values ignored when returning from user "
1521                              "called expressions");
1522 
1523       Thread *thread = m_exe_ctx.GetThreadPtr();
1524       Status error;
1525       error = thread->UnwindInnermostExpression();
1526       if (!error.Success()) {
1527         result.AppendErrorWithFormat("Unwinding expression failed - %s.",
1528                                      error.AsCString());
1529       } else {
1530         bool success =
1531             thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream());
1532         if (success) {
1533           m_exe_ctx.SetFrameSP(thread->GetSelectedFrame());
1534           result.SetStatus(eReturnStatusSuccessFinishResult);
1535         } else {
1536           result.AppendErrorWithFormat(
1537               "Could not select 0th frame after unwinding expression.");
1538         }
1539       }
1540       return result.Succeeded();
1541     }
1542 
1543     ValueObjectSP return_valobj_sp;
1544 
1545     StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1546     uint32_t frame_idx = frame_sp->GetFrameIndex();
1547 
1548     if (frame_sp->IsInlined()) {
1549       result.AppendError("Don't know how to return from inlined frames.");
1550       return false;
1551     }
1552 
1553     if (!command.empty()) {
1554       Target *target = m_exe_ctx.GetTargetPtr();
1555       EvaluateExpressionOptions options;
1556 
1557       options.SetUnwindOnError(true);
1558       options.SetUseDynamic(eNoDynamicValues);
1559 
1560       ExpressionResults exe_results = eExpressionSetupError;
1561       exe_results = target->EvaluateExpression(command, frame_sp.get(),
1562                                                return_valobj_sp, options);
1563       if (exe_results != eExpressionCompleted) {
1564         if (return_valobj_sp)
1565           result.AppendErrorWithFormat(
1566               "Error evaluating result expression: %s",
1567               return_valobj_sp->GetError().AsCString());
1568         else
1569           result.AppendErrorWithFormat(
1570               "Unknown error evaluating result expression.");
1571         return false;
1572       }
1573     }
1574 
1575     Status error;
1576     ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1577     const bool broadcast = true;
1578     error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast);
1579     if (!error.Success()) {
1580       result.AppendErrorWithFormat(
1581           "Error returning from frame %d of thread %d: %s.", frame_idx,
1582           thread_sp->GetIndexID(), error.AsCString());
1583       return false;
1584     }
1585 
1586     result.SetStatus(eReturnStatusSuccessFinishResult);
1587     return true;
1588   }
1589 
1590   CommandOptions m_options;
1591 };
1592 
1593 // CommandObjectThreadJump
1594 #define LLDB_OPTIONS_thread_jump
1595 #include "CommandOptions.inc"
1596 
1597 class CommandObjectThreadJump : public CommandObjectParsed {
1598 public:
1599   class CommandOptions : public Options {
1600   public:
1601     CommandOptions() { OptionParsingStarting(nullptr); }
1602 
1603     ~CommandOptions() override = default;
1604 
1605     void OptionParsingStarting(ExecutionContext *execution_context) override {
1606       m_filenames.Clear();
1607       m_line_num = 0;
1608       m_line_offset = 0;
1609       m_load_addr = LLDB_INVALID_ADDRESS;
1610       m_force = false;
1611     }
1612 
1613     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1614                           ExecutionContext *execution_context) override {
1615       const int short_option = m_getopt_table[option_idx].val;
1616       Status error;
1617 
1618       switch (short_option) {
1619       case 'f':
1620         m_filenames.AppendIfUnique(FileSpec(option_arg));
1621         if (m_filenames.GetSize() > 1)
1622           return Status("only one source file expected.");
1623         break;
1624       case 'l':
1625         if (option_arg.getAsInteger(0, m_line_num))
1626           return Status("invalid line number: '%s'.", option_arg.str().c_str());
1627         break;
1628       case 'b':
1629         if (option_arg.getAsInteger(0, m_line_offset))
1630           return Status("invalid line offset: '%s'.", option_arg.str().c_str());
1631         break;
1632       case 'a':
1633         m_load_addr = OptionArgParser::ToAddress(execution_context, option_arg,
1634                                                  LLDB_INVALID_ADDRESS, &error);
1635         break;
1636       case 'r':
1637         m_force = true;
1638         break;
1639       default:
1640         llvm_unreachable("Unimplemented option");
1641       }
1642       return error;
1643     }
1644 
1645     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1646       return llvm::makeArrayRef(g_thread_jump_options);
1647     }
1648 
1649     FileSpecList m_filenames;
1650     uint32_t m_line_num;
1651     int32_t m_line_offset;
1652     lldb::addr_t m_load_addr;
1653     bool m_force;
1654   };
1655 
1656   CommandObjectThreadJump(CommandInterpreter &interpreter)
1657       : CommandObjectParsed(
1658             interpreter, "thread jump",
1659             "Sets the program counter to a new address.", "thread jump",
1660             eCommandRequiresFrame | eCommandTryTargetAPILock |
1661                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1662 
1663   ~CommandObjectThreadJump() override = default;
1664 
1665   Options *GetOptions() override { return &m_options; }
1666 
1667 protected:
1668   bool DoExecute(Args &args, CommandReturnObject &result) override {
1669     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1670     StackFrame *frame = m_exe_ctx.GetFramePtr();
1671     Thread *thread = m_exe_ctx.GetThreadPtr();
1672     Target *target = m_exe_ctx.GetTargetPtr();
1673     const SymbolContext &sym_ctx =
1674         frame->GetSymbolContext(eSymbolContextLineEntry);
1675 
1676     if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) {
1677       // Use this address directly.
1678       Address dest = Address(m_options.m_load_addr);
1679 
1680       lldb::addr_t callAddr = dest.GetCallableLoadAddress(target);
1681       if (callAddr == LLDB_INVALID_ADDRESS) {
1682         result.AppendErrorWithFormat("Invalid destination address.");
1683         return false;
1684       }
1685 
1686       if (!reg_ctx->SetPC(callAddr)) {
1687         result.AppendErrorWithFormat("Error changing PC value for thread %d.",
1688                                      thread->GetIndexID());
1689         return false;
1690       }
1691     } else {
1692       // Pick either the absolute line, or work out a relative one.
1693       int32_t line = (int32_t)m_options.m_line_num;
1694       if (line == 0)
1695         line = sym_ctx.line_entry.line + m_options.m_line_offset;
1696 
1697       // Try the current file, but override if asked.
1698       FileSpec file = sym_ctx.line_entry.file;
1699       if (m_options.m_filenames.GetSize() == 1)
1700         file = m_options.m_filenames.GetFileSpecAtIndex(0);
1701 
1702       if (!file) {
1703         result.AppendErrorWithFormat(
1704             "No source file available for the current location.");
1705         return false;
1706       }
1707 
1708       std::string warnings;
1709       Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings);
1710 
1711       if (err.Fail()) {
1712         result.SetError(err);
1713         return false;
1714       }
1715 
1716       if (!warnings.empty())
1717         result.AppendWarning(warnings.c_str());
1718     }
1719 
1720     result.SetStatus(eReturnStatusSuccessFinishResult);
1721     return true;
1722   }
1723 
1724   CommandOptions m_options;
1725 };
1726 
1727 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1728 
1729 // CommandObjectThreadPlanList
1730 #define LLDB_OPTIONS_thread_plan_list
1731 #include "CommandOptions.inc"
1732 
1733 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads {
1734 public:
1735   class CommandOptions : public Options {
1736   public:
1737     CommandOptions() {
1738       // Keep default values of all options in one place: OptionParsingStarting
1739       // ()
1740       OptionParsingStarting(nullptr);
1741     }
1742 
1743     ~CommandOptions() override = default;
1744 
1745     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1746                           ExecutionContext *execution_context) override {
1747       const int short_option = m_getopt_table[option_idx].val;
1748 
1749       switch (short_option) {
1750       case 'i':
1751         m_internal = true;
1752         break;
1753       case 't':
1754         lldb::tid_t tid;
1755         if (option_arg.getAsInteger(0, tid))
1756           return Status("invalid tid: '%s'.", option_arg.str().c_str());
1757         m_tids.push_back(tid);
1758         break;
1759       case 'u':
1760         m_unreported = false;
1761         break;
1762       case 'v':
1763         m_verbose = true;
1764         break;
1765       default:
1766         llvm_unreachable("Unimplemented option");
1767       }
1768       return {};
1769     }
1770 
1771     void OptionParsingStarting(ExecutionContext *execution_context) override {
1772       m_verbose = false;
1773       m_internal = false;
1774       m_unreported = true; // The variable is "skip unreported" and we want to
1775                            // skip unreported by default.
1776       m_tids.clear();
1777     }
1778 
1779     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1780       return llvm::makeArrayRef(g_thread_plan_list_options);
1781     }
1782 
1783     // Instance variables to hold the values for command options.
1784     bool m_verbose;
1785     bool m_internal;
1786     bool m_unreported;
1787     std::vector<lldb::tid_t> m_tids;
1788   };
1789 
1790   CommandObjectThreadPlanList(CommandInterpreter &interpreter)
1791       : CommandObjectIterateOverThreads(
1792             interpreter, "thread plan list",
1793             "Show thread plans for one or more threads.  If no threads are "
1794             "specified, show the "
1795             "current thread.  Use the thread-index \"all\" to see all threads.",
1796             nullptr,
1797             eCommandRequiresProcess | eCommandRequiresThread |
1798                 eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1799                 eCommandProcessMustBePaused) {}
1800 
1801   ~CommandObjectThreadPlanList() override = default;
1802 
1803   Options *GetOptions() override { return &m_options; }
1804 
1805   bool DoExecute(Args &command, CommandReturnObject &result) override {
1806     // If we are reporting all threads, dispatch to the Process to do that:
1807     if (command.GetArgumentCount() == 0 && m_options.m_tids.empty()) {
1808       Stream &strm = result.GetOutputStream();
1809       DescriptionLevel desc_level = m_options.m_verbose
1810                                         ? eDescriptionLevelVerbose
1811                                         : eDescriptionLevelFull;
1812       m_exe_ctx.GetProcessPtr()->DumpThreadPlans(
1813           strm, desc_level, m_options.m_internal, true, m_options.m_unreported);
1814       result.SetStatus(eReturnStatusSuccessFinishResult);
1815       return true;
1816     } else {
1817       // Do any TID's that the user may have specified as TID, then do any
1818       // Thread Indexes...
1819       if (!m_options.m_tids.empty()) {
1820         Process *process = m_exe_ctx.GetProcessPtr();
1821         StreamString tmp_strm;
1822         for (lldb::tid_t tid : m_options.m_tids) {
1823           bool success = process->DumpThreadPlansForTID(
1824               tmp_strm, tid, eDescriptionLevelFull, m_options.m_internal,
1825               true /* condense_trivial */, m_options.m_unreported);
1826           // If we didn't find a TID, stop here and return an error.
1827           if (!success) {
1828             result.AppendError("Error dumping plans:");
1829             result.AppendError(tmp_strm.GetString());
1830             return false;
1831           }
1832           // Otherwise, add our data to the output:
1833           result.GetOutputStream() << tmp_strm.GetString();
1834         }
1835       }
1836       return CommandObjectIterateOverThreads::DoExecute(command, result);
1837     }
1838   }
1839 
1840 protected:
1841   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
1842     // If we have already handled this from a -t option, skip it here.
1843     if (llvm::is_contained(m_options.m_tids, tid))
1844       return true;
1845 
1846     Process *process = m_exe_ctx.GetProcessPtr();
1847 
1848     Stream &strm = result.GetOutputStream();
1849     DescriptionLevel desc_level = eDescriptionLevelFull;
1850     if (m_options.m_verbose)
1851       desc_level = eDescriptionLevelVerbose;
1852 
1853     process->DumpThreadPlansForTID(strm, tid, desc_level, m_options.m_internal,
1854                                    true /* condense_trivial */,
1855                                    m_options.m_unreported);
1856     return true;
1857   }
1858 
1859   CommandOptions m_options;
1860 };
1861 
1862 class CommandObjectThreadPlanDiscard : public CommandObjectParsed {
1863 public:
1864   CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
1865       : CommandObjectParsed(interpreter, "thread plan discard",
1866                             "Discards thread plans up to and including the "
1867                             "specified index (see 'thread plan list'.)  "
1868                             "Only user visible plans can be discarded.",
1869                             nullptr,
1870                             eCommandRequiresProcess | eCommandRequiresThread |
1871                                 eCommandTryTargetAPILock |
1872                                 eCommandProcessMustBeLaunched |
1873                                 eCommandProcessMustBePaused) {
1874     CommandArgumentEntry arg;
1875     CommandArgumentData plan_index_arg;
1876 
1877     // Define the first (and only) variant of this arg.
1878     plan_index_arg.arg_type = eArgTypeUnsignedInteger;
1879     plan_index_arg.arg_repetition = eArgRepeatPlain;
1880 
1881     // There is only one variant this argument could be; put it into the
1882     // argument entry.
1883     arg.push_back(plan_index_arg);
1884 
1885     // Push the data for the first argument into the m_arguments vector.
1886     m_arguments.push_back(arg);
1887   }
1888 
1889   ~CommandObjectThreadPlanDiscard() override = default;
1890 
1891   void
1892   HandleArgumentCompletion(CompletionRequest &request,
1893                            OptionElementVector &opt_element_vector) override {
1894     if (!m_exe_ctx.HasThreadScope() || request.GetCursorIndex())
1895       return;
1896 
1897     m_exe_ctx.GetThreadPtr()->AutoCompleteThreadPlans(request);
1898   }
1899 
1900   bool DoExecute(Args &args, CommandReturnObject &result) override {
1901     Thread *thread = m_exe_ctx.GetThreadPtr();
1902     if (args.GetArgumentCount() != 1) {
1903       result.AppendErrorWithFormat("Too many arguments, expected one - the "
1904                                    "thread plan index - but got %zu.",
1905                                    args.GetArgumentCount());
1906       return false;
1907     }
1908 
1909     uint32_t thread_plan_idx;
1910     if (!llvm::to_integer(args.GetArgumentAtIndex(0), thread_plan_idx)) {
1911       result.AppendErrorWithFormat(
1912           "Invalid thread index: \"%s\" - should be unsigned int.",
1913           args.GetArgumentAtIndex(0));
1914       return false;
1915     }
1916 
1917     if (thread_plan_idx == 0) {
1918       result.AppendErrorWithFormat(
1919           "You wouldn't really want me to discard the base thread plan.");
1920       return false;
1921     }
1922 
1923     if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) {
1924       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1925       return true;
1926     } else {
1927       result.AppendErrorWithFormat(
1928           "Could not find User thread plan with index %s.",
1929           args.GetArgumentAtIndex(0));
1930       return false;
1931     }
1932   }
1933 };
1934 
1935 class CommandObjectThreadPlanPrune : public CommandObjectParsed {
1936 public:
1937   CommandObjectThreadPlanPrune(CommandInterpreter &interpreter)
1938       : CommandObjectParsed(interpreter, "thread plan prune",
1939                             "Removes any thread plans associated with "
1940                             "currently unreported threads.  "
1941                             "Specify one or more TID's to remove, or if no "
1942                             "TID's are provides, remove threads for all "
1943                             "unreported threads",
1944                             nullptr,
1945                             eCommandRequiresProcess |
1946                                 eCommandTryTargetAPILock |
1947                                 eCommandProcessMustBeLaunched |
1948                                 eCommandProcessMustBePaused) {
1949     CommandArgumentEntry arg;
1950     CommandArgumentData tid_arg;
1951 
1952     // Define the first (and only) variant of this arg.
1953     tid_arg.arg_type = eArgTypeThreadID;
1954     tid_arg.arg_repetition = eArgRepeatStar;
1955 
1956     // There is only one variant this argument could be; put it into the
1957     // argument entry.
1958     arg.push_back(tid_arg);
1959 
1960     // Push the data for the first argument into the m_arguments vector.
1961     m_arguments.push_back(arg);
1962   }
1963 
1964   ~CommandObjectThreadPlanPrune() override = default;
1965 
1966   bool DoExecute(Args &args, CommandReturnObject &result) override {
1967     Process *process = m_exe_ctx.GetProcessPtr();
1968 
1969     if (args.GetArgumentCount() == 0) {
1970       process->PruneThreadPlans();
1971       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1972       return true;
1973     }
1974 
1975     const size_t num_args = args.GetArgumentCount();
1976 
1977     std::lock_guard<std::recursive_mutex> guard(
1978         process->GetThreadList().GetMutex());
1979 
1980     for (size_t i = 0; i < num_args; i++) {
1981       lldb::tid_t tid;
1982       if (!llvm::to_integer(args.GetArgumentAtIndex(i), tid)) {
1983         result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n",
1984                                      args.GetArgumentAtIndex(i));
1985         return false;
1986       }
1987       if (!process->PruneThreadPlansForTID(tid)) {
1988         result.AppendErrorWithFormat("Could not find unreported tid: \"%s\"\n",
1989                                      args.GetArgumentAtIndex(i));
1990         return false;
1991       }
1992     }
1993     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1994     return true;
1995   }
1996 };
1997 
1998 // CommandObjectMultiwordThreadPlan
1999 
2000 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword {
2001 public:
2002   CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
2003       : CommandObjectMultiword(
2004             interpreter, "plan",
2005             "Commands for managing thread plans that control execution.",
2006             "thread plan <subcommand> [<subcommand objects]") {
2007     LoadSubCommand(
2008         "list", CommandObjectSP(new CommandObjectThreadPlanList(interpreter)));
2009     LoadSubCommand(
2010         "discard",
2011         CommandObjectSP(new CommandObjectThreadPlanDiscard(interpreter)));
2012     LoadSubCommand(
2013         "prune",
2014         CommandObjectSP(new CommandObjectThreadPlanPrune(interpreter)));
2015   }
2016 
2017   ~CommandObjectMultiwordThreadPlan() override = default;
2018 };
2019 
2020 // Next are the subcommands of CommandObjectMultiwordTrace
2021 
2022 // CommandObjectTraceExport
2023 
2024 class CommandObjectTraceExport : public CommandObjectMultiword {
2025 public:
2026   CommandObjectTraceExport(CommandInterpreter &interpreter)
2027       : CommandObjectMultiword(
2028             interpreter, "trace thread export",
2029             "Commands for exporting traces of the threads in the current "
2030             "process to different formats.",
2031             "thread trace export <export-plugin> [<subcommand objects>]") {
2032 
2033     unsigned i = 0;
2034     for (llvm::StringRef plugin_name =
2035              PluginManager::GetTraceExporterPluginNameAtIndex(i++);
2036          !plugin_name.empty();
2037          plugin_name = PluginManager::GetTraceExporterPluginNameAtIndex(i++)) {
2038       if (ThreadTraceExportCommandCreator command_creator =
2039               PluginManager::GetThreadTraceExportCommandCreatorAtIndex(i)) {
2040         LoadSubCommand(plugin_name, command_creator(interpreter));
2041       }
2042     }
2043   }
2044 };
2045 
2046 // CommandObjectTraceStart
2047 
2048 class CommandObjectTraceStart : public CommandObjectTraceProxy {
2049 public:
2050   CommandObjectTraceStart(CommandInterpreter &interpreter)
2051       : CommandObjectTraceProxy(
2052             /*live_debug_session_only=*/true, interpreter, "thread trace start",
2053             "Start tracing threads with the corresponding trace "
2054             "plug-in for the current process.",
2055             "thread trace start [<trace-options>]") {}
2056 
2057 protected:
2058   lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
2059     return trace.GetThreadTraceStartCommand(m_interpreter);
2060   }
2061 };
2062 
2063 // CommandObjectTraceStop
2064 
2065 class CommandObjectTraceStop : public CommandObjectMultipleThreads {
2066 public:
2067   CommandObjectTraceStop(CommandInterpreter &interpreter)
2068       : CommandObjectMultipleThreads(
2069             interpreter, "thread trace stop",
2070             "Stop tracing threads, including the ones traced with the "
2071             "\"process trace start\" command."
2072             "Defaults to the current thread. Thread indices can be "
2073             "specified as arguments.\n Use the thread-index \"all\" to stop "
2074             "tracing "
2075             "for all existing threads.",
2076             "thread trace stop [<thread-index> <thread-index> ...]",
2077             eCommandRequiresProcess | eCommandTryTargetAPILock |
2078                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2079                 eCommandProcessMustBeTraced) {}
2080 
2081   ~CommandObjectTraceStop() override = default;
2082 
2083   bool DoExecuteOnThreads(Args &command, CommandReturnObject &result,
2084                           llvm::ArrayRef<lldb::tid_t> tids) override {
2085     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2086 
2087     TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2088 
2089     if (llvm::Error err = trace_sp->Stop(tids))
2090       result.AppendError(toString(std::move(err)));
2091     else
2092       result.SetStatus(eReturnStatusSuccessFinishResult);
2093 
2094     return result.Succeeded();
2095   }
2096 };
2097 
2098 // CommandObjectTraceDumpInstructions
2099 #define LLDB_OPTIONS_thread_trace_dump_instructions
2100 #include "CommandOptions.inc"
2101 
2102 class CommandObjectTraceDumpInstructions
2103     : public CommandObjectIterateOverThreads {
2104 public:
2105   class CommandOptions : public Options {
2106   public:
2107     CommandOptions() { OptionParsingStarting(nullptr); }
2108 
2109     ~CommandOptions() override = default;
2110 
2111     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2112                           ExecutionContext *execution_context) override {
2113       Status error;
2114       const int short_option = m_getopt_table[option_idx].val;
2115 
2116       switch (short_option) {
2117       case 'c': {
2118         int32_t count;
2119         if (option_arg.empty() || option_arg.getAsInteger(0, count) ||
2120             count < 0)
2121           error.SetErrorStringWithFormat(
2122               "invalid integer value for option '%s'",
2123               option_arg.str().c_str());
2124         else
2125           m_count = count;
2126         break;
2127       }
2128       case 's': {
2129         int32_t skip;
2130         if (option_arg.empty() || option_arg.getAsInteger(0, skip) || skip < 0)
2131           error.SetErrorStringWithFormat(
2132               "invalid integer value for option '%s'",
2133               option_arg.str().c_str());
2134         else
2135           m_skip = skip;
2136         break;
2137       }
2138       case 'r': {
2139         m_raw = true;
2140         break;
2141       }
2142       case 'f': {
2143         m_forwards = true;
2144         break;
2145       }
2146       case 't': {
2147         m_show_tsc = true;
2148         break;
2149       }
2150       default:
2151         llvm_unreachable("Unimplemented option");
2152       }
2153       return error;
2154     }
2155 
2156     void OptionParsingStarting(ExecutionContext *execution_context) override {
2157       m_count = kDefaultCount;
2158       m_skip = 0;
2159       m_raw = false;
2160       m_forwards = false;
2161       m_show_tsc = false;
2162     }
2163 
2164     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2165       return llvm::makeArrayRef(g_thread_trace_dump_instructions_options);
2166     }
2167 
2168     static const size_t kDefaultCount = 20;
2169 
2170     // Instance variables to hold the values for command options.
2171     size_t m_count;
2172     size_t m_skip;
2173     bool m_raw;
2174     bool m_forwards;
2175     bool m_show_tsc;
2176   };
2177 
2178   CommandObjectTraceDumpInstructions(CommandInterpreter &interpreter)
2179       : CommandObjectIterateOverThreads(
2180             interpreter, "thread trace dump instructions",
2181             "Dump the traced instructions for one or more threads. If no "
2182             "threads are specified, show the current thread.  Use the "
2183             "thread-index \"all\" to see all threads.",
2184             nullptr,
2185             eCommandRequiresProcess | eCommandTryTargetAPILock |
2186                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2187                 eCommandProcessMustBeTraced) {}
2188 
2189   ~CommandObjectTraceDumpInstructions() override = default;
2190 
2191   Options *GetOptions() override { return &m_options; }
2192 
2193   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
2194                                                uint32_t index) override {
2195     current_command_args.GetCommandString(m_repeat_command);
2196     m_create_repeat_command_just_invoked = true;
2197     return m_repeat_command;
2198   }
2199 
2200 protected:
2201   bool DoExecute(Args &args, CommandReturnObject &result) override {
2202     if (!IsRepeatCommand())
2203       m_dumpers.clear();
2204 
2205     bool status = CommandObjectIterateOverThreads::DoExecute(args, result);
2206 
2207     m_create_repeat_command_just_invoked = false;
2208     return status;
2209   }
2210 
2211   bool IsRepeatCommand() {
2212     return !m_repeat_command.empty() && !m_create_repeat_command_just_invoked;
2213   }
2214 
2215   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
2216     Stream &s = result.GetOutputStream();
2217 
2218     const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2219     ThreadSP thread_sp =
2220         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2221 
2222     if (!m_dumpers.count(thread_sp->GetID())) {
2223       lldb::TraceCursorUP cursor_up = trace_sp->GetCursor(*thread_sp);
2224       // Set up the cursor and return the presentation index of the first
2225       // instruction to dump after skipping instructions.
2226       auto setUpCursor = [&]() {
2227         cursor_up->SetForwards(m_options.m_forwards);
2228         if (m_options.m_forwards)
2229           return cursor_up->Seek(m_options.m_skip, TraceCursor::SeekType::Set);
2230         return -cursor_up->Seek(-m_options.m_skip, TraceCursor::SeekType::End);
2231       };
2232 
2233       int initial_index = setUpCursor();
2234 
2235       auto dumper = std::make_unique<TraceInstructionDumper>(
2236           std::move(cursor_up), initial_index, m_options.m_raw,
2237           m_options.m_show_tsc);
2238 
2239       // This happens when the seek value was more than the number of available
2240       // instructions.
2241       if (std::abs(initial_index) < (int)m_options.m_skip)
2242         dumper->SetNoMoreData();
2243 
2244       m_dumpers[thread_sp->GetID()] = std::move(dumper);
2245     }
2246 
2247     m_dumpers[thread_sp->GetID()]->DumpInstructions(s, m_options.m_count);
2248     return true;
2249   }
2250 
2251   CommandOptions m_options;
2252 
2253   // Repeat command helpers
2254   std::string m_repeat_command;
2255   bool m_create_repeat_command_just_invoked = false;
2256   std::map<lldb::tid_t, std::unique_ptr<TraceInstructionDumper>> m_dumpers;
2257 };
2258 
2259 // CommandObjectTraceDumpInfo
2260 #define LLDB_OPTIONS_thread_trace_dump_info
2261 #include "CommandOptions.inc"
2262 
2263 class CommandObjectTraceDumpInfo : public CommandObjectIterateOverThreads {
2264 public:
2265   class CommandOptions : public Options {
2266   public:
2267     CommandOptions() { OptionParsingStarting(nullptr); }
2268 
2269     ~CommandOptions() override = default;
2270 
2271     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
2272                           ExecutionContext *execution_context) override {
2273       Status error;
2274       const int short_option = m_getopt_table[option_idx].val;
2275 
2276       switch (short_option) {
2277       case 'v': {
2278         m_verbose = true;
2279         break;
2280       }
2281       default:
2282         llvm_unreachable("Unimplemented option");
2283       }
2284       return error;
2285     }
2286 
2287     void OptionParsingStarting(ExecutionContext *execution_context) override {
2288       m_verbose = false;
2289     }
2290 
2291     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
2292       return llvm::makeArrayRef(g_thread_trace_dump_info_options);
2293     }
2294 
2295     // Instance variables to hold the values for command options.
2296     bool m_verbose;
2297   };
2298 
2299   bool DoExecute(Args &command, CommandReturnObject &result) override {
2300     Target &target = m_exe_ctx.GetTargetRef();
2301     result.GetOutputStream().Format("Trace technology: {0}\n",
2302                                     target.GetTrace()->GetPluginName());
2303     return CommandObjectIterateOverThreads::DoExecute(command, result);
2304   }
2305 
2306   CommandObjectTraceDumpInfo(CommandInterpreter &interpreter)
2307       : CommandObjectIterateOverThreads(
2308             interpreter, "thread trace dump info",
2309             "Dump the traced information for one or more threads.  If no "
2310             "threads are specified, show the current thread.  Use the "
2311             "thread-index \"all\" to see all threads.",
2312             nullptr,
2313             eCommandRequiresProcess | eCommandTryTargetAPILock |
2314                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
2315                 eCommandProcessMustBeTraced) {}
2316 
2317   ~CommandObjectTraceDumpInfo() override = default;
2318 
2319   Options *GetOptions() override { return &m_options; }
2320 
2321 protected:
2322   bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override {
2323     const TraceSP &trace_sp = m_exe_ctx.GetTargetSP()->GetTrace();
2324     ThreadSP thread_sp =
2325         m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2326     trace_sp->DumpTraceInfo(*thread_sp, result.GetOutputStream(),
2327                             m_options.m_verbose);
2328     return true;
2329   }
2330 
2331   CommandOptions m_options;
2332 };
2333 
2334 // CommandObjectMultiwordTraceDump
2335 class CommandObjectMultiwordTraceDump : public CommandObjectMultiword {
2336 public:
2337   CommandObjectMultiwordTraceDump(CommandInterpreter &interpreter)
2338       : CommandObjectMultiword(
2339             interpreter, "dump",
2340             "Commands for displaying trace information of the threads "
2341             "in the current process.",
2342             "thread trace dump <subcommand> [<subcommand objects>]") {
2343     LoadSubCommand(
2344         "instructions",
2345         CommandObjectSP(new CommandObjectTraceDumpInstructions(interpreter)));
2346     LoadSubCommand(
2347         "info", CommandObjectSP(new CommandObjectTraceDumpInfo(interpreter)));
2348   }
2349   ~CommandObjectMultiwordTraceDump() override = default;
2350 };
2351 
2352 // CommandObjectMultiwordTrace
2353 class CommandObjectMultiwordTrace : public CommandObjectMultiword {
2354 public:
2355   CommandObjectMultiwordTrace(CommandInterpreter &interpreter)
2356       : CommandObjectMultiword(
2357             interpreter, "trace",
2358             "Commands for operating on traces of the threads in the current "
2359             "process.",
2360             "thread trace <subcommand> [<subcommand objects>]") {
2361     LoadSubCommand("dump", CommandObjectSP(new CommandObjectMultiwordTraceDump(
2362                                interpreter)));
2363     LoadSubCommand("start",
2364                    CommandObjectSP(new CommandObjectTraceStart(interpreter)));
2365     LoadSubCommand("stop",
2366                    CommandObjectSP(new CommandObjectTraceStop(interpreter)));
2367     LoadSubCommand("export",
2368                    CommandObjectSP(new CommandObjectTraceExport(interpreter)));
2369   }
2370 
2371   ~CommandObjectMultiwordTrace() override = default;
2372 };
2373 
2374 // CommandObjectMultiwordThread
2375 
2376 CommandObjectMultiwordThread::CommandObjectMultiwordThread(
2377     CommandInterpreter &interpreter)
2378     : CommandObjectMultiword(interpreter, "thread",
2379                              "Commands for operating on "
2380                              "one or more threads in "
2381                              "the current process.",
2382                              "thread <subcommand> [<subcommand-options>]") {
2383   LoadSubCommand("backtrace", CommandObjectSP(new CommandObjectThreadBacktrace(
2384                                   interpreter)));
2385   LoadSubCommand("continue",
2386                  CommandObjectSP(new CommandObjectThreadContinue(interpreter)));
2387   LoadSubCommand("list",
2388                  CommandObjectSP(new CommandObjectThreadList(interpreter)));
2389   LoadSubCommand("return",
2390                  CommandObjectSP(new CommandObjectThreadReturn(interpreter)));
2391   LoadSubCommand("jump",
2392                  CommandObjectSP(new CommandObjectThreadJump(interpreter)));
2393   LoadSubCommand("select",
2394                  CommandObjectSP(new CommandObjectThreadSelect(interpreter)));
2395   LoadSubCommand("until",
2396                  CommandObjectSP(new CommandObjectThreadUntil(interpreter)));
2397   LoadSubCommand("info",
2398                  CommandObjectSP(new CommandObjectThreadInfo(interpreter)));
2399   LoadSubCommand("exception", CommandObjectSP(new CommandObjectThreadException(
2400                                   interpreter)));
2401   LoadSubCommand("siginfo",
2402                  CommandObjectSP(new CommandObjectThreadSiginfo(interpreter)));
2403   LoadSubCommand("step-in",
2404                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2405                      interpreter, "thread step-in",
2406                      "Source level single step, stepping into calls.  Defaults "
2407                      "to current thread unless specified.",
2408                      nullptr, eStepTypeInto, eStepScopeSource)));
2409 
2410   LoadSubCommand("step-out",
2411                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2412                      interpreter, "thread step-out",
2413                      "Finish executing the current stack frame and stop after "
2414                      "returning.  Defaults to current thread unless specified.",
2415                      nullptr, eStepTypeOut, eStepScopeSource)));
2416 
2417   LoadSubCommand("step-over",
2418                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2419                      interpreter, "thread step-over",
2420                      "Source level single step, stepping over calls.  Defaults "
2421                      "to current thread unless specified.",
2422                      nullptr, eStepTypeOver, eStepScopeSource)));
2423 
2424   LoadSubCommand("step-inst",
2425                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2426                      interpreter, "thread step-inst",
2427                      "Instruction level single step, stepping into calls.  "
2428                      "Defaults to current thread unless specified.",
2429                      nullptr, eStepTypeTrace, eStepScopeInstruction)));
2430 
2431   LoadSubCommand("step-inst-over",
2432                  CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2433                      interpreter, "thread step-inst-over",
2434                      "Instruction level single step, stepping over calls.  "
2435                      "Defaults to current thread unless specified.",
2436                      nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
2437 
2438   LoadSubCommand(
2439       "step-scripted",
2440       CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2441           interpreter, "thread step-scripted",
2442           "Step as instructed by the script class passed in the -C option.  "
2443           "You can also specify a dictionary of key (-k) and value (-v) pairs "
2444           "that will be used to populate an SBStructuredData Dictionary, which "
2445           "will be passed to the constructor of the class implementing the "
2446           "scripted step.  See the Python Reference for more details.",
2447           nullptr, eStepTypeScripted, eStepScopeSource)));
2448 
2449   LoadSubCommand("plan", CommandObjectSP(new CommandObjectMultiwordThreadPlan(
2450                              interpreter)));
2451   LoadSubCommand("trace",
2452                  CommandObjectSP(new CommandObjectMultiwordTrace(interpreter)));
2453 }
2454 
2455 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;
2456