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