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