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