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