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